Files
pipelines/app/lib/shell/adaptive_shell.dart
T

432 lines
16 KiB
Dart

import '../ui/motion/fade_through_stack.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../ui/adaptive/segmented_bar.dart';
import '../ui/adaptive/floating_bar_layout.dart';
import '../ui/adaptive/floating_destination_bar.dart';
import 'attention_badge.dart';
import 'destination.dart';
import 'list_detail.dart';
import 'list_pane_widths.dart';
import 'shell_bar.dart';
import 'shell_list_shortcuts.dart';
import 'tab_history.dart';
class AdaptiveShell extends StatefulWidget {
const AdaptiveShell({
super.key,
this.destinationBodies = const {},
this.cupertino = false,
this.destination,
this.onDestinationSelected,
this.onSearch,
this.attentionCount = 0,
this.listPaneWidthStore = const SharedPreferencesListPaneWidthStore(),
});
/// Where each destination's dragged list-pane width is kept on this device.
final ListPaneWidthStore listPaneWidthStore;
final Map<AppDestination, WidgetBuilder> destinationBodies;
final bool cupertino;
/// The destination a route owner selected. When null the shell keeps its own
/// selection, which preserves the plain-shell tests and native composition.
final AppDestination? destination;
final ValueChanged<AppDestination>? onDestinationSelected;
/// Opens the transient Search page. Null hides the action, so the plain
/// shell tests and compositions without routing keep their tab set only.
final VoidCallback? onSearch;
/// Runs needing the operator today, mirrored on the Runs tab in every mount
/// so it stays visible from any destination. Zero shows no badge.
final int attentionCount;
@override
State<AdaptiveShell> createState() => _AdaptiveShellState();
}
class _AdaptiveShellState extends State<AdaptiveShell> {
late AppDestination _selected;
final Set<AppDestination> _visited = {};
final TabHistory _history = TabHistory();
// Whether a navigator inside each destination (an open item's pane) has a
// page of its own for the system Back to close first.
final Map<AppDestination, bool> _nestedCanPop = {};
final ShellBarRegistry _bar = ShellBarRegistry();
late final ListPaneWidths _paneWidths = ListPaneWidths(
store: widget.listPaneWidthStore,
);
// Keeps every destination's state if the stack's parent ever changes.
final GlobalKey _destinationStackKey = GlobalKey();
@override
void dispose() {
HardwareKeyboard.instance.removeHandler(_handleDestinationKeyEvent);
_bar.dispose();
_paneWidths.dispose();
super.dispose();
}
@override
void initState() {
super.initState();
_selected = widget.destination ?? AppDestination.pipelines;
_visited.add(_selected);
HardwareKeyboard.instance.addHandler(_handleDestinationKeyEvent);
}
@override
void didUpdateWidget(covariant AdaptiveShell oldWidget) {
super.didUpdateWidget(oldWidget);
final destination = widget.destination;
if (destination != null) {
_history.record(_selected, destination);
_selected = destination;
_visited.add(destination);
}
}
void _select(AppDestination destination) {
final callback = widget.onDestinationSelected;
if (callback != null) {
callback(destination);
return;
}
setState(() {
_history.record(_selected, destination);
_selected = destination;
_visited.add(destination);
});
}
/// The destination's icon; only Runs carries the attention count.
Widget _icon(AppDestination destination, IconData data) {
Widget icon = Icon(data);
if (destination == AppDestination.chat) {
return ActivityBadge(
key: const ValueKey('shell.badge.chat.unread'),
count: _bar.badge(destination, ShellBadgeKind.unread),
label: 'unread chats',
cupertino: widget.cupertino,
child: icon,
);
}
if (destination != AppDestination.runs) return icon;
// One indicator: runs that need you outrank runs in progress, so the
// tab never wears two counts at once.
final attention = widget.attentionCount > 0;
return AttentionDestinationIcon(
count: widget.attentionCount,
cupertino: widget.cupertino,
child: ActivityBadge(
key: const ValueKey('shell.badge.runs.running'),
count: attention ? 0 : _bar.badge(destination, ShellBadgeKind.running),
label: 'runs in progress',
cupertino: widget.cupertino,
child: icon,
),
);
}
@override
Widget build(BuildContext context) {
// Full-screen detail routes cover the shell themselves. Keep the root tabs
// mounted/layout-ready underneath, so Back does not resize or reveal them
// only after the outgoing page has finished its native animation.
// Settings is shown as a page of the Pipelines tab: the tab bar keeps
// Pipelines selected and the bar offers Back to it.
final index = shellTabDestinations.indexOf(shellTabFor(_selected));
final page = !shellTabDestinations.contains(_selected);
final details = destinationDetails(_selected);
final contents = AppDestination.values.map((destination) {
final item = destinationDetails(destination);
return KeyedSubtree(
key: ValueKey(destination),
child: NotificationListener<NavigationNotification>(
onNotification: (notification) {
_nestedCanPop[destination] = notification.canHandlePop;
return false;
},
child: ShellBarScope(
registry: _bar,
destination: destination,
child: _visited.contains(destination)
? widget.destinationBodies[destination]?.call(context) ??
Center(child: Text('${item.label} — Not implemented'))
: const SizedBox.shrink(),
),
),
);
}).toList();
// Only the bar shows the registry's state, so a published bar or badge
// rebuilds its bar alone; the destinations and scaffold stay as built.
_bar.focus = _selected;
// One floating glass tab bar at every width: sized to its tabs at the
// right edge, near the thumb. Content keeps the whole width and scrolls
// behind it, learning the bar's height as its bottom media padding.
// Neither scaffold's structure depends on the width, so resizing never
// remounts a destination.
//
// While the tab shows its list beside an open item the bar moves under
// the list pane, centred in the list's (dragged) width, so the open item
// keeps its whole height: the list clears the bar and the item clears
// only the system inset (see ListDetailPanes). The bar keeps its place
// in the tree, so a split never replays its entrance.
final bar = ListenableBuilder(
listenable: Listenable.merge([_bar.badges, _bar.bar, _paneWidths]),
builder: (context, _) {
// On a wide window the bar stays under the list column even when no
// item is open (Search, a list alone), so it never jumps sides. A page
// (Settings) has no list column, so its bar stays at the right edge.
final split =
_bar.split(_selected) || (!page && showsListBesideDetail(context));
return ListPaneWidth(
split: split,
preferredWidth: _paneWidths.widthFor(_selected.name),
alignment: AlignmentDirectional.bottomStart,
child: FloatingDestinationBar(
cupertino: widget.cupertino,
currentIndex: index,
onTap: (value) => _select(shellTabDestinations[value]),
items: _destinationItems(),
alignment: split ? Alignment.bottomCenter : null,
),
);
},
);
// Destinations reach the top edge and scroll behind the floating top
// bar too: each learns the bar's height as its top media padding and
// pads its own lists by it (see withTopBarClearance).
SegmentedBar currentBar() =>
_segmentedBar(_bar.specFor(_selected), details.label, page: page);
final topBar = _ListPaneBar(
listenable: Listenable.merge([_bar.bar, _paneWidths]),
initial: currentBar(),
split: () => _bar.split(_selected),
preferredWidth: () => _paneWidths.widthFor(_selected.name),
bar: currentBar,
);
// The scaffolds below swap the system insets for their bars'
// heights; panes beside a list read the real ones from here.
final system = MediaQuery.paddingOf(context);
// A page (Settings) closes to Pipelines on the system Back too; at a
// tab's root Back returns to the tab opened before it. Only with neither
// does Back reach the platform, so Android's (predictive) Back closes the
// app only from the first tab. Pages pushed over the shell (an item,
// Search, a dialog) pop before this scope is asked. The scope is always
// there, so opening the page never remounts the shell.
Widget backable(Widget child) => PopScope(
canPop: !page && _history.isEmpty,
onPopInvokedWithResult: (didPop, _) {
if (!didPop) _back(page: page);
},
child: child,
);
if (widget.cupertino) {
return backable(
ShellSystemInsets(
padding: system,
child: CupertinoPageScaffold(
navigationBar: topBar,
child: SafeArea(
top: false,
bottom: false,
child: FloatingBarOverlay(
bar: bar,
child: _destinationStack(contents),
),
),
),
),
);
}
return backable(
ShellSystemInsets(
padding: system,
child: Scaffold(
extendBodyBehindAppBar: true,
appBar: topBar,
body: _destinationStack(contents),
extendBody: true,
bottomNavigationBar: bar,
),
),
);
}
/// Leaves a page destination (Settings) for the tab it belongs to.
void _closePage() => _select(shellTabFor(_selected));
/// The system Back the shell handles: it closes a page, or else returns to
/// the previous tab unless the open item's own pane closes a page first.
void _back({required bool page}) {
if (page) {
_closePage();
return;
}
if (_nestedCanPop[shellTabFor(_selected)] ?? false) return;
final previous = _history.takePrevious();
if (previous != null) _select(previous);
}
/// Handles this before focused text controls can insert or traverse on
/// Ctrl+Tab. The handler is scoped to the shell's lifetime, not onboarding.
///
/// Ctrl+1…Ctrl+9 open the Nth item of the open tab's list the same way, in
/// the list's on-screen order; a page (Settings) has no list.
bool _handleDestinationKeyEvent(KeyEvent event) {
final listIndex = shellListShortcutIndex(
event,
HardwareKeyboard.instance,
);
if (listIndex != null) {
if (!shellTabDestinations.contains(_selected)) return false;
return _bar.lists.open(_selected, listIndex);
}
if (event is! KeyDownEvent ||
event.logicalKey != LogicalKeyboardKey.tab ||
!HardwareKeyboard.instance.isControlPressed) {
return false;
}
final current = shellTabDestinations.indexOf(shellTabFor(_selected));
final direction = HardwareKeyboard.instance.isShiftPressed ? -1 : 1;
final next = (current + direction) % shellTabDestinations.length;
_select(
shellTabDestinations[next < 0
? next + shellTabDestinations.length
: next],
);
return true;
}
List<FloatingDestinationItem> _destinationItems() =>
shellTabDestinations.map((destination) {
final item = destinationDetails(destination);
return FloatingDestinationItem(
key: ValueKey('shell.destination.${destination.name}'),
icon: _icon(
destination,
widget.cupertino ? item.cupertinoIcon : item.icon,
),
label: item.label,
);
}).toList();
/// The open screen's own bar: its Back, title and actions, or the tab's
/// name with Search.
SegmentedBar _segmentedBar(
ShellBarSpec? spec,
String label, {
required bool page,
}) {
final cupertino = widget.cupertino;
final onBack = spec?.onBack ?? (page ? _closePage : null);
final published = spec?.actions ?? const <Widget>[];
final onSearch = widget.onSearch;
return SegmentedBar(
cupertino: cupertino,
automaticallyImplyLeading: false,
leading: onBack == null
? null
: SegmentedBackButton(
key: const ValueKey('shell.back'),
cupertino: cupertino,
onPressed: onBack,
),
title: spec?.title ?? label,
titleWidget: spec?.titleWidget,
titleWidgetMaxWidth: spec?.titleWidgetMaxWidth ?? double.infinity,
backgroundColor: spec?.backgroundColor,
subtitle: spec?.subtitle,
subtitleIcon: spec?.subtitleIcon,
onTitlePressed: spec?.onTitlePressed,
expandableTitle: spec?.expandableTitle ?? false,
titleAction: spec?.titleAction,
titleSemanticLabel: spec?.titleSemanticLabel,
titleKey: spec?.titleKey,
// A screen taking the bar over brings its own actions, which pop in
// one after another; while it stays, they stay.
actionsKey: published.isEmpty ? null : _bar.ownerFor(_selected),
actions: [
if (published.isNotEmpty)
...published
// A screen whose main pill is its own field (Search) needs no
// separate Search action.
else if (onSearch != null && spec?.titleWidget == null && !page)
cupertino
? CupertinoButton(
key: const ValueKey('shell.search'),
padding: EdgeInsets.zero,
onPressed: onSearch,
child: const Icon(
CupertinoIcons.search,
semanticLabel: 'Search',
),
)
: IconButton(
key: const ValueKey('shell.search'),
onPressed: onSearch,
tooltip: 'Search',
icon: const Icon(Icons.search),
),
],
);
}
Widget _destinationStack(List<Widget> contents) => ListPaneWidthsScope(
widths: _paneWidths,
child: FadeThroughStack(
key: _destinationStackKey,
index: AppDestination.values.indexOf(_selected),
children: contents,
),
);
}
/// The shell's top bar, over the list pane only while the tab shows a list
/// beside an open item ([ShellPaneSplit]); the item's own bar takes the rest
/// of the same row. The bar keeps its place in the scaffold either way, so a
/// split never remounts it.
///
/// It rebuilds itself when [listenable] (the focused destination's published
/// bar) changes; [initial] supplies the size and obstruction, which do not
/// depend on the published contents.
class _ListPaneBar extends StatelessWidget
implements ObstructingPreferredSizeWidget {
const _ListPaneBar({
required this.listenable,
required this.initial,
required this.split,
required this.preferredWidth,
required this.bar,
});
final Listenable listenable;
final SegmentedBar initial;
final bool Function() split;
final double? Function() preferredWidth;
final SegmentedBar Function() bar;
@override
Size get preferredSize => initial.preferredSize;
@override
bool shouldFullyObstruct(BuildContext context) =>
initial.shouldFullyObstruct(context);
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: listenable,
builder: (context, _) => ListPaneWidth(
split: split(),
preferredWidth: preferredWidth(),
alignment: AlignmentDirectional.topStart,
child: bar(),
),
);
}