import 'dart:math' as math; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'pop_entrance.dart'; import 'segmented_action_row.dart'; import 'segmented_bar_entrance.dart'; import 'segmented_bar_overflow.dart'; import 'segmented_bar_motion.dart'; import 'segmented_bar_pieces.dart'; import 'window_controls.dart'; import 'window_margins.dart'; export 'segmented_bar_overflow.dart' show SegmentedMenuChoice, SegmentedOverflowAction, SegmentedOverflowEntry, SegmentedOverflowable, segmentedMoreKey; export 'segmented_bar_pieces.dart' show SegmentedBackButton, SegmentedPill; /// The app's top bar: separate frosted-glass pieces floating over the page's /// content, on a scrim of the page's background that fades out downwards. /// /// From the leading edge: a round piece holding [leading] (the platform's /// Back, implied as the stock bars do when [automaticallyImplyLeading]), a /// pill with the [title] and an optional one-line [subtitle] that runs /// [onTitlePressed] when given, and a pill holding the [actions] at the /// trailing edge. The title keeps its own width (up to [maxTitleShare] of the /// bar, and never under [minTitleShare]); the actions take their natural /// width beside it, and those that do not fit move into one More menu /// (when they are [SegmentedOverflowable]) rather than shrink below their /// touch targets. Only actions that cannot move ellipsise the first of them. /// /// A page whose bar is mainly an input (Search) passes [titleWidget] instead: /// it takes the title pill's place as one pill that fills the space beside /// the leading piece (up to the widget's own width cap), with no title. /// /// Only the pieces take taps: a tap between them reaches the content behind. /// It works as a [Scaffold.appBar] (with `extendBodyBehindAppBar`) and a /// [CupertinoPageScaffold.navigationBar], which inset the content by the /// bar's height through [MediaQuery.paddingOf], so a page keeps its /// scaffold's structure; [SegmentedBarOverlay] does the same anywhere else. /// It handles the top safe area itself, keeps its pieces clear of the /// system's window controls ([WindowControlsClearance]), and on a wide window /// keeps the wider [WindowMargins] from the top and the sides. class SegmentedBar extends StatefulWidget implements ObstructingPreferredSizeWidget { const SegmentedBar({ super.key, required this.cupertino, required this.title, this.titleWidget, this.titleWidgetMaxWidth = double.infinity, this.leading, this.automaticallyImplyLeading = true, this.subtitle, this.subtitleIcon, this.onTitlePressed, this.expandableTitle = false, this.titleAction, this.titleLeading, this.titleSemanticLabel, this.titleKey, this.actions = const [], this.separateActionIslands = false, this.actionsKey, this.backgroundColor, this.pillColor, this.foregroundColor, this.bottomPadding = 8, this.backdrop, }); /// Which control family to draw. Required because the bar's reserved /// height differs: a Cupertino navigation bar never scales its text, so it /// reserves exactly its height, while a Material app bar grows with text. final bool cupertino; /// The title; empty shows no title pill unless there is a [subtitle]. final String title; /// The bar's main pill when it is not a title: a search field and its /// filters. It replaces the title pill (so [title], [subtitle] and /// [onTitlePressed] are not drawn) and fills the width beside the leading /// piece and any [actions], up to [titleWidgetMaxWidth]. final Widget? titleWidget; /// The widest the [titleWidget] pill grows on a wide window; it starts at /// the leading edge, so content below can line up with it. final double titleWidgetMaxWidth; /// The leading control, normally a [SegmentedBackButton]. final Widget? leading; /// Whether to show the platform's Back (or close, on a full-screen dialog) /// when [leading] is null and the route can go back. final bool automaticallyImplyLeading; final String? subtitle; final IconData? subtitleIcon; /// Makes the title pill a button (an information page, a picker). final VoidCallback? onTitlePressed; /// Lets the title expand over the content without changing bar clearance. final bool expandableTitle; /// An action shown inside the expanded title pill. final Widget? titleAction; final Widget? titleLeading; final String? titleSemanticLabel; /// The key of the title's button (or its content when not pressable). final Key? titleKey; /// The bar's actions, at the trailing edge in one pill; each pops in on /// its own (see [SegmentedEntrancePlanner]). final List actions; /// Each action is an independently filled island, ordered before the next. /// Use non-overflowable group widgets to keep related controls together. final bool separateActionIslands; /// Who supplies [actions] (a shell's open screen): when it changes, every /// action is new and pops in, though one has the same key as before. final Object? actionsKey; /// The bar's backdrop; defaults to the enclosing scaffold's background. final Color? backgroundColor; /// The pieces' fill; defaults to the host's raised surface role. final Color? pillColor; /// The title's color, for a bar over a dark backdrop. final Color? foregroundColor; /// Space between the pieces and the content below. final double bottomPadding; /// Painted over the scrim and under the pieces, filling the bar from its /// top edge (a page's own tint, such as a chat's colour). It takes no taps. final Widget? backdrop; static const double _topPadding = WindowMargins.narrowTop; /// The share of the bar the title always keeps beside the actions. static const double minTitleShare = 0.25; /// The most of the bar the title's own width claims before the actions: /// a short title (a destination's name) shows whole, a long one leaves /// the actions room. static const double maxTitleShare = 0.5; /// Bar text grows with the reader's setting up to this factor, like the /// stock app bar caps its title, so the bar never takes over the page. static const double maxTextScale = 2; @override Size get preferredSize { final piece = segmentedPieceHeight(cupertino); if (cupertino) { // CupertinoPageScaffold disables text scaling for its navigation bar // and reserves exactly this height for it. return Size.fromHeight(_topPadding + piece + bottomPadding); } // A Material scaffold only caps its app bar at this height and lets it // size to its content: room for a title and subtitle at the largest // text scale. return Size.fromHeight(_topPadding + piece * maxTextScale + bottomPadding); } @override // Content scrolls behind the bar; the scaffold insets it by the bar's // height through the media padding instead. bool shouldFullyObstruct(BuildContext context) => false; Color _background(BuildContext context) { if (backgroundColor case final color?) { // A dynamic system colour (the grouped background) follows the theme. return CupertinoDynamicColor.maybeResolve(color, context) ?? color; } if (cupertino) { return context .dependOnInheritedWidgetOfExactType< CupertinoPageScaffoldBackgroundColor >() ?.color ?? CupertinoTheme.of(context).scaffoldBackgroundColor; } return Scaffold.maybeOf(context)?.widget.backgroundColor ?? Theme.of(context).scaffoldBackgroundColor; } @override State createState() => _SegmentedBarState(); } class _SegmentedBarState extends State { bool _expanded = false; /// The expanded title is drawn in the overlay, anchored to the collapsed /// pill: drawn inside the bar it would overflow the bar's bounds, where /// its pipeline action could be seen but not tapped. final _titleLink = LayerLink(); final _expandedTitle = OverlayPortalController(); /// The row's pieces sit side by side, so they share one read of the /// content behind them. The expanded title overlaps the content below the /// bar and is drawn later, in the overlay, so it reads its own. final _piecesBackdrop = BackdropKey(); final _expandedTitleBackdrop = BackdropKey(); /// When each piece pops in: in turn from the leading edge on the bar's /// first frame, at once (or in turn with those arriving together) later. final _entrances = SegmentedEntrancePlanner(); @override void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback((_) => _entrances.markShown()); } @override void didUpdateWidget(covariant SegmentedBar oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.title != widget.title || oldWidget.subtitle != widget.subtitle) { _expanded = false; } } void _toggleTitle() { // The portal stays attached once used and draws nothing while // collapsed, so collapsing on a new run (during a rebuild) needs no // overlay call. if (!_expandedTitle.isShowing) _expandedTitle.show(); setState(() => _expanded = !_expanded); } /// The bar's main pill: the [SegmentedBar.titleWidget] filling the row, or /// the title pill (drawn expanded in the overlay when it is expandable). Widget _titleIsland( BuildContext context, Widget Function(bool expanded) titlePill, ) { final titleWidget = widget.titleWidget; if (titleWidget != null) { // The main pill fills the row, up to its cap. return ConstrainedBox( constraints: BoxConstraints(maxWidth: widget.titleWidgetMaxWidth), child: SegmentedPill( cupertino: widget.cupertino, fill: widget.pillColor, child: SizedBox(width: double.infinity, child: titleWidget), ), ); } if (!widget.expandableTitle) return titlePill(false); return LayoutBuilder( builder: (context, titleSpace) => OverlayPortal( controller: _expandedTitle, overlayChildBuilder: (context) => !(_expanded && widget.expandableTitle) ? const SizedBox.shrink() : Positioned( top: 0, left: 0, child: CompositedTransformFollower( link: _titleLink, showWhenUnlinked: false, child: ConstrainedBox( constraints: BoxConstraints(maxWidth: titleSpace.maxWidth), child: BackdropGroup( backdropKey: _expandedTitleBackdrop, child: titlePill(true), ), ), ), ), child: CompositedTransformTarget( link: _titleLink, child: ExcludeSemantics( excluding: _expanded && widget.expandableTitle, child: titlePill(false), ), ), ), ); } /// Which actions (by identity) a narrow bar moved into its More menu. Set _overflowed = const {}; void _hidden(List ids, List indexes) { if (!mounted) return; final next = { for (final index in indexes) if (index < ids.length) ids[index], }; if (setEquals(next, _overflowed)) return; setState(() => _overflowed = next); } /// The actions, each keyed by its identity ([segmentedActionIds]) so one /// arriving or leaving leaves the others be, each popping in on its own, /// at its natural width. Those that do not fit leave for the trailing More /// button ([SegmentedActionRow]), so none is squeezed below its touch /// target; one moved there is out of the focus order too. Widget _actionRow( List actions, List ids, List entrances, { required bool cupertino, required double overflowWidth, }) { final entries = [ for (final (index, action) in actions.indexed) if (action is SegmentedOverflowable && _overflowed.contains(ids[index])) (action as SegmentedOverflowable).overflowEntry, ]; return SegmentedActionRow( overflowable: [ for (final action in actions) action is SegmentedOverflowable, ], overflowWidth: overflowWidth, onHidden: (indexes) => _hidden(ids, indexes), more: ExcludeFocus( excluding: entries.isEmpty, child: SegmentedPress( cupertino: cupertino, tint: widget.foregroundColor, child: SegmentedMoreButton(cupertino: cupertino, entries: entries), ), ), actions: [ for (final (index, action) in actions.indexed) ExcludeFocus( key: ValueKey(ids[index]), excluding: _overflowed.contains(ids[index]), child: PopEntrance( play: entrances[index].play, delay: entrances[index].delay, glass: false, child: SegmentedPress( cupertino: cupertino, tint: widget.foregroundColor, enabled: actions.length > 1, child: widget.separateActionIslands ? Padding( padding: EdgeInsetsDirectional.only( start: index == 0 ? 0 : 8, ), child: SegmentedPill( cupertino: cupertino, fill: widget.pillColor, child: action, ), ) : action, ), ), ), ], ); } Widget _actionsIsland({ required bool cupertino, Color? fill, required Widget child, }) => widget.separateActionIslands ? child : SegmentedPill(cupertino: cupertino, fill: fill, child: child); @override Widget build(BuildContext context) { final cupertino = widget.cupertino; final title = widget.title; final titleWidget = widget.titleWidget; final leadingWidget = widget.leading; final automaticallyImplyLeading = widget.automaticallyImplyLeading; final subtitle = widget.subtitle; final subtitleIcon = widget.subtitleIcon; final onTitlePressed = widget.onTitlePressed; final titleSemanticLabel = widget.titleSemanticLabel; final titleKey = widget.titleKey; final actions = widget.actions; final pillColor = widget.pillColor; final foregroundColor = widget.foregroundColor; final bottomPadding = widget.bottomPadding; final leading = leadingWidget ?? (automaticallyImplyLeading ? impliedSegmentedLeading(context, cupertino) : null); final showTitle = title.isNotEmpty || (subtitle ?? '').isNotEmpty; Widget titlePill(bool expanded) => SegmentedTitlePill( cupertino: cupertino, title: title, subtitle: subtitle, subtitleIcon: subtitleIcon, onPressed: widget.expandableTitle ? _toggleTitle : onTitlePressed, semanticLabel: widget.expandableTitle ? '${titleSemanticLabel ?? title}, ${expanded ? 'expanded' : 'collapsed'}' : titleSemanticLabel, buttonKey: expanded ? null : titleKey, expanded: expanded, titleAction: expanded ? widget.titleAction : null, leading: widget.titleLeading, foreground: foregroundColor, fill: pillColor, ); // Each island is keyed by its role (and each action by its identity), so // it keeps its entrance (and plays none) while the bar rebuilds around // it. final hasTitle = titleWidget != null || showTitle; final actionIds = segmentedActionIds(actions, widget.actionsKey); final entrances = _entrances.plan( leading: leading != null, title: hasTitle, actionIds: actionIds, ); final Widget bar = LayoutBuilder( builder: (context, constraints) { // The actions keep to the trailing edge at their natural width, so // a model name shows whole while the title has room. The title keeps // at least [SegmentedBar.minTitleShare] of the bar, and its own // width (a destination's name) up to [SegmentedBar.maxTitleShare]; // actions that do not fit beside it move into the More menu. final width = constraints.maxWidth; final titleMinimum = titleWidget != null || !showTitle ? width * SegmentedBar.minTitleShare : math.max( width * SegmentedBar.minTitleShare, math.min( segmentedTitleWidth( context, cupertino: cupertino, title: title, subtitle: subtitle, subtitleIcon: subtitleIcon, foreground: foregroundColor, ), width * SegmentedBar.maxTitleShare, ), ); final minimumTitleShare = widget.separateActionIslands ? .10 : SegmentedBar.minTitleShare; final besideTitle = width - (leading == null ? 0 : segmentedPieceHeight(cupertino) + 8) - 8; // Actions that cannot move (a model picker) may take the room down // to the title's minimum share; the rest leave for the More menu // before the title goes under its own width. final actionsMaxWidth = math.max( 0.0, besideTitle - width * minimumTitleShare, ); final overflowWidth = math.max(0.0, besideTitle - titleMinimum); return Row( children: [ if (leading != null) ...[ PopEntrance( key: const ValueKey('segmented.leading'), delay: entrances.leading, child: SegmentedPress( cupertino: cupertino, tint: foregroundColor, child: SegmentedPill( cupertino: cupertino, fill: pillColor, child: leading, ), ), ), const SizedBox(width: 8), ], Expanded( // Only as tall as the title: a Material scaffold offers its app // bar more height than it needs. child: Align( alignment: AlignmentDirectional.centerStart, heightFactor: 1, child: !hasTitle ? const SizedBox.shrink() : PopEntrance( key: ValueKey( titleWidget != null ? 'segmented.field' : 'segmented.title', ), delay: entrances.title, child: _titleIsland(context, titlePill), ), ), ), if (actions.isNotEmpty) ...[ const SizedBox(width: 8), ConstrainedBox( constraints: BoxConstraints(maxWidth: actionsMaxWidth), child: PopEntrance( key: const ValueKey('segmented.actions'), delay: entrances.pill, // A lone action is the whole pill, so the pill sinks when it // is pressed; beside others, each action sinks on its own. child: SegmentedPress( cupertino: cupertino, tint: foregroundColor, enabled: actions.length == 1, child: _actionsIsland( cupertino: cupertino, fill: pillColor, child: _actionRow( actions, actionIds, entrances.actions, cupertino: cupertino, overflowWidth: overflowWidth, ), ), ), ), ), ], ], ); }, ); final background = widget._background(context); final inset = MediaQuery.paddingOf(context).top; // A wide window's extra top margin arrives in the top padding (see // WindowMargins), so the reserved height stays the bar's own. final side = WindowMargins.sideOf(context); return Stack( children: [ // The scrim: the page's background, opaque at the edge and fading out // towards the content, so content scrolled behind the pieces still // reads. It takes no taps; only the pieces do. Positioned.fill( child: IgnorePointer( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ SizedBox( height: inset, child: ColoredBox(color: background), ), Expanded( child: DecoratedBox( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ background, background.withValues(alpha: background.a * 0.95), background.withValues(alpha: 0), ], stops: const [0, 0.5, 1], ), ), ), ), ], ), ), ), if (widget.backdrop case final backdrop?) Positioned.fill(child: IgnorePointer(child: backdrop)), SafeArea( bottom: false, child: Padding( padding: EdgeInsetsDirectional.fromSTEB( side, SegmentedBar._topPadding, side, bottomPadding, ), // In a window, iPadOS draws its window controls over the top // corner, outside the safe area: the pieces move clear of them. child: WindowControlsClearance( child: MediaQuery.withClampedTextScaling( maxScaleFactor: SegmentedBar.maxTextScale, child: BackdropGroup(backdropKey: _piecesBackdrop, child: bar), ), ), ), ), ], ); } }