Files
pipelines/app/lib/ui/adaptive/floating_destination_bar.dart
T
alan c742bb17f0 Merge branch 'main' into tab-pop-anim
# Conflicts:
#	app/lib/ui/adaptive/floating_destination_bar.dart
2026-11-01 17:05:54 +00:00

453 lines
15 KiB
Dart

import 'dart:math' as math;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'floating_bar_layout.dart';
import 'glass_pill.dart';
import '../motion/motion.dart';
/// A tab bar which floats above the bottom edge in a frosted [GlassPill]
/// instead of becoming a full-width system bar. Used for the app's
/// destinations and for every page's own tabs.
///
/// At any width the pill is only as wide as its icon tabs and sits at the
/// trailing (right, in left-to-right text) edge, near the thumb, keeping
/// [kFloatingBarMargin] from the sides and above the bottom safe area. Only
/// the pill takes taps: the space beside it reaches the content behind.
///
/// The selected tab's icon sits in a tinted circle. Each circle keeps the
/// same gap from its neighbours as from the pill's top and bottom, and the
/// outer ones the same gap from the pill's sides, so the pill's round ends
/// are concentric with them.
///
/// The tabs show icons only. Each tab's label stays its accessible name (and
/// the Material tooltip), so screen readers still announce it; the icons must
/// be distinct within a bar.
///
/// The controls inside remain the platform navigation controls (Material
/// [NavigationBar], Cupertino [CupertinoTabBar]), so tab semantics (selected
/// state, "tab n of m") come from the host. The Cupertino path builds no
/// Material widget.
class FloatingDestinationBar extends StatelessWidget {
const FloatingDestinationBar({
super.key,
required this.cupertino,
required this.currentIndex,
required this.onTap,
required this.items,
this.edge = FloatingBarEdge.bottom,
});
final bool cupertino;
/// The edge the bar floats at. At [FloatingBarEdge.top] (an open item's
/// tabs under its pane's top bar) the bar sits at the leading edge, in line
/// with the bar's title, and keeps no bottom safe area.
final FloatingBarEdge edge;
final int currentIndex;
final ValueChanged<int> onTap;
final List<FloatingDestinationItem> items;
/// The icon sizes used by the two host navigation controls.
static const double materialIconSize = 28;
static const double cupertinoIconSize = 30;
/// Padding between each icon and the edge of its selection circle.
static const double _materialRing = 8;
static const double _cupertinoRing = 6;
/// The gap between a circle and the pill's nearest edge or neighbour.
/// Keeping these as the source constants makes the bar grow with the icons.
static const double _materialEdgeGap = 8;
static const double _cupertinoEdgeGap = 6;
/// Diameter of the selection circle.
static const double materialHighlightSize =
materialIconSize + 2 * _materialRing;
static const double cupertinoHighlightSize =
cupertinoIconSize + 2 * _cupertinoRing;
/// Height of the host bar, derived from its circle and the equal edge gaps.
static const double materialHeight =
materialHighlightSize + 2 * _materialEdgeGap;
static const double cupertinoHeight =
cupertinoHighlightSize + 2 * _cupertinoEdgeGap;
/// The gap between a tab's circle and the pill's top and bottom; the outer
/// circles keep the same gap from the pill's sides, and neighbours from
/// each other.
static const double materialEdgeGap = _materialEdgeGap;
static const double cupertinoEdgeGap = _cupertinoEdgeGap;
/// The additional breathing room between neighbouring selection circles.
static const double materialNeighbourGap = 15;
static const double cupertinoNeighbourGap = 13;
/// Width of one equal native tab slot at the requested neighbour spacing.
static const double materialTabWidth =
materialHighlightSize + materialNeighbourGap;
static const double cupertinoTabWidth =
cupertinoHighlightSize + cupertinoNeighbourGap;
/// The side margin at [FloatingBarEdge.top], matching the top bar's own.
static const double topMargin = 12;
@override
Widget build(BuildContext context) {
final top = edge == FloatingBarEdge.top;
final bar = LayoutBuilder(
builder: (context, constraints) {
final width = math.max(0.0, math.min(constraints.maxWidth, _tabsWidth));
return Align(
// As tall as the pill, so a scaffold or overlay measures the bar
// and not the whole area it may grow into.
heightFactor: 1,
alignment: top
? AlignmentDirectional.topStart
: AlignmentDirectional.bottomEnd,
child: SizedBox(
width: width,
// The insets are handled around the pill. The host bars pad
// themselves by any media padding left over (a page's top bar,
// another floating bar below a pane), which would swell the pill.
child: MediaQuery.removePadding(
context: context,
removeTop: true,
removeBottom: true,
removeLeft: true,
removeRight: true,
child: GlassPill(
cupertino: cupertino,
child: _edgeAligned(
width,
cupertino ? _cupertinoBar(context) : _materialBar(context),
),
),
),
),
);
},
);
if (top) {
// Under a top bar: no safe area to keep clear of, only the gap to the
// content below.
return Padding(
padding: const EdgeInsets.fromLTRB(topMargin, 0, topMargin, 8),
child: bar,
);
}
return SafeArea(
top: false,
minimum: const EdgeInsets.fromLTRB(
kFloatingBarMargin,
0,
kFloatingBarMargin,
kFloatingBarMargin,
),
child: bar,
);
}
double get _highlight =>
cupertino ? cupertinoHighlightSize : materialHighlightSize;
double get _gap => cupertino ? cupertinoEdgeGap : materialEdgeGap;
double get _neighbourGap =>
cupertino ? cupertinoNeighbourGap : materialNeighbourGap;
/// The width the icon-only tabs need side by side. Icons do not scale with
/// text, so the pill keeps its size at any text scale.
double get _tabsWidth => pillWidth(cupertino: cupertino, tabs: items.length);
/// The width of a pill holding [tabs] tabs, when the space allows it.
static double pillWidth({required bool cupertino, required int tabs}) =>
cupertino
? cupertinoHighlightSize * tabs +
2 * cupertinoEdgeGap +
math.max(0, tabs - 1) * cupertinoNeighbourGap
: materialHighlightSize * tabs +
2 * materialEdgeGap +
math.max(0, tabs - 1) * materialNeighbourGap;
/// Insets the host bar's equal tab slots so the outer circles sit the edge
/// gap from the pill's sides. A pill squeezed below its tabs' width keeps
/// that gap and narrows the gaps between neighbours instead, as long as
/// the circles still fit side by side.
Widget _edgeAligned(double width, Widget bar) {
final count = items.length;
if (count < 2) return bar;
// The native bars use equal-width slots. Let their slot centers be the
// desired circle centers, and translate the slots by half the difference
// between the outer and neighbour gaps. The pill clips the harmless
// overflow of the native slot backgrounds, while the circles remain
// exactly edge-aligned.
final available = math.max(0.0, width - 2 * _gap - count * _highlight);
final neighbour = math.min(_neighbourGap, available / (count - 1));
final slot = _highlight + math.max(0, neighbour);
final barWidth = slot * count;
final offset = _gap - neighbour / 2;
return ClipRect(
child: SizedBox(
width: width,
height: cupertino ? cupertinoHeight : materialHeight,
child: OverflowBox(
alignment: AlignmentDirectional.topStart,
minWidth: 0,
maxWidth: double.infinity,
child: Transform.translate(
offset: Offset(offset, 0),
child: SizedBox(width: barWidth, child: bar),
),
),
),
);
}
Widget _materialBar(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return NavigationBarTheme(
data: const NavigationBarThemeData(
backgroundColor: Colors.transparent,
elevation: 0,
surfaceTintColor: Colors.transparent,
// The selected icon draws its own circle (the stock indicator is a
// fixed 64x32); the stock one stays for its circular ink response.
indicatorColor: Colors.transparent,
indicatorShape: CircleBorder(),
height: materialHeight,
iconTheme: WidgetStatePropertyAll(
IconThemeData(size: materialIconSize),
),
// Icons only; the label remains each tab's accessible name and its
// tooltip.
labelBehavior: NavigationDestinationLabelBehavior.alwaysHide,
),
child: NavigationBar(
selectedIndex: currentIndex,
onDestinationSelected: onTap,
destinations: [
for (var index = 0; index < items.length; index += 1)
NavigationDestination(
key: items[index].key,
icon: _entrance(items[index].icon, index),
selectedIcon: _SelectionCircle(
color: scheme.secondaryContainer,
ring: _materialRing,
child: _entrance(
items[index].selectedIcon ?? items[index].icon,
index,
),
),
label: items[index].label,
),
],
),
);
}
/// The stock Cupertino bar, transparent inside the pill. Each tab shows its
/// icon only, named by its label for accessibility; the item's key covers
/// the whole tab, and the selected tab's icon sits in a tinted circle so
/// the selection reads at a glance, not by colour alone.
Widget _cupertinoBar(BuildContext context) {
final active = CupertinoTheme.of(context).primaryColor;
Widget tab(
FloatingDestinationItem item, {
required bool selected,
required int index,
}) {
final icon = selected
? _SelectionCircle(
color: active.withValues(alpha: 0.16),
ring: _cupertinoRing,
child: _entrance(item.selectedIcon ?? item.icon, index),
)
: _entrance(item.icon, index);
return KeyedSubtree(
key: item.key,
child: Semantics(
label: item.label,
// The host centres the icon above a 4px bottom inset; 4 above it
// centres the icon and its circle in the whole bar, so the circle
// is as far from the pill's top as from its bottom.
child: Padding(padding: const EdgeInsets.only(top: 4), child: icon),
),
);
}
// The tab bar does not scale its text on iOS either; its height is fixed.
return MediaQuery.withNoTextScaling(
child: CupertinoTabBar(
backgroundColor: CupertinoColors.transparent,
border: null,
// Secondary-label translucency over glass falls below text contrast
// requirements. The host label role remains readable in both themes.
inactiveColor: CupertinoColors.label.resolveFrom(context),
iconSize: cupertinoIconSize,
height: cupertinoHeight,
currentIndex: currentIndex,
onTap: onTap,
items: [
for (var index = 0; index < items.length; index += 1)
BottomNavigationBarItem(
icon: tab(items[index], selected: false, index: index),
activeIcon: tab(items[index], selected: true, index: index),
),
],
),
);
}
Widget _entrance(Widget child, int index) => _TabEntrance(
key: ValueKey<Object?>('${_tabSetIdentity}_$index'),
index: index,
count: items.length,
child: child,
);
String get _tabSetIdentity =>
items.map((item) => '${item.key ?? item.label}:${item.label}').join('|');
}
class _TabEntrance extends StatefulWidget {
const _TabEntrance({
super.key,
required this.index,
required this.count,
required this.child,
});
final int index;
final int count;
final Widget child;
@override
State<_TabEntrance> createState() => _TabEntranceState();
}
class _TabEntranceState extends State<_TabEntrance>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
bool _started = false;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration:
Motion.tabEntranceDuration +
Motion.tabEntranceStagger * (widget.count - 1),
);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (_started) return;
_started = true;
final duration = Motion.of(context, Motion.tabEntranceDuration);
_controller.duration =
duration + Motion.tabEntranceStagger * (widget.count - 1);
if (duration == Duration.zero) {
_controller.value = 1;
} else {
_controller.forward();
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final total = _controller.duration!.inMicroseconds;
final start = Motion.tabEntranceStagger.inMicroseconds * widget.index;
final window = Motion.tabEntranceDuration.inMicroseconds;
final begin = total == 0 ? 0.0 : start / total;
final end = total == 0 ? 1.0 : (start + window) / total;
final pop = CurvedAnimation(
parent: _controller,
curve: Interval(
begin,
end.clamp(begin, 1.0).toDouble(),
curve: Curves.easeOutBack,
),
);
final opacity = CurvedAnimation(
parent: _controller,
curve: Interval(
begin,
total == 0
? 1.0
: (start + window * Motion.tabEntranceOpacityPortion)
.clamp(start, total)
.toDouble() /
total,
curve: Curves.easeOut,
),
);
return FadeTransition(
opacity: opacity,
// Tabs (and their badge counts) stay announced while they fade in.
alwaysIncludeSemantics: true,
child: AnimatedBuilder(
animation: pop,
child: widget.child,
builder: (context, child) => Transform.translate(
offset: Offset(0, (1 - pop.value) * Motion.tabEntranceSlideDistance),
child: Transform.scale(
scale: Tween<double>(
begin: Motion.tabEntranceScaleBegin,
end: 1,
).evaluate(pop),
child: child,
),
),
),
);
}
}
/// The selected tab's icon (and any badge on it) in a tinted circle, [ring]
/// wider than the icon on every side.
class _SelectionCircle extends StatelessWidget {
const _SelectionCircle({
required this.color,
required this.ring,
required this.child,
});
final Color color;
final double ring;
final Widget child;
@override
Widget build(BuildContext context) => DecoratedBox(
decoration: ShapeDecoration(color: color, shape: const CircleBorder()),
child: Padding(padding: EdgeInsets.all(ring), child: child),
);
}
/// The platform-neutral data needed by [FloatingDestinationBar].
class FloatingDestinationItem {
const FloatingDestinationItem({
required this.icon,
required this.label,
this.selectedIcon,
this.key,
});
final Widget icon;
/// The tab's accessible name (and Material tooltip); not drawn.
final String label;
final Widget? selectedIcon;
/// Identifies the whole tab, for tests and automation.
final Key? key;
}