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/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)); + }); +}