diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index bfdf0b82..70a86128 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -38,6 +38,7 @@ import '../features/artifacts/domain/artifact_record.dart'; import '../features/artifacts/ui/artifact_viewer_page.dart'; import '../features/artifacts/domain/gallery_navigation.dart'; import '../features/search/domain/search_target.dart'; +import '../features/settings/design_quick_switch.dart'; import '../features/settings/settings_screen.dart'; import '../features/settings/settings_store.dart'; import '../features/walkthrough/first_run_walkthrough.dart'; @@ -915,6 +916,9 @@ class _PipelinesAppState extends State if (!_chatRuntime.quickSwitch.toggle()) _focusOpenChatComposer(); } + /// Alt+L: the design switcher, over whatever is shown. + final DesignQuickSwitchToggle _designSwitch = DesignQuickSwitchToggle(); + /// Alt+N / Alt+J: the shell has shown Chat; once it has built (a first /// visit mounts the chat screen), the chat screen acts. void _chatAction(ShellChatAction action) { @@ -1191,6 +1195,7 @@ class _PipelinesAppState extends State onOpenChat: _focusOpenChatComposer, onChatQuickSwitch: _toggleChatQuickSwitch, onChatAction: _chatAction, + onDesignSwitch: _designSwitch.toggle, destinationBodies: { AppDestination.pipelines: (_) => FirstRunWalkthroughGate( store: _walkthroughStore, diff --git a/app/lib/application/pipelines_root.dart b/app/lib/application/pipelines_root.dart index 8027da11..0694a204 100644 --- a/app/lib/application/pipelines_root.dart +++ b/app/lib/application/pipelines_root.dart @@ -18,7 +18,6 @@ import '../features/settings/settings_store.dart'; import '../ui/scale/ui_scale.dart'; import '../ui/theme/app_design_controller.dart'; import '../ui/theme/app_font_controller.dart'; -import '../ui/theme/app_theme.dart'; import 'detached/detached_app.dart'; import 'detached/detached_route.dart'; import 'pipelines_app.dart'; @@ -322,7 +321,9 @@ class _PipelinesRootState extends State { child: Directionality( textDirection: TextDirection.ltr, child: Theme( - data: appLightTheme(), + // The device's design (Terminal until one is chosen), so the + // spinner does not flash another look before the app. + data: AppDesignController.instance.design.light(), child: const Center(child: CircularProgressIndicator()), ), ), diff --git a/app/lib/features/chat/chat_pane_content.dart b/app/lib/features/chat/chat_pane_content.dart index 0982cb43..a5a7a352 100644 --- a/app/lib/features/chat/chat_pane_content.dart +++ b/app/lib/features/chat/chat_pane_content.dart @@ -24,6 +24,7 @@ class ChatPanePlacement { this.pasteTarget = false, this.ownsPasteWhenFocused = false, this.paneControls, + this.leadingControl, this.paneCommands, this.onComposerFocus, this.onNextChat, @@ -54,6 +55,10 @@ class ChatPanePlacement { /// The pane menu's choices, built in the pane's own context. final List Function(BuildContext paneContext)? paneControls; + /// The bar's leading control where it shows no Back, built in the pane's + /// own context; null for none. + final Widget? Function(BuildContext paneContext)? leadingControl; + /// Choices the chat list hands to this chat's conversation to run. final ChatPaneCommands? paneCommands; final VoidCallback? onComposerFocus; @@ -117,6 +122,7 @@ Widget buildChatPaneContent({ ownsPasteWhenFocused: placement.ownsPasteWhenFocused, showBackButton: placement.showBackButton, paneControls: placement.paneControls?.call(context) ?? const [], + leadingControl: placement.leadingControl?.call(context), paneCommands: placement.paneCommands, onComposerFocus: placement.onComposerFocus, onComposerReady: (composer) => diff --git a/app/lib/features/chat/chat_screen_list_toggle.dart b/app/lib/features/chat/chat_screen_list_toggle.dart new file mode 100644 index 00000000..89489b3d --- /dev/null +++ b/app/lib/features/chat/chat_screen_list_toggle.dart @@ -0,0 +1,62 @@ +part of 'screen.dart'; + +/// Hiding the wide layout's chat list entirely (Ctrl+B, the pane menu, the +/// list's own bar), and the button that brings it back. +mixin _ChatScreenListToggle on State { + ChatComposerFocusRequests get _composerFocus; + ChatWorkspaceController get _workspace; + + late final ChatListHiddenController _listHidden = + widget.listHidden ?? ChatListHiddenController.instance; + + /// Whether the list is hidden beside an open chat. With no chat open the + /// list is the page, so it always shows. + bool _listHiddenBeside(String? selected) => + selected != null && _listHidden.value; + + void _bindListHidden() { + _listHidden.addListener(_listHiddenChanged); + unawaited(_listHidden.restore()); + } + + void _unbindListHidden() => _listHidden.removeListener(_listHiddenChanged); + + void _listHiddenChanged() { + if (mounted) setState(() {}); + } + + /// Shows or hides the list. Hiding gives the keyboard to the active chat, + /// since the list (and anything focused in it) goes away. + void _toggleChatList() { + final hiding = !_listHidden.value; + _listHidden.toggle(); + final active = _workspace.activePane?.sessionId; + if (hiding && active != null) _composerFocus.request(active); + } + + /// The pane menu's toggle, naming its shortcut. + ChatBarAction _chatListToggleAction() => ChatBarAction( + identifier: 'chat-list-toggle', + label: chatListToggleLabel(_listHidden.value), + onPressed: _toggleChatList, + materialIcon: _listHidden.value ? Icons.menu : Icons.menu_open, + ); + + /// The top bar's way back to a hidden list, at the start of the top left + /// pane's bar (the one beside where the list was); null elsewhere. + Widget? _showChatListButton(BuildContext paneContext, String? selected) { + if (!_listHiddenBeside(selected) || !showsListBesideDetail(context)) { + return null; + } + final scope = ChatWorkspacePaneScope.maybeOf(paneContext); + if (scope != null && (scope.leftEdgeShared || scope.topEdgeShared)) { + return null; + } + return IconButton( + key: const Key('chat-show-list'), + tooltip: chatListToggleLabel(true), + onPressed: _toggleChatList, + icon: const Icon(Icons.menu), + ); + } +} diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index e1e647f2..46de2235 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -12,6 +12,7 @@ mixin _ChatScreenWorkspace on State { void _back(); void _openRouted(String id); bool get _pageOpen; + void _toggleChatList(); Widget _thread(ChatWorkspacePane pane); ChatSidebarMode _sidebarMode = ChatSidebarMode.expanded; @@ -558,6 +559,7 @@ mixin _ChatScreenWorkspace on State { final id = _workspace.activePane?.sessionId; if (id != null) _paneCommands.request(id, ChatPaneCommand.files); }, + onToggleList: _toggleChatList, enabled: () => _workspaceVisible && _workspace.paneCount > 0 && diff --git a/app/lib/features/chat/conversation/chat_composer_bar.dart b/app/lib/features/chat/conversation/chat_composer_bar.dart index 863ea02d..415dc12c 100644 --- a/app/lib/features/chat/conversation/chat_composer_bar.dart +++ b/app/lib/features/chat/conversation/chat_composer_bar.dart @@ -1394,12 +1394,10 @@ class _ChatComposerBarState extends State { child: IconButton.filled( onLongPress: open, key: const Key('chat-composer-primary'), - style: tinted == null - ? null - : IconButton.styleFrom( - backgroundColor: tinted.primary, - foregroundColor: tinted.onPrimary, - ), + style: chatSendButtonStyle( + background: tinted?.primary, + foreground: tinted?.onPrimary, + ), onPressed: enabled ? press : null, icon: const Icon(Icons.arrow_upward), ), diff --git a/app/lib/features/chat/conversation/chat_send_usage_ring.dart b/app/lib/features/chat/conversation/chat_send_usage_ring.dart index 27f7e7f9..b190dcf2 100644 --- a/app/lib/features/chat/conversation/chat_send_usage_ring.dart +++ b/app/lib/features/chat/conversation/chat_send_usage_ring.dart @@ -132,15 +132,23 @@ class _ChatSendUsageRingState extends State { } } -/// The filled send button's visible circle: a Material 3 icon button's 40 -/// logical pixels adjusted by its visual density, inside a target that may -/// be padded beyond it. -double chatSendButtonDiameter(BuildContext context) { - final density = - IconButtonTheme.of(context).style?.visualDensity ?? - Theme.of(context).visualDensity; - return 40 + density.baseSizeAdjustment.dx; -} +/// The send button's visible size in every design: the composer pins it +/// ([chatSendButtonStyle]), so the ring's gap is the same everywhere. +const double chatSendButtonSize = 40; + +/// The send button's fixed size, whatever the design's density. +ButtonStyle chatSendButtonStyle({Color? background, Color? foreground}) => + IconButton.styleFrom( + backgroundColor: background, + foregroundColor: foreground, + fixedSize: const Size.square(chatSendButtonSize), + minimumSize: const Size.square(chatSendButtonSize), + maximumSize: const Size.square(chatSendButtonSize), + padding: EdgeInsets.zero, + ); + +/// The filled send button's visible size. +double chatSendButtonDiameter(BuildContext context) => chatSendButtonSize; /// The ring: a faint full track and the used arc clockwise from the top, a /// hairline gap outside the button's circle of diameter [circle], centred @@ -164,7 +172,10 @@ class ChatUsageRingPainter extends CustomPainter { final double? cornerRadius; static const double stroke = 2; - static const double gap = 1; + + /// A clear gap between the button and the ring, so the ring reads as its + /// own feature. + static const double gap = 3; /// The ring's centre-line radius. double get radius => circle / 2 + gap + stroke / 2; diff --git a/app/lib/features/chat/conversation/chat_thread_header.dart b/app/lib/features/chat/conversation/chat_thread_header.dart index 8ceeec52..fc6d090f 100644 --- a/app/lib/features/chat/conversation/chat_thread_header.dart +++ b/app/lib/features/chat/conversation/chat_thread_header.dart @@ -50,6 +50,7 @@ class ChatThreadHeader extends StatelessWidget { this.moreActions = const [], this.chatColor, this.identity, + this.leading, }); final String title; @@ -77,6 +78,10 @@ class ChatThreadHeader extends StatelessWidget { /// The chat's identity avatar, shown in the title on a phone. final Widget? identity; + /// A control at the bar's leading edge where there is no Back: the wide + /// layout's Show chat list while the list is hidden. + final Widget? leading; + @override Widget build(BuildContext context) { final tint = chatBarTintOf(context, chatColor); @@ -125,7 +130,7 @@ class ChatThreadHeader extends StatelessWidget { key: const Key('chat-back'), onPressed: onBack, ) - : null, + : leading, title: !showTitle ? '' : (title.isEmpty ? 'Chat' : title), titleLeading: showTitle ? identity : null, subtitle: showTitle ? ServerContext.metadata(context, folder) : null, diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index c7d69d59..fba71e0c 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -141,6 +141,7 @@ class ChatThreadView extends StatefulWidget { this.paneCommands, this.onComposerFocus, this.sidebarControl, + this.leadingControl, this.showBackButton, this.useNativeBack = false, this.pasteTarget = true, @@ -159,6 +160,9 @@ class ChatThreadView extends StatefulWidget { final ChatPaneCommands? paneCommands; final VoidCallback? onComposerFocus; final Widget? sidebarControl; + + /// The header's leading control where it shows no Back (Show chat list). + final Widget? leadingControl; final bool? showBackButton; final bool useNativeBack; final bool pasteTarget; @@ -1682,6 +1686,7 @@ class _ChatThreadViewState extends State with ChatFindHost { ? null : ChatSessionAvatar(session: session, selected: true), onInfo: _openInfo, + leading: widget.leadingControl, showTitle: !inWindow, showBack: canGoBack, // A pushed page keeps the platform's stock Back (pop this route); a diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index 8786098b..80468ee0 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -51,6 +51,7 @@ import 'stack/mobile_chat_navigation.dart'; import 'workspace/chat_center_stage_action.dart'; import 'workspace/chat_center_stage_controller.dart'; import 'workspace/chat_center_stage_keys.dart'; +import 'workspace/chat_list_hidden_controller.dart'; import 'workspace/chat_pane_move_actions.dart'; import 'workspace/chat_pane_move_shortcuts.dart'; import 'workspace/chat_workspace_entrance.dart'; @@ -73,6 +74,7 @@ part 'chat_screen_attention.dart'; part 'chat_screen_float.dart'; part 'chat_screen_pane_menu.dart'; part 'chat_screen_keys.dart'; +part 'chat_screen_list_toggle.dart'; part 'chat_screen_quick_switch.dart'; part 'chat_screen_stack.dart'; part 'chat_screen_stack_groups.dart'; @@ -99,6 +101,7 @@ class ChatScreen extends StatefulWidget { this.persistWorkspace = false, this.runtime, this.windows, + this.listHidden, }); final ApiGateway gateway; @@ -112,6 +115,10 @@ class ChatScreen extends StatefulWidget { /// float). final ChatWindows? windows; + /// Whether a wide layout hides its chat list beside an open chat; the + /// device's own choice ([ChatListHiddenController.instance]) when null. + final ChatListHiddenController? listHidden; + /// The chat session the current route names, or null for the list. final String? initialSessionId; @@ -137,7 +144,8 @@ class _ChatScreenState extends State _ChatScreenQuickSwitch, _ChatScreenAttention, _ChatScreenStackGroups, - _ChatScreenStack { + _ChatScreenStack, + _ChatScreenListToggle { /// The chats' shared state: the list, opened rows, accepted models, /// transcript positions and caches (see [ChatRuntime]). @override @@ -178,6 +186,7 @@ class _ChatScreenState extends State _bindWindows(); _bindQuickSwitch(); _bindAttention(); + _bindListHidden(); final initial = widget.initialSessionId; if (initial != null && initial.isNotEmpty) { _workspace.open(initial); @@ -487,6 +496,7 @@ class _ChatScreenState extends State _unbindWindows(); _unbindQuickSwitch(); _unbindAttention(); + _unbindListHidden(); _workspace.removeListener(_workspaceChanged); _workspace.dispose(); _sessions.removeListener(_nextChanged); @@ -523,12 +533,16 @@ class _ChatScreenState extends State showBackButton: _page.open || !showsListBesideDetail(context), paneCommands: _paneCommands, onComposerFocus: () => _composerFocus.request(selected), + leadingControl: (paneContext) => + _showChatListButton(paneContext, _selected), paneControls: (paneContext) => [ ChatBarAction( label: 'Add chat pane', onPressed: () => _addPane(paneContext), materialIcon: Icons.add_box_outlined, ), + if (showsListBesideDetail(context) && !_page.open) + _chatListToggleAction(), if (_workspace.paneCount > 1 && showsListBesideDetail(context)) chatCenterStageAction(ChatCenterStageController.instance), ...chatPaneMoveActions( @@ -595,8 +609,10 @@ class _ChatScreenState extends State publishShellBar: (selected == null || !beside || - _sidebarMode == ChatSidebarMode.expanded) && + (_sidebarMode == ChatSidebarMode.expanded && + !_listHiddenBeside(selected))) && (beside || !_usedWorkspace || selected == null), + onHideList: beside && selected != null ? _toggleChatList : null, ); final fullList = ContainerTransformScope( sources: _rowSources, @@ -644,11 +660,15 @@ class _ChatScreenState extends State ); } return ShellBar( - active: selected != null && _sidebarMode != ChatSidebarMode.expanded, + active: + selected != null && + (_sidebarMode != ChatSidebarMode.expanded || + _listHiddenBeside(selected)), barless: true, hideNavigation: true, child: ListDetailPanes( list: list, + listHidden: _listHiddenBeside(selected), compactListWidth: selected == null ? null : ChatCompactSidebar.width, onListCompactChanged: selected == null ? null diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart index 76291a84..7e49ea09 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -25,6 +25,7 @@ import 'create_chat_dialog.dart'; import 'rename_chat_dialog.dart'; import 'session_actions.dart'; import 'session_pane_menu.dart'; +import '../../workspace/chat_list_hidden_controller.dart'; /// Browses server-owned sessions. Opening a row is read-only at this layer. class ChatSessionsScreen extends StatefulWidget { @@ -47,6 +48,7 @@ class ChatSessionsScreen extends StatefulWidget { this.visibleSessionIds = const {}, this.publishShellBar, this.folds, + this.onHideList, }); final ApiGateway gateway; final void Function(JsonMap session) onOpen; @@ -87,6 +89,10 @@ class ChatSessionsScreen extends StatefulWidget { /// ready without pretending its open conversation is unread/inactive. final bool? publishShellBar; + /// Hides the list beside the open chat (the wide layout's Hide chat + /// list); null offers no such action. + final VoidCallback? onHideList; + /// Overrides the device-local hidden/read store in tests. final ChatSessionLocalStore? localStore; @@ -440,6 +446,14 @@ class ChatSessionsScreenState extends State { materialIcon: Icons.refresh, ), ?terminal, + if (widget.onHideList case final hide?) + ChatBarAction( + key: const Key('chat-hide-list'), + identifier: 'chat-hide-list', + label: chatListToggleLabel(false), + onPressed: hide, + materialIcon: Icons.menu_open, + ), ]; } } diff --git a/app/lib/features/chat/workspace/chat_center_stage_keys.dart b/app/lib/features/chat/workspace/chat_center_stage_keys.dart index 2a0b8f4f..2be2e5b7 100644 --- a/app/lib/features/chat/workspace/chat_center_stage_keys.dart +++ b/app/lib/features/chat/workspace/chat_center_stage_keys.dart @@ -6,9 +6,12 @@ import 'package:flutter/widgets.dart'; import '../../../ui/input/keyboard_owner.dart'; import '../windows/chat_window_tabs.dart'; import 'chat_center_stage_controller.dart'; +import 'chat_list_hidden_controller.dart'; void _ignoreFilesShortcut() {} +void _ignoreListShortcut() {} + /// Answers the center-stage chord before any focused widget sees it, so it /// works from the composer, the sidebar or a toolbar, and the focused field /// never types it. Handling the app-owned chords also stops a browser's own @@ -24,6 +27,7 @@ class ChatCenterStageKeys extends StatefulWidget { required this.controller, required this.enabled, this.onToggleFiles = _ignoreFilesShortcut, + this.onToggleList = _ignoreListShortcut, required this.child, }); @@ -33,6 +37,9 @@ class ChatCenterStageKeys extends StatefulWidget { /// no popup or other destination over it. final bool Function() enabled; final VoidCallback onToggleFiles; + + /// Shows or hides the chat list (Ctrl+B, Cmd+B on Apple platforms). + final VoidCallback onToggleList; final Widget child; @override @@ -68,6 +75,15 @@ class _ChatCenterStageKeysState extends State { } return KeyEventResult.handled; } + if (chatListToggleShortcut(event, keyboard)) { + // Ctrl+B stays the terminal's (tmux's prefix, the shell's back a + // character) while it has the keyboard; Cmd+B works there too. + if (!chatCenterStageUsesCommand() && primaryFocusIsTypingSurface()) { + return KeyEventResult.ignored; + } + if (event is KeyDownEvent) widget.onToggleList(); + return KeyEventResult.handled; + } if (!chatCenterStageShortcut(event, keyboard)) { return KeyEventResult.ignored; } diff --git a/app/lib/features/chat/workspace/chat_list_hidden_controller.dart b/app/lib/features/chat/workspace/chat_list_hidden_controller.dart new file mode 100644 index 00000000..d7197937 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_list_hidden_controller.dart @@ -0,0 +1,121 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'chat_center_stage_controller.dart'; + +const chatListHiddenPreferenceKey = 'pipelines.chat.listHidden.v1'; + +abstract interface class ChatListHiddenStore { + Future load(); + Future save(bool hidden); +} + +class SharedChatListHiddenStore implements ChatListHiddenStore { + const SharedChatListHiddenStore(); + + @override + Future load() async { + try { + return (await SharedPreferences.getInstance()).getBool( + chatListHiddenPreferenceKey, + ); + } on Object { + return null; + } + } + + @override + Future save(bool hidden) async { + try { + return await (await SharedPreferences.getInstance()).setBool( + chatListHiddenPreferenceKey, + hidden, + ); + } on Object { + return false; + } + } +} + +/// An in-memory store for tests and fixtures. +class MemoryChatListHiddenStore implements ChatListHiddenStore { + MemoryChatListHiddenStore([this.hidden]); + + bool? hidden; + + @override + Future load() async => hidden; + + @override + Future save(bool hidden) async { + this.hidden = hidden; + return true; + } +} + +/// Whether a wide Chat screen hides its chat list entirely while a chat is +/// open, giving the open chats the whole width. Device-local, like center +/// stage: a presentation choice, not part of any server's layout. The +/// expanded or compact list comes back as it was when shown again. +class ChatListHiddenController extends ValueNotifier { + ChatListHiddenController({ChatListHiddenStore? store}) + : _store = store ?? const SharedChatListHiddenStore(), + super(false); + + static final instance = ChatListHiddenController(); + final ChatListHiddenStore _store; + int _revision = 0; + bool _restored = false; + + /// Reads the saved choice once, unless it was changed meanwhile. + Future restore() async { + if (_restored) return; + _restored = true; + final revision = _revision; + final saved = await _store.load(); + if (saved != null && revision == _revision) super.value = saved; + } + + /// An explicit choice, even of the current value, outranks a restore + /// still reading the stored one. + @override + set value(bool hidden) { + _revision++; + if (hidden == value) return; + super.value = hidden; + unawaited(_store.save(hidden)); + } + + void toggle() => value = !value; +} + +/// Whether [event] shows or hides the chat list: Ctrl+B (Cmd+B on Apple +/// platforms), as an editor's sidebar toggle. Repeats of a held chord match +/// too, so they are swallowed; only the first press toggles. +bool chatListToggleShortcut( + KeyEvent event, + HardwareKeyboard keyboard, { + TargetPlatform? platform, +}) { + if (event is KeyUpEvent || + event.physicalKey != PhysicalKeyboardKey.keyB || + keyboard.isShiftPressed || + keyboard.isAltPressed) { + return false; + } + return chatCenterStageUsesCommand(platform) + ? keyboard.isMetaPressed && !keyboard.isControlPressed + : keyboard.isControlPressed && !keyboard.isMetaPressed; +} + +/// The shortcut as this platform shows it, for menus and tooltips. +String chatListToggleShortcutLabel([TargetPlatform? platform]) => + chatCenterStageUsesCommand(platform) ? 'Cmd+B' : 'Ctrl+B'; + +/// The toggle's label, naming its keyboard shortcut. +String chatListToggleLabel(bool hidden, [TargetPlatform? platform]) => + '${hidden ? 'Show chat list' : 'Hide chat list'} ' + '(${chatListToggleShortcutLabel(platform)})'; diff --git a/app/lib/features/settings/design_quick_switch.dart b/app/lib/features/settings/design_quick_switch.dart new file mode 100644 index 00000000..dc533839 --- /dev/null +++ b/app/lib/features/settings/design_quick_switch.dart @@ -0,0 +1,272 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../ui/adaptive/app_popups.dart'; +import '../../ui/theme/app_design.dart'; +import '../../ui/theme/app_design_controller.dart'; +import '../chat/conversation/chat_quick_switch_keys.dart'; +import 'design_quick_switch_match.dart'; +import 'settings_design_section.dart'; + +/// Opens and closes the design switcher for the app-wide shortcut (Alt+L): +/// a second press while it is open closes it, as Alt+K does the chat +/// switcher. +class DesignQuickSwitchToggle { + DesignQuickSwitchToggle({AppDesignController? designs}) + : _designs = designs ?? AppDesignController.instance; + + final AppDesignController _designs; + ModalRoute? _route; + + bool get isOpen => _route?.isActive ?? false; + + void toggle(BuildContext context) { + final route = _route; + if (route != null && route.isActive) { + final navigator = route.navigator!; + route.isCurrent ? navigator.pop() : navigator.removeRoute(route); + _route = null; + return; + } + _route = showDesignQuickSwitch(context, designs: _designs); + } +} + +/// Shows the design switcher: the chat switcher's popup (a search field with +/// the keyboard, Ctrl+N / Ctrl+P and Down / Up to move, wrapping, Enter or a +/// click to choose, Esc to close) over every registered [AppDesign], with its +/// swatch and one-line summary, the current one marked and selected. +/// +/// Moving the selection previews that design app-wide at once +/// ([AppDesignController.preview], nothing stored); Enter or a click keeps it +/// ([AppDesignController.select]) and closing any other way returns to the +/// design the switcher opened with. The popup takes the app's theme rather +/// than the opener's, so it previews too. +ModalRoute showDesignQuickSwitch( + BuildContext context, { + AppDesignController? designs, +}) { + final controller = designs ?? AppDesignController.instance; + final navigator = Navigator.of(context, rootNavigator: true); + Widget content(BuildContext context) => + DesignQuickSwitch(designs: controller); + final ModalRoute route = usesDesktopPopups(context) + ? DialogRoute( + context: navigator.context, + barrierLabel: 'Close the design switcher', + builder: (context) => Dialog( + alignment: const Alignment(0, -0.6), + clipBehavior: Clip.antiAlias, + child: ConstrainedBox( + constraints: BoxConstraints( + maxWidth: 560, + maxHeight: MediaQuery.sizeOf(context).height * 0.7, + ), + child: content(context), + ), + ), + ) + : ModalBottomSheetRoute( + builder: content, + isScrollControlled: true, + showDragHandle: true, + useSafeArea: true, + barrierLabel: 'Close the design switcher', + modalBarrierColor: Theme.of( + context, + ).bottomSheetTheme.modalBarrierColor, + ); + navigator.push(route).then((design) { + if (design == null) { + controller.preview(null); + } else { + controller.select(design); + } + }); + return route; +} + +/// The switcher's content: the field and the matching designs. +class DesignQuickSwitch extends StatefulWidget { + const DesignQuickSwitch({super.key, required this.designs}); + + final AppDesignController designs; + + @override + State createState() => _DesignQuickSwitchState(); +} + +class _DesignQuickSwitchState extends State { + final _query = TextEditingController(); + final _rowKeys = {}; + + /// The stored design when the switcher opened: marked, and what closing + /// without a choice returns to. + late final AppDesign _current = widget.designs.chosen; + List _shown = AppDesign.values; + late int _selected = _shown.indexOf(_current); + + @override + void dispose() { + _query.dispose(); + super.dispose(); + } + + AppDesign? get _selection => + _shown.isEmpty ? null : _shown[_selected.clamp(0, _shown.length - 1)]; + + /// With no query the current design is selected; with one, the best match. + void _queryChanged(String query) { + setState(() { + _shown = designQuickSwitchMatches(AppDesign.values, query); + _selected = query.trim().isEmpty ? _shown.indexOf(_current) : 0; + }); + widget.designs.preview(_selection ?? _current); + } + + /// Moves the selection [step] rows, wrapping, previews it and scrolls it + /// into view at the edge it moved towards. + void _step(int step) { + if (_shown.isEmpty) return; + setState(() => _selected = (_selected + step) % _shown.length); + final design = _selection!; + widget.designs.preview(design); + final policy = step < 0 + ? ScrollPositionAlignmentPolicy.keepVisibleAtStart + : ScrollPositionAlignmentPolicy.keepVisibleAtEnd; + WidgetsBinding.instance.addPostFrameCallback((_) { + final row = _rowKeys[design]?.currentContext; + if (row != null) Scrollable.ensureVisible(row, alignmentPolicy: policy); + }); + } + + void _choose([AppDesign? design]) { + final chosen = design ?? _selection; + if (chosen != null) Navigator.of(context).pop(chosen); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final field = Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Focus( + canRequestFocus: false, + skipTraversal: true, + onKeyEvent: (_, event) => chatQuickSwitchKey( + event, + HardwareKeyboard.instance, + onStep: _step, + onChoose: _choose, + ), + child: TextField( + key: const Key('design-quick-switch-field'), + controller: _query, + autofocus: true, + onChanged: _queryChanged, + textInputAction: TextInputAction.go, + decoration: const InputDecoration( + hintText: 'Switch design', + prefixIcon: Icon(Icons.search), + border: OutlineInputBorder(), + isDense: true, + ), + ), + ), + ); + final Widget list = _shown.isEmpty + ? const Padding( + padding: EdgeInsets.all(24), + child: Text( + 'No designs match.', + key: Key('design-quick-switch-empty'), + textAlign: TextAlign.center, + ), + ) + : SingleChildScrollView( + padding: const EdgeInsets.only(bottom: 8), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final (index, design) in _shown.indexed) + DesignQuickSwitchRow( + key: _rowKeys.putIfAbsent(design, GlobalKey.new), + design: design, + brightness: theme.brightness, + selected: index == _selected, + current: design == _current, + onTap: () => _choose(design), + ), + ], + ), + ); + return Semantics( + label: 'Switch design', + explicitChildNodes: true, + child: Material( + type: MaterialType.transparency, + child: Padding( + padding: EdgeInsets.only( + bottom: MediaQuery.viewInsetsOf(context).bottom, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + field, + Flexible(child: list), + ], + ), + ), + ), + ); + } +} + +/// One design in the switcher: its swatch, name and summary, and a check on +/// the [current] one. The selected row takes the selection fill, as in the +/// chat switcher. +class DesignQuickSwitchRow extends StatelessWidget { + const DesignQuickSwitchRow({ + super.key, + required this.design, + required this.brightness, + required this.selected, + required this.current, + required this.onTap, + }); + + final AppDesign design; + final Brightness brightness; + final bool selected; + final bool current; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return ListTile( + key: Key('design-quick-switch-row-${design.id}'), + selected: selected, + selectedTileColor: scheme.secondaryContainer, + selectedColor: scheme.onSecondaryContainer, + visualDensity: VisualDensity.compact, + leading: DesignSwatchPreview(swatch: design.swatch(brightness)), + title: Text(design.label, maxLines: 1, overflow: TextOverflow.ellipsis), + subtitle: Text( + design.description, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + trailing: current + ? Icon( + Icons.check, + key: const Key('design-quick-switch-current'), + color: selected ? null : scheme.primary, + semanticLabel: 'Current design', + ) + : null, + onTap: onTap, + ); + } +} diff --git a/app/lib/features/settings/design_quick_switch_match.dart b/app/lib/features/settings/design_quick_switch_match.dart new file mode 100644 index 00000000..0af613b5 --- /dev/null +++ b/app/lib/features/settings/design_quick_switch_match.dart @@ -0,0 +1,46 @@ +import '../../ui/theme/app_design.dart'; + +/// [designs] narrowed to [query] and ranked, best first, for the design +/// switcher (Alt+L). +/// +/// Every whitespace-separated word of the query must occur, ignoring case, in +/// the design's name or its one-line description. A word ranks by where it +/// matched: the start of the name, anywhere in the name, the start of a word +/// in the description, anywhere in it. A design's rank is the sum over the +/// query's words; equal ranks keep [designs]' order (the registry's). +List designQuickSwitchMatches( + List designs, + String query, +) { + final words = query.toLowerCase().split(RegExp(r'\s+')) + ..removeWhere((word) => word.isEmpty); + if (words.isEmpty) return designs; + final ranked = <({int rank, int index, AppDesign design})>[]; + for (final (index, design) in designs.indexed) { + final name = design.label.toLowerCase(); + final description = design.description.toLowerCase(); + var rank = 0; + for (final word in words) { + final tier = name.startsWith(word) + ? 0 + : name.contains(word) + ? 1 + : RegExp( + '(^|[^\\p{L}\\p{N}])${RegExp.escape(word)}', + unicode: true, + ).hasMatch(description) + ? 2 + : description.contains(word) + ? 3 + : null; + if (tier == null) { + rank = -1; + break; + } + rank += tier; + } + if (rank >= 0) ranked.add((rank: rank, index: index, design: design)); + } + ranked.sort((a, b) => a.rank != b.rank ? a.rank - b.rank : a.index - b.index); + return [for (final hit in ranked) hit.design]; +} diff --git a/app/lib/features/settings/keyboard_shortcuts_registry.dart b/app/lib/features/settings/keyboard_shortcuts_registry.dart index 592b7c7c..5161df77 100644 --- a/app/lib/features/settings/keyboard_shortcuts_registry.dart +++ b/app/lib/features/settings/keyboard_shortcuts_registry.dart @@ -2,12 +2,14 @@ import 'package:flutter/foundation.dart'; import '../chat/workspace/chat_center_stage_controller.dart'; import '../chat/workspace/chat_float_shortcut.dart'; +import '../chat/workspace/chat_list_hidden_controller.dart'; import '../terminal/terminal_shortcuts.dart'; import '../../shell/detached/detached_window_scope.dart'; import '../../shell/windows/window_shortcuts.dart'; import '../../shell/shell_chat_actions_shortcut.dart'; import '../../shell/shell_chat_shortcut.dart'; import '../../shell/shell_cheatsheet_shortcut.dart'; +import '../../shell/shell_design_shortcut.dart'; import '../../shell/shell_runs_pipelines_shortcut.dart'; import '../../shell/shell_search_shortcut_labels.dart'; @@ -101,6 +103,13 @@ class KeyboardShortcutRegistry { ? 'From another destination: shows the open chat and focuses its message input. On Chat it opens the chat switcher. The browser may reserve Ctrl+K.' : 'From another destination: shows the open chat and focuses its message input. On Chat it opens the chat switcher. In the terminal Ctrl+K stays kill-line; ${_apple ? 'Option+K and Cmd+K still open' : 'Alt+K still opens'} Chat.', ), + KeyboardShortcutEntry( + group: KeyboardShortcutGroup.navigation, + action: 'Switch design', + keys: shellDesignShortcutLabel(platform), + caveat: + 'From any destination: every design with its preview, the current one marked. Type to filter, Ctrl+N or Down and Ctrl+P or Up to move (the app shows the selected design at once), Enter to keep it, Esc or the shortcut again to go back to the design you had. In the terminal the key goes to the terminal.${web ? ' A browser tab keeps Ctrl+N (new window) for itself; use Down, or the installed app.' : ''}', + ), const KeyboardShortcutEntry( group: KeyboardShortcutGroup.navigation, action: 'Switch between Runs and Pipelines', @@ -162,6 +171,14 @@ class KeyboardShortcutRegistry { action: 'Toggle Files', keys: _apple ? 'Cmd+E' : 'Ctrl+E', ), + KeyboardShortcutEntry( + group: KeyboardShortcutGroup.chat, + action: 'Show or hide the chat list', + keys: chatListToggleShortcutLabel(platform), + caveat: _apple + ? 'Beside an open chat on a wide window.' + : 'Beside an open chat on a wide window. In the terminal Ctrl+B goes to the terminal.', + ), KeyboardShortcutEntry( group: KeyboardShortcutGroup.chat, action: 'Toggle Center Stage', diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart index 8bef446f..3e9d1324 100644 --- a/app/lib/shell/adaptive_shell.dart +++ b/app/lib/shell/adaptive_shell.dart @@ -16,6 +16,7 @@ import 'shell_chat_actions_shortcut.dart'; import 'shell_chat_shortcut.dart'; import 'shell_cheatsheet.dart'; import 'shell_cheatsheet_shortcut.dart'; +import 'shell_design_shortcut.dart'; import 'shell_list_shortcuts.dart'; import 'shell_runs_pipelines_shortcut.dart'; import 'shell_search_shortcut_labels.dart'; @@ -35,6 +36,7 @@ class AdaptiveShell extends StatefulWidget { this.onOpenChat, this.onChatQuickSwitch, this.onChatAction, + this.onDesignSwitch, this.attentionCount = 0, this.runningRunCount, this.listPaneWidthStore = const SharedPreferencesListPaneWidthStore(), @@ -84,6 +86,11 @@ class AdaptiveShell extends StatefulWidget { /// needing the operator. Null leaves both chords unhandled. final ValueChanged? onChatAction; + /// Runs on Alt+L (see [shellDesignShortcut]) from any destination: the host + /// toggles its design switcher, shown from the given context. Null leaves + /// the chord unhandled. + final ValueChanged? onDesignSwitch; + /// Runs needing the operator today, retained in the tab's accessible label. final int attentionCount; @@ -419,6 +426,11 @@ class _AdaptiveShellState extends State { } // A terminal keeps its keys (Escape, Ctrl+/, Ctrl+digits, Alt+N, Alt+J). if (primaryFocusIsTypingSurface()) return false; + final designSwitch = widget.onDesignSwitch; + if (designSwitch != null && shellDesignShortcut(event, keyboard)) { + if (event is KeyDownEvent) designSwitch(context); + return true; + } final chatAction = widget.onChatAction == null ? null : shellChatActionShortcut(event, keyboard); diff --git a/app/lib/shell/list_detail.dart b/app/lib/shell/list_detail.dart index ce992640..0e6f869f 100644 --- a/app/lib/shell/list_detail.dart +++ b/app/lib/shell/list_detail.dart @@ -3,6 +3,7 @@ import 'dart:math' as math; import 'package:flutter/material.dart'; import '../ui/adaptive/floating_bar_layout.dart'; +import '../ui/motion/motion.dart'; import 'detail_pane_navigator.dart'; import 'list_detail_policy.dart'; import 'list_pane_divider.dart'; @@ -99,6 +100,7 @@ class ListDetailPanes extends StatefulWidget { this.listWidthOverride, this.compactListWidth, this.onListCompactChanged, + this.listHidden = false, }); final Widget list; @@ -110,6 +112,10 @@ class ListDetailPanes extends StatefulWidget { /// The grab handle remains available at the rail edge to expand it again. final double? compactListWidth; final ValueChanged? onListCompactChanged; + + /// Whether the list is hidden entirely: it slides to zero width (at once + /// with reduced motion) and comes back at the width it had. + final bool listHidden; final Widget detail; /// Which item [detail] shows; selecting another item closes any page the @@ -120,13 +126,32 @@ class ListDetailPanes extends StatefulWidget { State createState() => _ListDetailPanesState(); } -class _ListDetailPanesState extends State { +class _ListDetailPanesState extends State + with SingleTickerProviderStateMixin { // Outside a shell (no [ListPaneWidthsScope]) the divider still drags; the // width lasts as long as the panes. ListPaneWidths? _ownWidths; + /// How far the list has slid away: 0 shown, 1 hidden. + late final AnimationController _hidden = AnimationController( + vsync: this, + value: widget.listHidden ? 1 : 0, + ); + + @override + void didUpdateWidget(ListDetailPanes oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.listHidden == oldWidget.listHidden) return; + _hidden.animateTo( + widget.listHidden ? 1 : 0, + duration: Motion.of(context, Motion.standard), + curve: Motion.curve, + ); + } + @override void dispose() { + _hidden.dispose(); _ownWidths?.dispose(); super.dispose(); } @@ -141,7 +166,7 @@ class _ListDetailPanesState extends State { final split = ShellBar.available(context); return ShellPaneSplit( child: ListenableBuilder( - listenable: widths, + listenable: Listenable.merge([widths, _hidden]), builder: (context, _) => LayoutBuilder( builder: (context, constraints) { final window = ShellRailScope.windowWidth(context); @@ -171,14 +196,19 @@ class _ListDetailPanesState extends State { preferred != null ? preferred.clamp(compactThreshold, normalBounds.max).toDouble() : listDetailListWidth(window, available, preferred); - final listWidth = (widget.listWidthOverride ?? normalWidth) + final shownWidth = (widget.listWidthOverride ?? normalWidth) .clamp(0.0, math.max(0.0, available - kDetailPaneMinWidth)) .toDouble(); + final hidden = _hidden.value; + final listWidth = shownWidth * (1 - hidden); final lineWidth = listWidth > 0 ? 1.0 : 0.0; final bodyWidth = math.max(0.0, available - lineWidth - listWidth); + // The list keeps its width while it slides, so it moves out + // rather than reflowing. final retainedWidth = widget.listWidthOverride == null - ? listWidth + ? shownWidth : math.max(normalWidth, kListPaneMinWidth); + final listGone = listWidth == 0 || widget.listHidden; void resize(double value) { widths.preview(key, value); widget.onListCompactChanged?.call(value < compactThreshold); @@ -225,9 +255,9 @@ class _ListDetailPanesState extends State { minWidth: retainedWidth, maxWidth: retainedWidth, child: ExcludeFocus( - excluding: listWidth == 0, + excluding: listGone, child: ExcludeSemantics( - excluding: listWidth == 0, + excluding: listGone, child: SizedBox.expand( key: const ValueKey('list-detail-list'), child: Semantics( @@ -257,7 +287,7 @@ class _ListDetailPanesState extends State { ), ], ), - if (bounds != null) + if (bounds != null && hidden == 0) PositionedDirectional( start: listWidth + 0.5 - kListPaneDividerGrabWidth / 2, top: 0, diff --git a/app/lib/shell/shell_design_shortcut.dart b/app/lib/shell/shell_design_shortcut.dart new file mode 100644 index 00000000..372c9e61 --- /dev/null +++ b/app/lib/shell/shell_design_shortcut.dart @@ -0,0 +1,35 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +/// Whether [event] opens or closes the design switcher: Alt+L (Option+L on +/// a Mac, L for look) with no other modifier, from any destination. Option+L +/// types a symbol (¬) on a Mac, so the key is matched by position as well. +/// Repeats of a held chord match too, so the caller can swallow them; only +/// the first press acts. +/// +/// The chord sits beside Alt+K (the chat switcher) and works the same way. +/// Alt+T (the terminal) and Alt+D (the browser's address bar) are taken, and +/// no Ctrl or Cmd chord is free for it: Ctrl+L and Cmd+L are the browser's +/// address bar and the terminal's clear screen, Ctrl+Alt+T and Ctrl+Alt+L +/// open a terminal and lock the screen on Linux desktops. No browser, +/// GNOME, KDE or macOS takes Alt+L. The terminal keeps it for readline +/// (downcase-word), so the caller leaves it to the terminal while it has the +/// keyboard. +bool shellDesignShortcut(KeyEvent event, HardwareKeyboard keyboard) { + if (event is KeyUpEvent || + !keyboard.isAltPressed || + keyboard.isControlPressed || + keyboard.isMetaPressed || + keyboard.isShiftPressed) { + return false; + } + return event.logicalKey == LogicalKeyboardKey.keyL || + event.physicalKey == PhysicalKeyboardKey.keyL; +} + +/// The chord as it reads on [platform], for the help page. +String shellDesignShortcutLabel([TargetPlatform? platform]) { + final target = platform ?? defaultTargetPlatform; + final apple = target == TargetPlatform.macOS || target == TargetPlatform.iOS; + return apple ? 'Option+L' : 'Alt+L'; +} diff --git a/app/lib/ui/adaptive/anchored_menu_layout.dart b/app/lib/ui/adaptive/anchored_menu_layout.dart new file mode 100644 index 00000000..d1db58d9 --- /dev/null +++ b/app/lib/ui/adaptive/anchored_menu_layout.dart @@ -0,0 +1,126 @@ +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +/// Places an anchored menu panel below its anchor, aligned to the anchor's +/// leading edge, or above it when it fits better there, and always inside +/// the app's safe area. +/// +/// [anchor] and the layout share one coordinate space: the overlay the menu +/// route fills. The system insets ([insets]: a status bar, a cutout, a +/// gesture bar) are therefore only bounds the panel stays inside, never an +/// offset. Wrapping the layout in a `SafeArea` shifted the panel down by the +/// top inset while the anchor stayed put, which on an unfolded foldable +/// opened a top bar's menus far below the bar. A hinge that splits the +/// screen ([avoid]) confines the panel to the anchor's side. +class AnchoredMenuLayout extends SingleChildLayoutDelegate { + AnchoredMenuLayout({ + required this.anchor, + required this.width, + this.insets = EdgeInsets.zero, + this.avoid = const [], + }); + + final Rect anchor; + final double width; + final EdgeInsets insets; + final List avoid; + + static const double margin = 8; + static const double gap = 4; + + /// Less room than this on both sides means the anchor is not a button but + /// a region (a pane's bar, a whole pane): the panel then opens over it, + /// from its top. + static const double minRoom = 200; + + /// Where the panel may go in an overlay of [size]. + Rect bounds(Size size) { + var screen = Offset.zero & size; + if (avoid.isNotEmpty) { + Rect? closest; + var best = double.infinity; + for (final candidate in DisplayFeatureSubScreen.subScreensInBounds( + screen, + avoid, + )) { + final distance = _distance(anchor.center, candidate); + if (distance < best) { + best = distance; + closest = candidate; + } + } + screen = closest ?? screen; + } + final inner = insets.deflateRect(screen).deflate(margin); + // An area too small for the insets and margins collapses, never inverts. + return Rect.fromLTRB( + inner.left, + inner.top, + math.max(inner.left, inner.right), + math.max(inner.top, inner.bottom), + ); + } + + static double _distance(Offset point, Rect rect) { + final dx = math.max( + 0.0, + math.max(rect.left - point.dx, point.dx - rect.right), + ); + final dy = math.max( + 0.0, + math.max(rect.top - point.dy, point.dy - rect.bottom), + ); + return math.sqrt(dx * dx + dy * dy); + } + + double _below(Rect area) => area.bottom - anchor.bottom - gap; + double _above(Rect area) => anchor.top - gap - area.top; + bool _over(Rect area) => _below(area) < minRoom && _above(area) < minRoom; + + @override + BoxConstraints getConstraintsForChild(BoxConstraints constraints) { + final area = bounds(constraints.biggest); + final below = _below(area); + final above = _above(area); + final double room; + if (_over(area)) { + room = area.bottom - anchor.top.clamp(area.top, area.bottom); + } else { + room = below >= minRoom || below >= above ? below : above; + } + final panelWidth = width.clamp(0.0, area.width); + return BoxConstraints( + minWidth: panelWidth, + maxWidth: panelWidth, + maxHeight: room.clamp(0.0, area.height), + ); + } + + @override + Offset getPositionForChild(Size size, Size childSize) { + final area = bounds(size); + final double top; + if (_over(area)) { + top = anchor.top + gap; + } else if (childSize.height <= _below(area)) { + top = anchor.bottom + gap; + } else { + top = anchor.top - gap - childSize.height; + } + final maxTop = math.max(area.top, area.bottom - childSize.height); + final maxLeft = math.max(area.left, area.right - childSize.width); + return Offset( + anchor.left.clamp(area.left, maxLeft), + top.clamp(area.top, maxTop), + ); + } + + @override + bool shouldRelayout(AnchoredMenuLayout oldDelegate) => + oldDelegate.anchor != anchor || + oldDelegate.width != width || + oldDelegate.insets != insets || + !listEquals(oldDelegate.avoid, avoid); +} diff --git a/app/lib/ui/adaptive/app_popups.dart b/app/lib/ui/adaptive/app_popups.dart index 95822bab..69705913 100644 --- a/app/lib/ui/adaptive/app_popups.dart +++ b/app/lib/ui/adaptive/app_popups.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import '../motion/motion.dart'; +import 'anchored_menu_layout.dart'; /// The narrowest app that gets desktop popups: the width where a list shows /// beside its open item (`kListDetailMinWidth`). @@ -157,9 +158,26 @@ class _AnchoredMenuRoute extends PopupRoute { Animation secondaryAnimation, ) { final colors = Theme.of(context).colorScheme; - return SafeArea( - child: CustomSingleChildLayout( - delegate: _AnchoredMenuLayout(anchor, width), + final media = MediaQuery.of(context); + // The anchor is in the overlay's coordinates, which this page fills: the + // system insets bound the panel but must not shift it (a SafeArea here + // opened menus an inset below their anchor on Android). The panel itself + // is clear of them, so content that pads itself for a bottom sheet + // (a SafeArea) adds nothing inside it. + return CustomSingleChildLayout( + delegate: AnchoredMenuLayout( + anchor: anchor, + width: width, + insets: + media.padding + EdgeInsets.only(bottom: media.viewInsets.bottom), + avoid: DisplayFeatureSubScreen.avoidBounds(media).toList(), + ), + child: MediaQuery.removePadding( + context: context, + removeLeft: true, + removeTop: true, + removeRight: true, + removeBottom: true, child: FadeTransition( opacity: CurvedAnimation(parent: animation, curve: Motion.curve), child: Semantics( @@ -196,74 +214,3 @@ class _AnchoredMenuRoute extends PopupRoute { ); } } - -/// Places the panel below its anchor, aligned to the anchor's leading edge, -/// or above it when it fits better there, and always inside the app. -class _AnchoredMenuLayout extends SingleChildLayoutDelegate { - _AnchoredMenuLayout(this.anchor, this.width); - - final Rect anchor; - final double width; - - static const double margin = 8; - static const double gap = 4; - - /// Less room than this on both sides means the anchor is not a button but - /// a region (a pane's bar, a whole pane): the panel then opens over it, - /// from its top. - static const double minRoom = 200; - - double _below(Size size) => size.height - anchor.bottom - gap - margin; - double _above() => anchor.top - gap - margin; - bool _over(Size size) => _below(size) < minRoom && _above() < minRoom; - - @override - BoxConstraints getConstraintsForChild(BoxConstraints constraints) { - final available = constraints.biggest; - final below = _below(available); - final above = _above(); - final double room; - if (_over(available)) { - room = - available.height - - anchor.top.clamp(margin, available.height) - - margin; - } else { - room = below >= minRoom || below >= above ? below : above; - } - final maxWidth = (available.width - 2 * margin).clamp(0.0, double.infinity); - return BoxConstraints( - minWidth: width.clamp(0.0, maxWidth), - maxWidth: width.clamp(0.0, maxWidth), - maxHeight: room.clamp(0.0, available.height - 2 * margin), - ); - } - - @override - Offset getPositionForChild(Size size, Size childSize) { - final double top; - if (_over(size)) { - top = anchor.top + gap; - } else if (childSize.height <= _below(size)) { - top = anchor.bottom + gap; - } else { - top = anchor.top - gap - childSize.height; - } - final maxTop = (size.height - margin - childSize.height).clamp( - margin, - double.infinity, - ); - final maxLeft = (size.width - margin - childSize.width).clamp( - margin, - double.infinity, - ); - return Offset( - anchor.left.clamp(margin, maxLeft), - top.clamp(margin, maxTop), - ); - } - - @override - bool shouldRelayout(_AnchoredMenuLayout oldDelegate) => - oldDelegate.anchor != anchor || oldDelegate.width != width; -} diff --git a/app/lib/ui/theme/app_design.dart b/app/lib/ui/theme/app_design.dart index e79519a3..99494e51 100644 --- a/app/lib/ui/theme/app_design.dart +++ b/app/lib/ui/theme/app_design.dart @@ -25,13 +25,15 @@ final Map<(AppDesign, Brightness, String?), ThemeData> _themes = {}; /// 3. give the theme an [AppDesignTokens] extension: set only the tokens it /// changes (corners, flat surfaces, frame, panel fill, transcript, /// composer and selected-row styles, reading type); every token defaults -/// to the Default look; +/// to the Classic look; /// 4. give it a [swatch] for the picker and say whether it [usesInterfaceFont]. /// 5. run the design budget (app/tool/perf/README.md) and keep it passing. /// Widgets read the tokens, so most surfaces follow without per-widget code. enum AppDesign { - /// The app's own Material look. - standard('default', 'Default', 'The app’s Material look.'), + /// The app's original Material look. Its stored id stays `default` (the + /// id it had when it was the default); the picker calls it Classic so it + /// does not read as "whatever the app starts with". + standard('default', 'Classic', 'The app’s original Material look.'), /// A terminal-style look: monospace text, near-black pages, thin frames /// and a transcript drawn as prompt and tool lines. @@ -60,12 +62,16 @@ enum AppDesign { /// The picker's one-line summary of the design. final String description; - /// The design stored as [id], or [standard] for an unknown or missing id. + /// The design a device has before it chooses one: Terminal. + static const AppDesign defaultDesign = terminal; + + /// The design stored as [id], or [defaultDesign] for an unknown or missing + /// id. A stored choice (Classic's `default` included) is kept. static AppDesign fromId(String? id) { for (final design in values) { if (design.id == id) return design; } - return standard; + return defaultDesign; } /// The design's light theme. [fontFamily] is the device's interface font; diff --git a/app/lib/ui/theme/app_design_controller.dart b/app/lib/ui/theme/app_design_controller.dart index 96a0eb0a..0dc9ed66 100644 --- a/app/lib/ui/theme/app_design_controller.dart +++ b/app/lib/ui/theme/app_design_controller.dart @@ -71,11 +71,24 @@ class AppDesignController extends ChangeNotifier { static final AppDesignController instance = AppDesignController(); final AppDesignStore _store; - AppDesign _design = AppDesign.standard; + AppDesign _design = AppDesign.defaultDesign; + AppDesign? _preview; int _revision = 0; bool _saveFailed = false; - AppDesign get design => _design; + /// The design shown: a [preview] while there is one, else the choice. + AppDesign get design => _preview ?? _design; + + /// The stored choice, whatever a [preview] shows meanwhile. + AppDesign get chosen => _design; + + /// Shows [design] app-wide without storing it (the design switcher's live + /// preview); null returns to the choice. [select] ends a preview. + void preview(AppDesign? design) { + final shown = this.design; + _preview = design; + if (this.design != shown) notifyListeners(); + } /// The last choice could not be stored on this device. bool get saveFailed => _saveFailed; @@ -88,17 +101,17 @@ class AppDesignController extends ChangeNotifier { final design = AppDesign.fromId(id); if (design == _design) return; _design = design; - notifyListeners(); + if (_preview == null) notifyListeners(); } /// Applies [design] now and stores it. Future select(AppDesign design) async { _revision++; final revision = _revision; - if (design != _design) { - _design = design; - notifyListeners(); - } + final shown = this.design; + _preview = null; + _design = design; + if (design != shown) notifyListeners(); final saved = await _store.save(design.id); if (revision != _revision || saved != _saveFailed) return; _saveFailed = !saved; diff --git a/app/lib/ui/theme/app_design_styles.dart b/app/lib/ui/theme/app_design_styles.dart index 19014124..ff36b944 100644 --- a/app/lib/ui/theme/app_design_styles.dart +++ b/app/lib/ui/theme/app_design_styles.dart @@ -5,7 +5,7 @@ import 'package:flutter/painting.dart'; /// transcript widgets branch on it, never on the design itself. enum TranscriptStyle { /// The operator's turns as bubbles on the trailing side, the agent's - /// answers on the page and its activity as a one-line button (Default). + /// answers on the page and its activity as a one-line button (Classic). bubbles, /// A CLI's prompt line, glyph-led tool lines and bracketed injected @@ -32,7 +32,7 @@ enum ComposerStyle { /// How a list (AppListRow) marks the row that is open. Every style keeps /// the leading bar in the row's accent; they differ in the fill and frame. enum SelectedRowStyle { - /// Material's tonal `secondaryContainer` fill (Default). + /// Material's tonal `secondaryContainer` fill (Classic). tonal, /// The accent washed over the page, stronger than a tinted row, inside a diff --git a/app/lib/ui/theme/app_design_tokens.dart b/app/lib/ui/theme/app_design_tokens.dart index f8d5eeab..349fc00b 100644 --- a/app/lib/ui/theme/app_design_tokens.dart +++ b/app/lib/ui/theme/app_design_tokens.dart @@ -6,7 +6,7 @@ import 'app_design_styles.dart'; export 'app_design_styles.dart'; /// The muted ANSI-style accents a design names for status and roles. The -/// Default design leaves them to its colour scheme; Terminal sets them, and +/// Classic design leaves them to its colour scheme; Terminal sets them, and /// Paper sets ink-toned ones. @immutable class AnsiAccents { @@ -46,7 +46,7 @@ class AnsiAccents { /// typography. Every theme an [AppDesign] builds carries one; a theme without /// one (a test's bare `ThemeData`) reads as [standard]. /// -/// Adding a design: every field has a default that keeps the Default look, +/// Adding a design: every field has a default that keeps the Classic look, /// so a new design sets only what it changes. Widgets branch on the named /// styles ([transcript], [composer], [selectedRow]) rather than on [design], /// so two designs can share a behaviour. @@ -67,7 +67,7 @@ class AppDesignTokens extends ThemeExtension { this.chatColorSaturation = 1, }); - /// The Default design: every widget keeps its own shapes. + /// The Classic design: every widget keeps its own shapes. static const AppDesignTokens standard = AppDesignTokens( design: AppDesign.standard, ); diff --git a/app/notes/fold-menus-hide-list-terminal-default.md b/app/notes/fold-menus-hide-list-terminal-default.md new file mode 100644 index 00000000..1bc27b24 --- /dev/null +++ b/app/notes/fold-menus-hide-list-terminal-default.md @@ -0,0 +1,44 @@ +# Foldable menus, hidden chat list, Terminal by default + +## Top bar menus far below the bar on an unfolded foldable + +Cause: `showAppChoiceMenu` (model, mode/permission, thinking, the narrow +bar's Chat settings panel, Add chat pane, Claude account) measured its anchor +in the root overlay's coordinates, then laid the panel out inside a +`SafeArea`. On Android the app draws edge to edge, so the overlay's +`MediaQuery.padding.top` is the status bar (and cutout): the `SafeArea` +moved the layout's origin down by that inset while the anchor rect stayed in +overlay coordinates, so every panel opened one inset (~50 dp) too low. On a +foldable's narrow pane the selectors sit in the Chat settings panel, itself +such a menu, so a selector's menu opened two insets below the bar. Phones +never showed it (they get bottom sheets below 600 dp) and neither did the +web (no insets). Overflow menus (`AppMenuAnchor` / `MenuAnchor`) were right. + +Fix: `AnchoredMenuLayout` (`lib/ui/adaptive/anchored_menu_layout.dart`) lays +out in the overlay's own coordinates and treats the insets (plus the +keyboard) only as bounds; a half-opened hinge confines the panel to the +anchor's side (`DisplayFeatureSubScreen`). The panel's content has the +padding removed, so a sheet's own `SafeArea` adds nothing inside it. +Tests: `test/ui/adaptive/app_popups_foldable_test.dart` (884x1104, 52/24 +insets, a fold; wide and narrow panes; above-anchor; hinge). + +Captures on web: `?inset=52,24&fold=1` (`tool/fixture_host/inset_view.dart`) +gives the fixture app an Android phone's insets and a fold. + +## Hiding the chat list + +Beside an open chat on a wide window the list can be hidden entirely: +Ctrl+B (Cmd+B on Apple; a focused terminal keeps Ctrl+B), Hide chat list in +the list's bar and in the pane's More menu. While hidden the top-left pane's +bar starts with Show chat list. `ListDetailPanes.listHidden` slides the list +to zero width (`Motion.standard`, instant with reduced motion) and brings it +back in its previous expanded or compact mode; the divider is not offered +while hidden. Device-local: `pipelines.chat.listHidden.v1` +(`ChatListHiddenController`). Ctrl/Alt+K and Ctrl+Tab are unaffected. + +## Terminal is the default design + +No stored (or an unknown) design id resolves to Terminal, including the boot +spinner and detached windows (same controller). A stored choice is kept; the +former Default keeps its stored id `default` and is now labelled Classic in +the picker. diff --git a/app/test/application/chat_quick_switch_shortcut_test.dart b/app/test/application/chat_quick_switch_shortcut_test.dart index 4ef9af04..c7695df6 100644 --- a/app/test/application/chat_quick_switch_shortcut_test.dart +++ b/app/test/application/chat_quick_switch_shortcut_test.dart @@ -6,6 +6,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/application/pipelines_app.dart'; import 'package:pipelines_app/core/transport/pipelines_client.dart'; import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_list_hidden_controller.dart'; import '../core/transport/pipelines_client_test.dart' show FakeChannel; import 'chat_registration_test.dart' @@ -269,4 +270,31 @@ void main() { }, variant: TargetPlatformVariant.only(TargetPlatform.macOS), ); + + testWidgets('with the chat list hidden the switcher still opens and ' + 'switches', (tester) async { + final hidden = ChatListHiddenController.instance; + hidden.value = true; + addTearDown(() => hidden.value = false); + final provider = _provider(); + final channel = await _mountOnChat(tester, provider); + expect(find.byKey(const Key('chat-show-list')), findsOneWidget); + + await _chord(tester, LogicalKeyboardKey.controlLeft); + expect(_field, findsOneWidget); + await tester.enterText(_field, 'second'); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(); + await replySubscribe(tester, channel, index: 1); + await replyHistory(tester, channel, index: 1); + await tester.pumpAndSettle(); + expect(provider.value.uri.path, '/chat/s2'); + expect(_composerFocused(tester, 's2'), isTrue); + // Switching leaves the list hidden. + expect(hidden.value, isTrue); + expect(find.byKey(const Key('chat-show-list')), findsOneWidget); + expect(tester.takeException(), isNull); + await _teardown(tester); + }); } diff --git a/app/test/application/chat_registration_test.dart b/app/test/application/chat_registration_test.dart index 9514eacd..1c829d3b 100644 --- a/app/test/application/chat_registration_test.dart +++ b/app/test/application/chat_registration_test.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart'; @@ -19,6 +20,8 @@ import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dar import '../core/transport/pipelines_client_test.dart' show FakeChannel; import '../native_back.dart'; import 'package:pipelines_app/ui/adaptive/segmented_bar.dart'; +import 'package:pipelines_app/ui/theme/app_design.dart'; +import 'package:pipelines_app/ui/theme/app_design_controller.dart'; ServerEndpoint webServer() => ServerEndpoint.resolve( base: Uri.parse('http://127.0.0.1:8096/'), @@ -307,6 +310,15 @@ void main() { tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); + // The Classic design's transcript (its activity summary line); the + // app starts on Terminal when no design is stored. + // The choice applies at once; its save need not finish here. + unawaited(AppDesignController.instance.select(AppDesign.standard)); + addTearDown( + () => unawaited( + AppDesignController.instance.select(AppDesign.defaultDesign), + ), + ); final channel = FakeChannel()..readyCompleter.complete(); final client = PipelinesClient( diff --git a/app/test/features/chat/chat_list_hide_test.dart b/app/test/features/chat/chat_list_hide_test.dart new file mode 100644 index 00000000..a19ee966 --- /dev/null +++ b/app/test/features/chat/chat_list_hide_test.dart @@ -0,0 +1,147 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_list_hidden_controller.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:pipelines_app/shell/list_pane_divider.dart'; +import 'package:pipelines_app/ui/adaptive/segmented_bar_overflow.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'conversation/chat_thread_fixtures.dart'; + +class _Gateway extends FakeChatGateway { + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_sessions') { + return Future.value({ + 'chat_sessions': [ + {'id': 'a', 'title': 'First chat'}, + {'id': 'b', 'title': 'Second chat'}, + {'id': 'c', 'title': 'Third chat'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + return super.call(type, fields); + } +} + +final _body = find.byKey(const ValueKey('list-detail-body')); +final _show = find.byKey(const Key('chat-show-list')); + +Future _open( + WidgetTester tester, { + bool hidden = false, +}) async { + SharedPreferences.setMockInitialValues({}); + tester.view.physicalSize = const Size(1280, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final listHidden = ChatListHiddenController( + store: MemoryChatListHiddenStore(hidden), + ); + addTearDown(listHidden.dispose); + final gateway = _Gateway()..history = (_) async => chatPage(const []); + addTearDown(gateway.close); + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + destination: AppDestination.chat, + destinationBodies: { + AppDestination.chat: (_) => + ChatScreen(gateway: gateway, listHidden: listHidden), + }, + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('First chat')); + await tester.pumpAndSettle(); + return listHidden; +} + +Future _chord(WidgetTester tester, LogicalKeyboardKey key) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(key); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pumpAndSettle(); +} + +double _railRight(WidgetTester tester) => + tester.getRect(find.byType(NavigationRail)).right; + +String? _active(WidgetTester tester) => tester + .widget(find.byType(ChatWorkspace)) + .controller + .activePane + ?.sessionId; + +void main() { + testWidgets('Ctrl+B hides the list entirely and Show chat list brings it ' + 'back', (tester) async { + final listHidden = await _open(tester); + final shown = tester.getRect(_body).left; + expect(shown, greaterThan(_railRight(tester) + 100)); + expect(_show, findsNothing); + // The list's own bar offers hiding too. + expect(find.byKey(const Key('chat-hide-list')), findsOneWidget); + + await _chord(tester, LogicalKeyboardKey.keyB); + expect(listHidden.value, isTrue); + // The open chat takes the whole width beside the rail; no divider is + // left to drag. + expect(tester.getRect(_body).left, closeTo(_railRight(tester), 1)); + expect(find.byType(ListPaneDivider), findsNothing); + expect(find.text('Second chat').hitTestable(), findsNothing); + // The chat's top bar starts with the way back. + expect(_show, findsOneWidget); + final bar = tester.getRect(find.byKey(const Key('chat-thread-header'))); + expect(tester.getRect(_show).left - bar.left, lessThan(24)); + + await tester.tap(_show); + await tester.pumpAndSettle(); + expect(listHidden.value, isFalse); + expect(tester.getRect(_body).left, closeTo(shown, 1)); + expect(_show, findsNothing); + expect(find.text('Second chat').hitTestable(), findsOneWidget); + + // Ctrl+B again hides, and again shows. + await _chord(tester, LogicalKeyboardKey.keyB); + expect(listHidden.value, isTrue); + await _chord(tester, LogicalKeyboardKey.keyB); + expect(listHidden.value, isFalse); + expect(tester.takeException(), isNull); + }); + + testWidgets('the pane menu names the toggle and its shortcut', ( + tester, + ) async { + final listHidden = await _open(tester); + await tester.tap(find.byKey(segmentedMoreKey).first); + await tester.pumpAndSettle(); + await tester.tap(find.text('Hide chat list (Ctrl+B)')); + await tester.pumpAndSettle(); + expect(listHidden.value, isTrue); + await tester.tap(find.byKey(segmentedMoreKey).first); + await tester.pumpAndSettle(); + expect(find.text('Show chat list (Ctrl+B)'), findsOneWidget); + }); + + testWidgets('a stored hidden list stays hidden, and Ctrl+Tab still cycles ' + 'the chats', (tester) async { + await _open(tester, hidden: true); + expect(tester.getRect(_body).left, closeTo(_railRight(tester), 1)); + expect(_show, findsOneWidget); + expect(_active(tester), 'a'); + await _chord(tester, LogicalKeyboardKey.tab); + expect(_active(tester), 'b'); + await _chord(tester, LogicalKeyboardKey.tab); + expect(_active(tester), 'c'); + // Still hidden. + expect(tester.getRect(_body).left, closeTo(_railRight(tester), 1)); + }); +} diff --git a/app/test/features/chat/conversation/chat_composer_focus_ring_test.dart b/app/test/features/chat/conversation/chat_composer_focus_ring_test.dart index aa8f772b..ab70b1f2 100644 --- a/app/test/features/chat/conversation/chat_composer_focus_ring_test.dart +++ b/app/test/features/chat/conversation/chat_composer_focus_ring_test.dart @@ -103,7 +103,11 @@ void main() { await tester.pumpWidget(composerThread(gateway)); await tester.pumpAndSettle(); final send = find.byKey(const Key('chat-composer-primary')); - expect(tester.widget(send).style, isNull); + // Only the fixed size is set: no colours, so the host's filled colours + // apply. + final style = tester.widget(send).style!; + expect(style.backgroundColor, isNull); + expect(style.foregroundColor, isNull); expect(chatSchemeOf(tester.element(send), null), isNull); }); diff --git a/app/test/features/chat/workspace/chat_list_hidden_controller_test.dart b/app/test/features/chat/workspace/chat_list_hidden_controller_test.dart new file mode 100644 index 00000000..ecefe087 --- /dev/null +++ b/app/test/features/chat/workspace/chat_list_hidden_controller_test.dart @@ -0,0 +1,82 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_list_hidden_controller.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +KeyDownEvent _b() => const KeyDownEvent( + physicalKey: PhysicalKeyboardKey.keyB, + logicalKey: LogicalKeyboardKey.keyB, + timeStamp: Duration.zero, +); + +void main() { + test('the choice is kept per device and restored', () async { + SharedPreferences.setMockInitialValues({}); + final first = ChatListHiddenController(); + expect(first.value, isFalse); + first.toggle(); + expect(first.value, isTrue); + await Future.delayed(Duration.zero); + expect( + (await SharedPreferences.getInstance()).getBool( + chatListHiddenPreferenceKey, + ), + isTrue, + ); + final next = ChatListHiddenController(); + await next.restore(); + expect(next.value, isTrue); + }); + + test('a choice made while restoring wins', () async { + final store = MemoryChatListHiddenStore(true); + final controller = ChatListHiddenController(store: store); + final restoring = controller.restore(); + controller.value = false; + await restoring; + expect(controller.value, isFalse); + }); + + testWidgets('Ctrl+B elsewhere, Cmd+B on Apple; no other chord', ( + tester, + ) async { + final keyboard = HardwareKeyboard.instance; + Future matches( + List modifiers, + TargetPlatform platform, + ) async { + for (final key in modifiers) { + await tester.sendKeyDownEvent(key); + } + final result = chatListToggleShortcut(_b(), keyboard, platform: platform); + for (final key in modifiers.reversed) { + await tester.sendKeyUpEvent(key); + } + return result; + } + + const linux = TargetPlatform.linux; + const mac = TargetPlatform.macOS; + expect(await matches([LogicalKeyboardKey.controlLeft], linux), isTrue); + expect(await matches([LogicalKeyboardKey.metaLeft], mac), isTrue); + expect(await matches([LogicalKeyboardKey.controlLeft], mac), isFalse); + expect(await matches([LogicalKeyboardKey.metaLeft], linux), isFalse); + expect( + await matches([ + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.shiftLeft, + ], linux), + isFalse, + ); + expect( + await matches([ + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.altLeft, + ], linux), + isFalse, + ); + expect(await matches(const [], linux), isFalse); + expect(chatListToggleLabel(true, linux), 'Show chat list (Ctrl+B)'); + expect(chatListToggleLabel(false, mac), 'Hide chat list (Cmd+B)'); + }); +} diff --git a/app/test/features/settings/design_quick_switch_test.dart b/app/test/features/settings/design_quick_switch_test.dart new file mode 100644 index 00000000..087f3d21 --- /dev/null +++ b/app/test/features/settings/design_quick_switch_test.dart @@ -0,0 +1,219 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/settings/design_quick_switch.dart'; +import 'package:pipelines_app/features/settings/design_quick_switch_match.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:pipelines_app/ui/input/keyboard_owner.dart'; +import 'package:pipelines_app/ui/theme/app_design.dart'; +import 'package:pipelines_app/ui/theme/app_design_controller.dart'; +import 'package:pipelines_app/ui/theme/app_design_tokens.dart'; + +final _field = find.byKey(const Key('design-quick-switch-field')); +Finder _row(AppDesign design) => + find.byKey(Key('design-quick-switch-row-${design.id}')); +bool _selected(WidgetTester tester, AppDesign design) => + tester.widget(_row(design)).selected; + +class _App { + _App(this.store) : designs = AppDesignController(store: store); + final MemoryAppDesignStore store; + final AppDesignController designs; + final terminal = FocusNode(); + + /// The design the app's theme is drawn in, read from the shell's context. + AppDesign shown(WidgetTester tester) => + AppDesignTokens.of(tester.element(find.byKey(const Key('body')))).design; +} + +Future<_App> _pump(WidgetTester tester, {String? stored}) async { + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final app = _App(MemoryAppDesignStore(stored)); + addTearDown(app.terminal.dispose); + await app.designs.restore(); + final toggle = DesignQuickSwitchToggle(designs: app.designs); + await tester.pumpWidget( + ListenableBuilder( + listenable: app.designs, + builder: (context, _) => MaterialApp( + theme: app.designs.design.light(), + themeAnimationDuration: Duration.zero, + home: AdaptiveShell( + onDesignSwitch: toggle.toggle, + destinationBodies: { + AppDestination.pipelines: (_) => TypingSurface( + child: Focus( + focusNode: app.terminal, + child: const Text('body', key: Key('body')), + ), + ), + }, + ), + ), + ), + ); + return app; +} + +Future _chord( + WidgetTester tester, + LogicalKeyboardKey modifier, + LogicalKeyboardKey key, +) async { + await tester.sendKeyDownEvent(modifier); + await tester.sendKeyEvent(key); + await tester.sendKeyUpEvent(modifier); + await tester.pumpAndSettle(); +} + +Future _altL(WidgetTester tester) => + _chord(tester, LogicalKeyboardKey.altLeft, LogicalKeyboardKey.keyL); + +void main() { + test('a query narrows the designs by name, then summary', () { + expect(designQuickSwitchMatches(AppDesign.values, ''), AppDesign.values); + expect(designQuickSwitchMatches(AppDesign.values, 'PAP'), [ + AppDesign.paper, + ]); + expect(designQuickSwitchMatches(AppDesign.values, 'mono'), [ + AppDesign.terminal, + ]); + expect(designQuickSwitchMatches(AppDesign.values, 'paper serif'), [ + AppDesign.paper, + ]); + expect(designQuickSwitchMatches(AppDesign.values, 'zzz'), isEmpty); + }); + + testWidgets('Alt+L lists every design with its swatch, the current one ' + 'marked and selected; Alt+L again closes it', (tester) async { + final app = await _pump(tester); + await _altL(tester); + expect(_field, findsOneWidget); + for (final design in AppDesign.values) { + expect(_row(design), findsOneWidget); + expect( + find.descendant(of: _row(design), matching: find.text(design.label)), + findsOneWidget, + ); + expect( + find.descendant( + of: _row(design), + matching: find.text(design.description), + ), + findsOneWidget, + ); + } + expect(find.byType(ListTile), findsNWidgets(AppDesign.values.length)); + expect( + find.descendant( + of: _row(AppDesign.terminal), + matching: find.byKey(const Key('design-quick-switch-current')), + ), + findsOneWidget, + ); + expect(find.byKey(const Key('design-quick-switch-current')), findsOne); + expect(_selected(tester, AppDesign.terminal), isTrue); + + await _altL(tester); + expect(_field, findsNothing); + expect(app.shown(tester), AppDesign.terminal); + }); + + testWidgets('Ctrl+N and Ctrl+P preview live without storing; Esc goes back ' + 'to the design it opened with', (tester) async { + final app = await _pump(tester); + await _altL(tester); + final order = AppDesign.values; + final start = order.indexOf(AppDesign.terminal); + final next = order[(start + 1) % order.length]; + final previous = order[(start - 1) % order.length]; + + await _chord( + tester, + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.keyN, + ); + expect(_selected(tester, next), isTrue); + expect(app.shown(tester), next); + expect(app.designs.chosen, AppDesign.terminal); + expect(app.store.id, isNull); + + await _chord( + tester, + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.keyP, + ); + await _chord( + tester, + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.keyP, + ); + expect(_selected(tester, previous), isTrue); + expect(app.shown(tester), previous); + + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(_field, findsNothing); + expect(app.shown(tester), AppDesign.terminal); + expect(app.designs.design, AppDesign.terminal); + expect(app.store.id, isNull); + }); + + testWidgets('a filter selects the best match and Enter keeps it', ( + tester, + ) async { + final app = await _pump(tester, stored: AppDesign.standard.id); + await _altL(tester); + expect(_selected(tester, AppDesign.standard), isTrue); + + await tester.enterText(_field, 'pap'); + await tester.pumpAndSettle(); + expect(find.byType(ListTile), findsOneWidget); + expect(_selected(tester, AppDesign.paper), isTrue); + expect(app.shown(tester), AppDesign.paper); + expect(app.store.id, AppDesign.standard.id); + + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(_field, findsNothing); + expect(app.shown(tester), AppDesign.paper); + expect(app.designs.chosen, AppDesign.paper); + expect(app.store.id, AppDesign.paper.id); + + // Reopened, Paper is now the marked one. + await _altL(tester); + expect( + find.descendant( + of: _row(AppDesign.paper), + matching: find.byKey(const Key('design-quick-switch-current')), + ), + findsOneWidget, + ); + }); + + testWidgets('a filter matching nothing shows the design it opened with', ( + tester, + ) async { + final app = await _pump(tester); + await _altL(tester); + await tester.enterText(_field, 'pap'); + await tester.pumpAndSettle(); + expect(app.shown(tester), AppDesign.paper); + await tester.enterText(_field, 'zzz'); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('design-quick-switch-empty')), findsOne); + expect(app.shown(tester), AppDesign.terminal); + }); + + testWidgets('the terminal keeps Alt+L', (tester) async { + final app = await _pump(tester); + app.terminal.requestFocus(); + await tester.pump(); + await _altL(tester); + expect(_field, findsNothing); + }); +} diff --git a/app/test/features/settings/settings_design_section_test.dart b/app/test/features/settings/settings_design_section_test.dart index 6b2185ae..7ca1d5bd 100644 --- a/app/test/features/settings/settings_design_section_test.dart +++ b/app/test/features/settings/settings_design_section_test.dart @@ -29,7 +29,7 @@ AppDesignTokens _tokens(WidgetTester tester) => AppDesignTokens.of(tester.element(find.text(designSectionTitle))); void main() { - testWidgets('every design is a radio row; Default is chosen at first', ( + testWidgets('every design is a radio row; Terminal is chosen at first', ( tester, ) async { final designs = AppDesignController(store: MemoryAppDesignStore()); @@ -43,40 +43,43 @@ void main() { final group = tester.widget>( find.byType(RadioGroup), ); - expect(group.groupValue, AppDesign.standard); - expect(_tokens(tester).terminal, isFalse); + expect(group.groupValue, AppDesign.terminal); + expect(_tokens(tester).terminal, isTrue); + // The Material look is called Classic, so no row reads "Default". + expect(find.text('Classic'), findsOneWidget); + expect(find.text('Default'), findsNothing); }); - testWidgets('choosing Terminal stores it and restyles the page live', ( + testWidgets('choosing Classic stores it and restyles the page live', ( tester, ) async { final store = MemoryAppDesignStore(); final designs = AppDesignController(store: store); await _pump(tester, designs); - await tester.tap(find.text(AppDesign.terminal.label)); - await tester.pumpAndSettle(); - expect(store.id, AppDesign.terminal.id); - expect(designs.design, AppDesign.terminal); - expect(_tokens(tester).terminal, isTrue); - expect(find.text(designSaveFailedText), findsNothing); - await tester.tap(find.text(AppDesign.standard.label)); await tester.pumpAndSettle(); expect(store.id, AppDesign.standard.id); + expect(designs.design, AppDesign.standard); expect(_tokens(tester).terminal, isFalse); + expect(find.text(designSaveFailedText), findsNothing); + + await tester.tap(find.text(AppDesign.terminal.label)); + await tester.pumpAndSettle(); + expect(store.id, AppDesign.terminal.id); + expect(_tokens(tester).terminal, isTrue); }); testWidgets('a stored choice is restored into the picker', (tester) async { final designs = AppDesignController( - store: MemoryAppDesignStore(AppDesign.terminal.id), + store: MemoryAppDesignStore(AppDesign.standard.id), ); await designs.restore(); await _pump(tester, designs); final group = tester.widget>( find.byType(RadioGroup), ); - expect(group.groupValue, AppDesign.terminal); + expect(group.groupValue, AppDesign.standard); }); testWidgets('a failed save says the choice lasts until reload', ( @@ -86,10 +89,10 @@ void main() { store: MemoryAppDesignStore()..failSaves = true, ); await _pump(tester, designs); - await tester.tap(find.text(AppDesign.terminal.label)); + await tester.tap(find.text(AppDesign.paper.label)); await tester.pumpAndSettle(); expect(find.text(designSaveFailedText), findsOneWidget); - expect(designs.design, AppDesign.terminal); + expect(designs.design, AppDesign.paper); }); testWidgets('choosing Paper stores it, restyles the page live and is ' diff --git a/app/test/shell/list_detail_hide_test.dart b/app/test/shell/list_detail_hide_test.dart new file mode 100644 index 00000000..e6656a25 --- /dev/null +++ b/app/test/shell/list_detail_hide_test.dart @@ -0,0 +1,73 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/shell/list_detail.dart'; +import 'package:pipelines_app/shell/list_pane_divider.dart'; + +final _body = find.byKey(const ValueKey('list-detail-body')); + +Widget _panes({required bool hidden, bool reduceMotion = false}) => MaterialApp( + home: Builder( + builder: (context) => MediaQuery( + data: MediaQuery.of(context).copyWith(disableAnimations: reduceMotion), + child: Scaffold( + body: ListDetailPanes( + listHidden: hidden, + list: const Focus( + autofocus: true, + child: Text('The list', key: Key('list-text')), + ), + detail: const SizedBox.expand(), + ), + ), + ), + ), +); + +void _size(WidgetTester tester) { + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); +} + +void main() { + testWidgets('a hidden list slides to zero width and comes back as it was', ( + tester, + ) async { + _size(tester); + await tester.pumpWidget(_panes(hidden: false)); + await tester.pumpAndSettle(); + final shown = tester.getRect(_body).left; + expect(shown, greaterThan(200)); + expect(find.byType(ListPaneDivider), findsOneWidget); + + await tester.pumpWidget(_panes(hidden: true)); + await tester.pump(const Duration(milliseconds: 60)); + final sliding = tester.getRect(_body).left; + expect(sliding, inExclusiveRange(0, shown), reason: 'animates'); + // The handle is not offered while the list slides or is hidden. + expect(find.byType(ListPaneDivider), findsNothing); + await tester.pumpAndSettle(); + expect(tester.getRect(_body).left, 0); + expect(tester.getRect(_body).width, 1200); + // Nothing in the hidden list keeps the keyboard. + final listFocus = Focus.of( + tester.element(find.byKey(const Key('list-text'))), + ); + expect(listFocus.hasFocus, isFalse); + + await tester.pumpWidget(_panes(hidden: false)); + await tester.pumpAndSettle(); + expect(tester.getRect(_body).left, shown); + expect(find.byType(ListPaneDivider), findsOneWidget); + }); + + testWidgets('with reduced motion the list hides at once', (tester) async { + _size(tester); + await tester.pumpWidget(_panes(hidden: false, reduceMotion: true)); + await tester.pumpAndSettle(); + await tester.pumpWidget(_panes(hidden: true, reduceMotion: true)); + await tester.pump(); + await tester.pump(); + expect(tester.getRect(_body).left, 0); + }); +} diff --git a/app/test/shell/shell_design_shortcut_test.dart b/app/test/shell/shell_design_shortcut_test.dart new file mode 100644 index 00000000..ff2d0277 --- /dev/null +++ b/app/test/shell/shell_design_shortcut_test.dart @@ -0,0 +1,49 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/shell/shell_design_shortcut.dart'; + +KeyDownEvent _down(PhysicalKeyboardKey physical, LogicalKeyboardKey logical) => + KeyDownEvent( + physicalKey: physical, + logicalKey: logical, + timeStamp: Duration.zero, + ); + +void main() { + test('Alt+L alone is the design switcher, Option+L by position', () { + bool chord(Set held, KeyEvent event) => + shellDesignShortcut(event, _FakeKeyboard(held)); + final l = _down(PhysicalKeyboardKey.keyL, LogicalKeyboardKey.keyL); + const alt = LogicalKeyboardKey.altLeft; + expect(chord({alt}, l), isTrue); + expect(chord({}, l), isFalse); + expect(chord({alt, LogicalKeyboardKey.shiftLeft}, l), isFalse); + expect(chord({alt, LogicalKeyboardKey.controlLeft}, l), isFalse); + expect(chord({alt, LogicalKeyboardKey.metaLeft}, l), isFalse); + expect(chord({LogicalKeyboardKey.controlLeft}, l), isFalse); + expect(chord({LogicalKeyboardKey.metaLeft}, l), isFalse); + // Option+L types ¬ on a Mac. + final symbol = _down( + PhysicalKeyboardKey.keyL, + const LogicalKeyboardKey(0x00ac), + ); + expect(chord({alt}, symbol), isTrue); + final k = _down(PhysicalKeyboardKey.keyK, LogicalKeyboardKey.keyK); + expect(chord({alt}, k), isFalse); + final up = KeyUpEvent( + physicalKey: PhysicalKeyboardKey.keyL, + logicalKey: LogicalKeyboardKey.keyL, + timeStamp: Duration.zero, + ); + expect(chord({alt}, up), isFalse); + expect(shellDesignShortcutLabel(TargetPlatform.macOS), 'Option+L'); + expect(shellDesignShortcutLabel(TargetPlatform.linux), 'Alt+L'); + }); +} + +class _FakeKeyboard extends HardwareKeyboard { + _FakeKeyboard(this.pressed); + final Set pressed; + @override + bool isLogicalKeyPressed(LogicalKeyboardKey key) => pressed.contains(key); +} diff --git a/app/test/ui/adaptive/app_popups_foldable_test.dart b/app/test/ui/adaptive/app_popups_foldable_test.dart new file mode 100644 index 00000000..fcca0751 --- /dev/null +++ b/app/test/ui/adaptive/app_popups_foldable_test.dart @@ -0,0 +1,208 @@ +import 'dart:ui'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_header.dart'; +import 'package:pipelines_app/ui/adaptive/app_popups.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_adaptive.dart'; +import 'package:pipelines_app/ui/adaptive/segmented_bar_overflow.dart'; + +/// An unfolded foldable: 884x1104 dp, a status bar and a cutout above the +/// app (Android draws edge to edge), a gesture bar below it, and the fold +/// down the middle. +void _foldable(WidgetTester tester, {bool halfOpened = false}) { + tester.view.physicalSize = const Size(884, 1104); + tester.view.devicePixelRatio = 1; + tester.view.padding = const FakeViewPadding(top: 52, bottom: 24); + tester.view.viewPadding = const FakeViewPadding(top: 52, bottom: 24); + tester.view.displayFeatures = [ + DisplayFeature( + bounds: halfOpened + ? const Rect.fromLTWH(436, 0, 12, 1104) + : const Rect.fromLTWH(442, 0, 0, 1104), + type: halfOpened ? DisplayFeatureType.hinge : DisplayFeatureType.fold, + state: halfOpened + ? DisplayFeatureState.postureHalfOpened + : DisplayFeatureState.postureFlat, + ), + ]; + addTearDown(tester.view.reset); +} + +Widget _choices(BuildContext menu) => Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final choice in const ['Opus', 'Sonnet', 'Haiku']) + ListTile(title: Text(choice), onTap: () => Navigator.of(menu).pop()), + ], +); + +Widget _menuButton(String label) => Builder( + builder: (anchor) => TextButton( + onPressed: () => showAppChoiceMenu(anchor, builder: _choices), + child: Text(label), + ), +); + +/// A chat pane's top bar the way the app lays it out: the app's own top +/// bar under the status bar, the selectors in the pane header, and the +/// overflow menu at its end. +Widget _app({required double listWidth}) => MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: Scaffold( + body: SafeArea( + child: Row( + children: [ + SizedBox(width: listWidth, child: const Placeholder()), + Expanded( + child: Column( + children: [ + ChatThreadHeader( + title: 'Chat', + folder: 'demo', + onInfo: () {}, + controls: [ + _menuButton('Model'), + _menuButton('Permission'), + _menuButton('Thinking'), + ], + moreActions: [ + ChatBarAction( + label: 'Rename chat', + onPressed: () {}, + materialIcon: Icons.edit_outlined, + ), + ], + ), + const Expanded(child: SizedBox.expand()), + ], + ), + ), + ], + ), + ), + ), +); + +final _menu = find.byKey(const ValueKey('app-choice-menu')); + +Future _expectUnder( + WidgetTester tester, + Finder button, + Finder panel, { + double slack = 16, +}) async { + final anchor = tester.getRect(button); + await tester.tap(button); + await tester.pumpAndSettle(); + final menu = tester.getRect(panel); + expect(menu.top, greaterThanOrEqualTo(anchor.bottom - 1)); + expect( + menu.top - anchor.bottom, + lessThan(slack), + reason: 'the menu opens right under its anchor, not an inset lower', + ); + await tester.tapAt(const Offset(200, 900)); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets('unfolded foldable, wide pane: every top bar menu opens ' + 'under its control', (tester) async { + _foldable(tester); + await tester.pumpWidget(_app(listWidth: 200)); + await tester.pumpAndSettle(); + for (final label in const ['Model', 'Thinking', 'Permission']) { + final button = find.widgetWithText(TextButton, label); + await _expectUnder(tester, button, _menu); + } + // The overflow menu is a MenuAnchor in the root overlay. + await _expectUnder( + tester, + find.byKey(segmentedMoreKey).first, + find.text('Rename chat').hitTestable(), + // The first item's label, inside the panel's and the item's padding. + slack: 32, + ); + }); + + testWidgets('unfolded foldable, narrow pane: the settings panel opens ' + 'under the bar and each selector menu under its control', (tester) async { + _foldable(tester); + await tester.pumpWidget(_app(listWidth: 360)); + await tester.pumpAndSettle(); + final bar = tester.getRect(find.byType(ChatThreadHeader)); + await tester.tap(find.byKey(segmentedMoreKey).first); + await tester.pumpAndSettle(); + await tester.tap(find.text('Chat settings')); + await tester.pumpAndSettle(); + final settings = tester.getRect(_menu); + expect(settings.top - bar.bottom, inInclusiveRange(-1, 16)); + for (final label in const ['Model', 'Thinking', 'Permission']) { + final button = find.widgetWithText(TextButton, label); + final anchor = tester.getRect(button); + await tester.tap(button); + await tester.pumpAndSettle(); + final menu = tester.getRect(_menu.last); + expect( + menu.top - anchor.bottom, + inInclusiveRange(-1, 16), + reason: '$label menu right under its control', + ); + await tester.tap(find.text('Opus').last); + await tester.pumpAndSettle(); + } + }); + + testWidgets('a menu stays inside the safe area and above when needed', ( + tester, + ) async { + _foldable(tester); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Align( + alignment: Alignment.bottomRight, + child: _menuButton('Low'), + ), + ), + ), + ); + final anchor = tester.getRect(find.widgetWithText(TextButton, 'Low')); + await tester.tap(find.text('Low')); + await tester.pumpAndSettle(); + final menu = tester.getRect(_menu); + // No room below: above the anchor, close to it, inside the app. + expect(menu.bottom, lessThanOrEqualTo(anchor.top)); + expect(anchor.top - menu.bottom, lessThan(16)); + expect(menu.right, lessThanOrEqualTo(884 - 8)); + }); + + testWidgets('a half opened hinge keeps the menu on its anchor side', ( + tester, + ) async { + _foldable(tester, halfOpened: true); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SafeArea( + child: Padding( + padding: const EdgeInsets.only(left: 340), + child: Align( + alignment: Alignment.topLeft, + child: _menuButton('Across'), + ), + ), + ), + ), + ), + ); + final anchor = tester.getRect(find.widgetWithText(TextButton, 'Across')); + await tester.tap(find.text('Across')); + await tester.pumpAndSettle(); + final menu = tester.getRect(_menu); + expect(menu.top - anchor.bottom, inInclusiveRange(-1, 16)); + // The anchor's centre is left of the hinge: the panel stays left of it. + expect(menu.right, lessThanOrEqualTo(436)); + }); +} diff --git a/app/test/ui/theme/app_design_controller_test.dart b/app/test/ui/theme/app_design_controller_test.dart index 49d51f23..2b7c6999 100644 --- a/app/test/ui/theme/app_design_controller_test.dart +++ b/app/test/ui/theme/app_design_controller_test.dart @@ -4,34 +4,52 @@ import 'package:pipelines_app/ui/theme/app_design_controller.dart'; import 'package:shared_preferences/shared_preferences.dart'; void main() { - test('restore applies the stored design; unknown ids keep Default', () async { - final stored = AppDesignController(store: MemoryAppDesignStore('terminal')); - var notified = 0; - stored.addListener(() => notified++); - await stored.restore(); - expect(stored.design, AppDesign.terminal); - expect(notified, 1); - - final unknown = AppDesignController(store: MemoryAppDesignStore('neon')); - await unknown.restore(); - expect(unknown.design, AppDesign.standard); + test('an unset device starts on Terminal and keeps it', () async { + final unset = AppDesignController(store: MemoryAppDesignStore()); + expect(unset.design, AppDesign.terminal); + await unset.restore(); + expect(unset.design, AppDesign.terminal); }); + test( + 'restore applies the stored design; unknown ids are the default', + () async { + // An explicit Classic choice, stored as `default` back when Classic was + // the default, is respected. + final stored = AppDesignController( + store: MemoryAppDesignStore('default'), + ); + var notified = 0; + stored.addListener(() => notified++); + await stored.restore(); + expect(stored.design, AppDesign.standard); + expect(notified, 1); + + final paper = AppDesignController(store: MemoryAppDesignStore('paper')); + await paper.restore(); + expect(paper.design, AppDesign.paper); + + final unknown = AppDesignController(store: MemoryAppDesignStore('neon')); + await unknown.restore(); + expect(unknown.design, AppDesign.terminal); + }, + ); + test('select applies at once and stores the id', () async { final store = MemoryAppDesignStore(); final designs = AppDesignController(store: store); - final pending = designs.select(AppDesign.terminal); - expect(designs.design, AppDesign.terminal); + final pending = designs.select(AppDesign.standard); + expect(designs.design, AppDesign.standard); await pending; - expect(store.id, 'terminal'); + expect(store.id, 'default'); expect(designs.saveFailed, isFalse); }); test('a failed save is reported and the choice still applies', () async { final store = MemoryAppDesignStore()..failSaves = true; final designs = AppDesignController(store: store); - await designs.select(AppDesign.terminal); - expect(designs.design, AppDesign.terminal); + await designs.select(AppDesign.paper); + expect(designs.design, AppDesign.paper); expect(designs.saveFailed, isTrue); store.failSaves = false; await designs.select(AppDesign.standard); @@ -48,6 +66,33 @@ void main() { expect(designs.design, AppDesign.standard); }); + test('a preview shows a design without storing it; select ends it', () async { + final store = MemoryAppDesignStore('default'); + final designs = AppDesignController(store: store); + await designs.restore(); + var notified = 0; + designs.addListener(() => notified++); + designs.preview(AppDesign.paper); + expect(designs.design, AppDesign.paper); + expect(designs.chosen, AppDesign.standard); + expect(notified, 1); + designs.preview(AppDesign.paper); + expect(notified, 1); + designs.preview(null); + expect(designs.design, AppDesign.standard); + expect(notified, 2); + expect(store.id, 'default'); + + designs.preview(AppDesign.terminal); + await designs.select(AppDesign.terminal); + expect(notified, 3); + expect(designs.design, AppDesign.terminal); + expect(store.id, 'terminal'); + designs.preview(null); + expect(designs.design, AppDesign.terminal); + expect(notified, 3); + }); + test('shared preferences keep the choice per device', () async { SharedPreferences.setMockInitialValues({}); const store = SharedPreferencesAppDesignStore(); diff --git a/app/test/ui/theme/app_design_test.dart b/app/test/ui/theme/app_design_test.dart index 97689724..1d0193d3 100644 --- a/app/test/ui/theme/app_design_test.dart +++ b/app/test/ui/theme/app_design_test.dart @@ -11,16 +11,19 @@ import 'package:pipelines_app/ui/theme/app_font_store.dart'; import 'package:pipelines_app/ui/theme/app_theme.dart'; void main() { - test('ids round-trip and an unknown id is the Default design', () { + test('ids round-trip and a missing or unknown id is Terminal', () { for (final design in AppDesign.values) { expect(AppDesign.fromId(design.id), design); } - expect(AppDesign.fromId(null), AppDesign.standard); - expect(AppDesign.fromId('neon'), AppDesign.standard); + expect(AppDesign.defaultDesign, AppDesign.terminal); + expect(AppDesign.fromId(null), AppDesign.terminal); + expect(AppDesign.fromId('neon'), AppDesign.terminal); + // Classic keeps the id it was stored under when it was the default. expect(AppDesign.standard.id, 'default'); + expect(AppDesign.standard.label, 'Classic'); }); - test('the Default design builds exactly the existing themes', () { + test('the Classic design builds exactly the existing themes', () { expect(AppDesign.standard.light(), appLightTheme()); expect(AppDesign.standard.dark(), appDarkTheme()); expect( @@ -97,14 +100,15 @@ void main() { }, ), ); - expect(tokens.terminal, isFalse); - expect(family, isNot(appMonospaceFamily)); - await designs.select(AppDesign.terminal); - await tester.pumpAndSettle(); + // Terminal until the device chooses. expect(tokens.terminal, isTrue); expect(family, appMonospaceFamily); await designs.select(AppDesign.standard); await tester.pumpAndSettle(); expect(tokens.terminal, isFalse); + expect(family, isNot(appMonospaceFamily)); + await designs.select(AppDesign.terminal); + await tester.pumpAndSettle(); + expect(tokens.terminal, isTrue); }); } diff --git a/app/test/ui/theme/app_font_theme_test.dart b/app/test/ui/theme/app_font_theme_test.dart index bacaed08..5918b31e 100644 --- a/app/test/ui/theme/app_font_theme_test.dart +++ b/app/test/ui/theme/app_font_theme_test.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/application/app.dart'; import 'package:pipelines_app/shell/destination.dart'; +import 'package:pipelines_app/ui/theme/app_design_controller.dart'; import 'package:pipelines_app/ui/theme/app_font.dart'; import 'package:pipelines_app/ui/theme/app_font_controller.dart'; import 'package:pipelines_app/ui/theme/app_font_store.dart'; @@ -36,10 +37,14 @@ void main() { store: MemoryAppFontStore(), loader: (family, assets) async {}, ); + // Classic follows the interface font (Terminal keeps its monospace). + final designs = AppDesignController(store: MemoryAppDesignStore('default')); + await designs.restore(); String? family; await tester.pumpWidget( MyApp( fonts: fonts, + designs: designs, destination: AppDestination.settings, destinationBodies: { AppDestination.settings: (context) => Builder( diff --git a/app/tool/fixture_host/fixture_host_web.dart b/app/tool/fixture_host/fixture_host_web.dart index 780346e3..1a113e57 100644 --- a/app/tool/fixture_host/fixture_host_web.dart +++ b/app/tool/fixture_host/fixture_host_web.dart @@ -6,6 +6,7 @@ import '../perf/backdrop_census.dart'; import '../perf/chat_scroll_probe.dart'; import '../perf/design_probe.dart'; import '../perf/frame_log.dart'; +import 'inset_view.dart'; /// The fixture options: the page URL's query. Map fixtureParams() => Uri.base.queryParameters; @@ -30,5 +31,26 @@ ServerEndpoint fixtureServer(Map params) => /// The browser's location is the route; no provider is needed. RouteInformationProvider? fixtureRouteProvider(String? route) => null; -/// Runs [app] unchanged. -void runFixtureApp(Widget app, Map params) => runApp(app); +/// Runs [app], under an Android phone's system insets (and a fold) when +/// `?inset=,` (and `&fold=1`) ask for them; see [InsetView]. +void runFixtureApp(Widget app, Map params) { + final inset = params['inset']; + if (inset == null && params['fold'] != '1') { + runApp(app); + return; + } + final parts = (inset ?? '').split(','); + final binding = WidgetsFlutterBinding.ensureInitialized(); + final view = binding.platformDispatcher.implicitView!; + runWidget( + View( + view: InsetView( + view, + top: double.tryParse(parts.first) ?? 0, + bottom: parts.length > 1 ? double.tryParse(parts[1]) ?? 0 : 0, + fold: params['fold'] == '1', + ), + child: app, + ), + ); +} diff --git a/app/tool/fixture_host/inset_view.dart b/app/tool/fixture_host/inset_view.dart new file mode 100644 index 00000000..c72f8a71 --- /dev/null +++ b/app/tool/fixture_host/inset_view.dart @@ -0,0 +1,92 @@ +import 'dart:ui' as ui; + +/// The real view with an Android phone's system insets: a status bar +/// [top] and a gesture bar [bottom] logical pixels tall, drawn over the app +/// edge to edge, and with [fold] a vertical fold down the middle, as an +/// unfolded foldable reports it. A browser always reports no insets, so this +/// is how a capture sees inset-dependent layout (anchored menus, bars). +/// +/// `?inset=52,24&fold=1` in the fixture URL. +class InsetView implements ui.FlutterView { + InsetView(this._view, {this.top = 0, this.bottom = 0, this.fold = false}); + + final ui.FlutterView _view; + final double top; + final double bottom; + final bool fold; + + ui.ViewPadding get _insets => _Padding( + top: top * _view.devicePixelRatio, + bottom: bottom * _view.devicePixelRatio, + ); + + @override + ui.Size get physicalSize => _view.physicalSize; + + @override + ui.ViewConstraints get physicalConstraints => _view.physicalConstraints; + + @override + int get viewId => _view.viewId; + + @override + ui.PlatformDispatcher get platformDispatcher => _view.platformDispatcher; + + @override + ui.Display get display => _view.display; + + @override + double get devicePixelRatio => _view.devicePixelRatio; + + @override + ui.ViewPadding get viewInsets => _view.viewInsets; + + @override + ui.ViewPadding get viewPadding => _insets; + + @override + ui.ViewPadding get systemGestureInsets => _view.systemGestureInsets; + + @override + ui.ViewPadding get padding => _insets; + + @override + ui.GestureSettings get gestureSettings => _view.gestureSettings; + + @override + List get displayFeatures { + if (!fold) return _view.displayFeatures; + final size = _view.physicalSize; + return [ + ui.DisplayFeature( + bounds: ui.Rect.fromLTWH(size.width / 2, 0, 0, size.height), + type: ui.DisplayFeatureType.fold, + state: ui.DisplayFeatureState.postureFlat, + ), + ]; + } + + @override + ui.DisplayCornerRadii? get displayCornerRadii => _view.displayCornerRadii; + + @override + void render(ui.Scene scene, {ui.Size? size}) => + _view.render(scene, size: size); + + @override + void updateSemantics(ui.SemanticsUpdate update) => + _view.updateSemantics(update); +} + +class _Padding implements ui.ViewPadding { + const _Padding({required this.top, required this.bottom}); + + @override + final double top; + @override + final double bottom; + @override + double get left => 0; + @override + double get right => 0; +}