Merge: tab bar — sliding highlight, no entrance replay on switches

This commit is contained in:
2026-11-02 15:59:26 +00:00
5 changed files with 766 additions and 219 deletions
+185 -197
View File
@@ -4,8 +4,8 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'floating_bar_layout.dart';
import 'floating_tab_motion.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
@@ -16,10 +16,13 @@ import '../motion/motion.dart';
/// [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.
/// One tinted circle sits behind the selected tab's icon and glides to a
/// newly selected tab. At rest it keeps the same gap from its neighbours' slots
/// as from the pill's top and bottom, and at the outer tabs the same gap from
/// the pill's sides, so the pill's round ends are concentric with it.
///
/// The tabs pop in when the bar appears or its set of tabs changes, never
/// when only the selection does.
///
/// 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
@@ -29,7 +32,7 @@ import '../motion/motion.dart';
/// [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 {
class FloatingDestinationBar extends StatefulWidget {
const FloatingDestinationBar({
super.key,
required this.cupertino,
@@ -93,9 +96,66 @@ class FloatingDestinationBar extends StatelessWidget {
/// The side margin at [FloatingBarEdge.top], matching the top bar's own.
static const double topMargin = 12;
/// The selection highlight inside each bar, for tests.
static const Key highlightKey = ValueKey(
'floating-destination-bar.highlight',
);
/// 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;
@override
State<FloatingDestinationBar> createState() => _FloatingDestinationBarState();
}
class _FloatingDestinationBarState extends State<FloatingDestinationBar>
with TickerProviderStateMixin {
late final FloatingTabMotion _motion = FloatingTabMotion(this);
bool _entered = false;
bool get cupertino => widget.cupertino;
List<FloatingDestinationItem> get items => widget.items;
int get currentIndex => widget.currentIndex;
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (_entered) return;
_entered = true;
_motion.enter(context, count: items.length, selected: currentIndex);
}
@override
void didUpdateWidget(FloatingDestinationBar oldWidget) {
super.didUpdateWidget(oldWidget);
if (_tabSetIdentity(oldWidget.items) != _tabSetIdentity(items)) {
// New tabs (a run's page tabs appearing): they pop in, and the
// highlight starts on the selected one.
_motion.enter(context, count: items.length, selected: currentIndex);
} else if (oldWidget.currentIndex != currentIndex) {
_motion.select(context, currentIndex);
}
}
@override
void dispose() {
_motion.dispose();
super.dispose();
}
static String _tabSetIdentity(List<FloatingDestinationItem> items) =>
items.map((item) => '${item.key ?? item.label}:${item.label}').join('|');
@override
Widget build(BuildContext context) {
final top = edge == FloatingBarEdge.top;
final top = widget.edge == FloatingBarEdge.top;
final bar = LayoutBuilder(
builder: (context, constraints) {
final width = math.max(0.0, math.min(constraints.maxWidth, _tabsWidth));
@@ -120,8 +180,11 @@ class FloatingDestinationBar extends StatelessWidget {
child: GlassPill(
cupertino: cupertino,
child: _edgeAligned(
context,
width,
cupertino ? _cupertinoBar(context) : _materialBar(context),
cupertino
? _cupertinoBar(context, _slot(width))
: _materialBar(context),
),
),
),
@@ -133,7 +196,12 @@ class FloatingDestinationBar extends StatelessWidget {
// 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),
padding: const EdgeInsets.fromLTRB(
FloatingDestinationBar.topMargin,
0,
FloatingDestinationBar.topMargin,
8,
),
child: bar,
);
}
@@ -149,74 +217,114 @@ class FloatingDestinationBar extends StatelessWidget {
);
}
double get _highlight =>
cupertino ? cupertinoHighlightSize : materialHighlightSize;
double get _gap => cupertino ? cupertinoEdgeGap : materialEdgeGap;
double get _neighbourGap =>
cupertino ? cupertinoNeighbourGap : materialNeighbourGap;
double get _highlight => cupertino
? FloatingDestinationBar.cupertinoHighlightSize
: FloatingDestinationBar.materialHighlightSize;
double get _gap => cupertino
? FloatingDestinationBar.cupertinoEdgeGap
: FloatingDestinationBar.materialEdgeGap;
double get _neighbourGap => cupertino
? FloatingDestinationBar.cupertinoNeighbourGap
: FloatingDestinationBar.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);
double get _tabsWidth => FloatingDestinationBar.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;
/// The gap between neighbouring circles in a pill [width] wide: the named
/// one, or less in a pill squeezed below its tabs' width.
double _neighbour(double width) {
final count = items.length;
if (count < 2) return _neighbourGap;
final available = math.max(0.0, width - 2 * _gap - count * _highlight);
return math.min(_neighbourGap, available / (count - 1));
}
/// The width of each equal tab slot, which is also the distance between
/// neighbouring circles' centres.
double _slot(double width) => _highlight + math.max(0, _neighbour(width));
bool get _hasSelection => currentIndex >= 0 && currentIndex < items.length;
/// 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) {
/// the circles still fit side by side. The Material highlight is laid over
/// the first slot, behind the host bar.
Widget _edgeAligned(BuildContext context, double width, Widget bar) {
final count = items.length;
if (count < 2) return bar;
if (count == 0) 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;
final slot = _slot(width);
final offset = _gap - _neighbour(width) / 2;
return ClipRect(
child: SizedBox(
width: width,
height: cupertino ? cupertinoHeight : materialHeight,
height: cupertino
? FloatingDestinationBar.cupertinoHeight
: FloatingDestinationBar.materialHeight,
child: OverflowBox(
alignment: AlignmentDirectional.topStart,
minWidth: 0,
maxWidth: double.infinity,
child: Transform.translate(
offset: Offset(offset, 0),
child: SizedBox(width: barWidth, child: bar),
child: SizedBox(
width: slot * count,
child: Stack(
fit: StackFit.expand,
children: [
if (!cupertino && _hasSelection)
PositionedDirectional(
start: 0,
top: 0,
bottom: 0,
width: slot,
child: _highlightFor(context, slot),
),
bar,
],
),
),
),
),
),
);
}
/// The bar's one selection highlight, laid out over tab 0.
Widget _highlightFor(BuildContext context, double slot) =>
FloatingTabHighlight(
key: FloatingDestinationBar.highlightKey,
motion: _motion,
slot: slot,
size: _highlight,
color: cupertino
? CupertinoTheme.of(context).primaryColor.withValues(alpha: 0.16)
: Theme.of(context).colorScheme.secondaryContainer,
);
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.
// The bar draws one gliding highlight behind the icons (the stock
// indicator is a fixed 64x32 that jumps); the stock one stays for
// its circular ink response.
indicatorColor: Colors.transparent,
indicatorShape: CircleBorder(),
height: materialHeight,
height: FloatingDestinationBar.materialHeight,
iconTheme: WidgetStatePropertyAll(
IconThemeData(size: materialIconSize),
IconThemeData(size: FloatingDestinationBar.materialIconSize),
),
// Icons only; the label remains each tab's accessible name and its
// tooltip.
@@ -224,19 +332,15 @@ class FloatingDestinationBar extends StatelessWidget {
),
child: NavigationBar(
selectedIndex: currentIndex,
onDestinationSelected: onTap,
onDestinationSelected: widget.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,
),
icon: _icon(items[index].icon, index),
selectedIcon: _icon(
items[index].selectedIcon ?? items[index].icon,
index,
),
label: items[index].label,
),
@@ -247,30 +351,42 @@ class FloatingDestinationBar extends StatelessWidget {
/// 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;
/// the whole tab, and the highlight behind the selected icon makes the
/// selection read at a glance, not by colour alone.
///
/// The host blurs whatever is behind its translucent background, so the
/// highlight is painted from inside tab 0, under the icons but above the
/// blur.
Widget _cupertinoBar(BuildContext context, double slot) {
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);
final icon = _icon(
selected ? item.selectedIcon ?? item.icon : 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),
// centres the icon and its highlight in the whole bar, so the
// highlight is as far from the pill's top as from its bottom.
child: Padding(
padding: const EdgeInsets.only(top: 4),
child: index == 0 && _hasSelection
? Stack(
clipBehavior: Clip.none,
alignment: Alignment.center,
children: [
Positioned.fill(child: _highlightFor(context, slot)),
icon,
],
)
: icon,
),
),
);
}
@@ -283,10 +399,10 @@ class FloatingDestinationBar extends StatelessWidget {
// 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,
iconSize: FloatingDestinationBar.cupertinoIconSize,
height: FloatingDestinationBar.cupertinoHeight,
currentIndex: currentIndex,
onTap: onTap,
onTap: widget.onTap,
items: [
for (var index = 0; index < items.length; index += 1)
BottomNavigationBarItem(
@@ -298,138 +414,10 @@ class FloatingDestinationBar extends StatelessWidget {
);
}
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),
);
/// Tab [index]'s icon, animated by the bar: the host swaps a tab's icon
/// subtree on selection, so the icon itself holds no animation state.
Widget _icon(Widget child, int index) =>
FloatingTabEntrance(motion: _motion, index: index, child: child);
}
/// The platform-neutral data needed by [FloatingDestinationBar].
@@ -0,0 +1,251 @@
import 'dart:math' as math;
import 'package:flutter/widgets.dart';
import '../motion/motion.dart';
/// The animations of one floating tab bar: its tabs popping in, the
/// selection highlight gliding between tabs and the newly selected icon's
/// bounce.
///
/// They live with the bar, not with each tab's icon, because the host
/// navigation controls rebuild a tab's icon subtree whenever it is selected
/// or deselected: state kept in the icons would restart with every tap.
class FloatingTabMotion {
FloatingTabMotion(TickerProvider vsync)
: entrance = AnimationController(vsync: vsync),
slide = AnimationController(
vsync: vsync,
duration: Motion.tabHighlightDuration,
value: 1,
),
bounce = AnimationController(
vsync: vsync,
duration: Motion.tabBounceDuration,
value: 1,
);
/// Drives every tab's entrance; tab n plays its pop in its own window.
final AnimationController entrance;
final AnimationController slide;
final AnimationController bounce;
int _count = 0;
final List<({Animation<double> pop, Animation<double> opacity})> _entrances =
[];
double _from = 0;
int _to = 0;
/// Plays the entrance of a bar of [count] tabs, from the start, and places
/// the highlight on [selected] without a move.
void enter(
BuildContext context, {
required int count,
required int selected,
}) {
_count = count;
final duration = Motion.of(context, Motion.tabEntranceDuration);
entrance.duration =
duration + Motion.tabEntranceStagger * math.max(0, count - 1);
if (duration == Duration.zero) {
entrance.value = 1;
} else {
entrance.forward(from: 0);
}
_splitEntrance();
_from = selected.toDouble();
_to = selected;
slide.value = 1;
bounce.value = 1;
}
/// Glides the highlight from where it is now to [selected] and bounces
/// that tab's icon. Under reduced motion the highlight jumps.
void select(BuildContext context, int selected) {
if (selected == _to) return;
_from = position;
_to = selected;
if (Motion.of(context, Motion.tabHighlightDuration) == Duration.zero) {
slide.value = 1;
bounce.value = 1;
return;
}
slide.forward(from: 0);
bounce.forward(from: 0);
}
double get _travel => Motion.curve.transform(slide.value);
/// The highlight's position in tab slots: 1.5 is halfway from tab 1 to 2.
double get position => _from + (_to - _from) * _travel;
/// The highlight's width over its height: 1 at rest, at most
/// [Motion.tabHighlightStretch] halfway through a move.
double get stretch => _from == _to
? 1
: 1 + (Motion.tabHighlightStretch - 1) * math.sin(math.pi * _travel);
/// The scale of tab [index]'s icon: only the newly selected one bounces.
double scaleOf(int index) {
if (index != _to || bounce.isCompleted) return 1;
final t = bounce.value;
final rise = t < 0.5 ? t * 2 : (1 - t) * 2;
return 1 + (Motion.tabBounceScale - 1) * Curves.easeOut.transform(rise);
}
/// Tab [index]'s share of [entrance]: its pop, then its fade.
({Animation<double> pop, Animation<double> opacity}) entranceOf(int index) =>
index >= 0 && index < _entrances.length
? _entrances[index]
: (pop: kAlwaysCompleteAnimation, opacity: kAlwaysCompleteAnimation);
/// Splits [entrance] into each tab's window, once per entrance.
void _splitEntrance() {
_disposeEntrances();
final total = entrance.duration!.inMicroseconds;
if (total == 0) return;
final window = Motion.tabEntranceDuration.inMicroseconds;
for (var index = 0; index < _count; index += 1) {
final start = Motion.tabEntranceStagger.inMicroseconds * index;
final begin = (start / total).clamp(0.0, 1.0);
final end = ((start + window) / total).clamp(begin, 1.0);
final faded =
((start + window * Motion.tabEntranceOpacityPortion) / total).clamp(
begin,
1.0,
);
_entrances.add((
pop: CurvedAnimation(
parent: entrance,
curve: Interval(begin, end, curve: Curves.easeOutBack),
),
opacity: CurvedAnimation(
parent: entrance,
curve: Interval(begin, faded, curve: Curves.easeOut),
),
));
}
}
void _disposeEntrances() {
for (final animations in _entrances) {
(animations.pop as CurvedAnimation).dispose();
(animations.opacity as CurvedAnimation).dispose();
}
_entrances.clear();
}
void dispose() {
_disposeEntrances();
entrance.dispose();
slide.dispose();
bounce.dispose();
}
}
/// Tab [index]'s icon (or the highlight behind it) popping in with the bar,
/// and bouncing when it becomes selected.
class FloatingTabEntrance extends StatelessWidget {
const FloatingTabEntrance({
super.key,
required this.motion,
required this.index,
required this.child,
this.bounces = true,
});
final FloatingTabMotion motion;
final int index;
final bool bounces;
final Widget child;
@override
Widget build(BuildContext context) {
final entrance = motion.entranceOf(index);
return FadeTransition(
opacity: entrance.opacity,
// Tabs (and their badge counts) stay announced while they fade in.
alwaysIncludeSemantics: true,
child: AnimatedBuilder(
animation: Listenable.merge([entrance.pop, motion.bounce]),
child: child,
builder: (context, child) {
final pop = entrance.pop.value;
final scale =
Motion.tabEntranceScaleBegin +
(1 - Motion.tabEntranceScaleBegin) * pop;
return Transform.translate(
offset: Offset(0, (1 - pop) * Motion.tabEntranceSlideDistance),
child: Transform.scale(
scale: scale * (bounces ? motion.scaleOf(index) : 1),
child: child,
),
);
},
),
);
}
}
/// The one selection highlight of a bar, behind its icons: a circle of
/// [size] centred on the selected tab, gliding (and stretching along the way)
/// to a newly selected one. It takes no taps and says nothing; the host's
/// tabs carry the selected state.
///
/// It is laid out over tab 0 (its slot, or its icon) and paints itself
/// [slot] widths along the reading direction per tab, unclipped.
class FloatingTabHighlight extends StatelessWidget {
const FloatingTabHighlight({
super.key,
required this.motion,
required this.slot,
required this.size,
required this.color,
});
final FloatingTabMotion motion;
/// The distance between neighbouring tabs' centres.
final double slot;
final double size;
final Color color;
@override
Widget build(BuildContext context) {
final direction = Directionality.of(context) == TextDirection.rtl ? -1 : 1;
return IgnorePointer(
child: ExcludeSemantics(
child: AnimatedBuilder(
animation: motion.slide,
builder: (context, _) {
final width = size * motion.stretch;
return OverflowBox(
minWidth: 0,
minHeight: 0,
maxWidth: double.infinity,
maxHeight: double.infinity,
child: Transform.translate(
offset: Offset(direction * slot * motion.position, 0),
child: FloatingTabEntrance(
motion: motion,
index: motion.position.round(),
bounces: false,
child: SizedBox(
width: width,
height: size,
child: DecoratedBox(
decoration: ShapeDecoration(
color: color,
shape: const StadiumBorder(),
),
),
),
),
),
);
},
),
),
);
}
}
+13
View File
@@ -34,6 +34,19 @@ abstract final class Motion {
/// The fraction of a tab's entrance spent fading in.
static const double tabEntranceOpacityPortion = 0.6;
/// How long a tab bar's selection highlight takes to glide to a new tab.
static const Duration tabHighlightDuration = Duration(milliseconds: 250);
/// The highlight's width, relative to its height, halfway through a move;
/// it is a circle again at rest.
static const double tabHighlightStretch = 1.25;
/// The newly selected tab icon's brief bounce.
static const Duration tabBounceDuration = Duration(milliseconds: 180);
/// The icon's scale at the top of its bounce.
static const double tabBounceScale = 1.08;
static const Curve curve = Curves.easeOutCubic;
/// [duration], or zero under the system's reduce-motion setting.
@@ -65,19 +65,24 @@ void main() {
await tester.pumpAndSettle();
}
Rect circle(WidgetTester tester, int index) => tester.getRect(
find
.descendant(
of: find.byKey(tabKey(index)),
matching: find.byWidgetPredicate(
(widget) =>
widget is DecoratedBox &&
widget.decoration is ShapeDecoration &&
(widget.decoration as ShapeDecoration).shape is CircleBorder,
),
)
.first,
);
/// The bar's one selection highlight, at rest on tab [index].
Rect circle(WidgetTester tester, int index) {
final rect = tester.getRect(
find.descendant(
of: find.byKey(FloatingDestinationBar.highlightKey),
matching: find.byType(DecoratedBox),
),
);
final icon = tester.getCenter(
find.descendant(
of: find.byKey(tabKey(index)),
matching: find.byIcon(icons[index]),
),
);
expect(rect.center.dx, moreOrLessEquals(icon.dx, epsilon: 0.5));
expect(rect.center.dy, moreOrLessEquals(icon.dy, epsilon: 0.5));
return rect;
}
Rect pill(WidgetTester tester) => tester.getRect(
find.descendant(
@@ -169,17 +174,20 @@ void main() {
),
),
);
final entrance = find.descendant(
of: find.byType(FloatingDestinationBar),
matching: find.byWidgetPredicate(
(widget) =>
widget is FadeTransition && widget.child is AnimatedBuilder,
),
);
Finder entranceOf(int index) => find
.descendant(
of: find.byKey(tabKey(index)),
matching: find.byWidgetPredicate(
(widget) =>
widget is FadeTransition && widget.child is AnimatedBuilder,
),
)
.last;
final entrance = entranceOf(0);
double firstOpacity() =>
tester.widget<FadeTransition>(entrance.at(0)).opacity.value;
tester.widget<FadeTransition>(entranceOf(0)).opacity.value;
double lastOpacity() =>
tester.widget<FadeTransition>(entrance.at(2)).opacity.value;
tester.widget<FadeTransition>(entranceOf(2)).opacity.value;
expect(firstOpacity(), 0);
expect(lastOpacity(), 0);
await tester.pump(const Duration(milliseconds: 130));
@@ -0,0 +1,287 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/shell/adaptive_shell.dart';
import 'package:pipelines_app/shell/destination.dart';
import 'package:pipelines_app/ui/adaptive/floating_destination_bar.dart';
/// The floating tab bar's motion: the tabs pop in only when the bar appears
/// or its set of tabs changes, and one selection highlight glides (and
/// stretches on the way) to a newly selected tab, whose icon bounces.
void main() {
const icons = [
Icons.account_tree_outlined,
Icons.play_circle_outline,
Icons.chat_bubble_outline,
Icons.search,
];
Key tabKey(int index) => ValueKey('tab-$index');
List<FloatingDestinationItem> items(int count) => [
for (var index = 0; index < count; index += 1)
FloatingDestinationItem(
key: tabKey(index),
icon: Icon(icons[index]),
label: 'Tab $index',
),
];
void animate(WidgetTester tester, {required bool on}) {
tester.platformDispatcher.accessibilityFeaturesTestValue =
FakeAccessibilityFeatures(disableAnimations: !on);
addTearDown(() {
tester.platformDispatcher.accessibilityFeaturesTestValue =
const FakeAccessibilityFeatures(disableAnimations: true);
});
tester.view.physicalSize = const Size(560, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
}
/// A bar of [count] tabs whose tap selects.
Future<void> pumpBar(
WidgetTester tester, {
required bool cupertino,
int count = 3,
}) async {
var selected = 0;
final body = StatefulBuilder(
builder: (context, setState) {
return Align(
alignment: Alignment.bottomCenter,
child: FloatingDestinationBar(
cupertino: cupertino,
currentIndex: selected,
onTap: (index) => setState(() => selected = index),
items: items(count),
),
);
},
);
await tester.pumpWidget(
cupertino
? CupertinoApp(home: CupertinoPageScaffold(child: body))
: MaterialApp(home: Scaffold(body: body)),
);
}
/// The opacity of [tab]'s entrance fade.
double opacityOf(WidgetTester tester, Finder tab) => tester
.widget<FadeTransition>(
find
.descendant(
of: tab,
matching: find.byWidgetPredicate(
(widget) =>
widget is FadeTransition && widget.child is AnimatedBuilder,
),
)
.last,
)
.opacity
.value;
double iconWidth(WidgetTester tester, Finder tab, IconData icon) => tester
.getRect(find.descendant(of: tab, matching: find.byIcon(icon)))
.width;
Rect highlight(WidgetTester tester) => tester.getRect(
find.descendant(
of: find.byKey(FloatingDestinationBar.highlightKey),
matching: find.byType(DecoratedBox),
),
);
Offset iconCentre(WidgetTester tester, int index) => tester.getCenter(
find.descendant(
of: find.byKey(tabKey(index)),
matching: find.byIcon(icons[index]),
),
);
for (final cupertino in [false, true]) {
final host = cupertino ? 'Cupertino' : 'Material';
final iconSize = cupertino
? FloatingDestinationBar.cupertinoIconSize
: FloatingDestinationBar.materialIconSize;
final size = cupertino
? FloatingDestinationBar.cupertinoHighlightSize
: FloatingDestinationBar.materialHighlightSize;
testWidgets('$host: the entrance does not replay when the selection '
'changes, and plays again for a new set of tabs', (tester) async {
animate(tester, on: true);
await pumpBar(tester, cupertino: cupertino);
expect(opacityOf(tester, find.byKey(tabKey(0))), 0);
await tester.pumpAndSettle();
for (final target in [1, 2, 0]) {
await tester.tap(find.byKey(tabKey(target)));
for (var frame = 0; frame < 12; frame += 1) {
await tester.pump(const Duration(milliseconds: 25));
for (var index = 0; index < 3; index += 1) {
final tab = find.byKey(tabKey(index));
expect(opacityOf(tester, tab), 1, reason: 'tab $index faded');
// Only the bounce may grow an icon; a replayed pop shrinks it.
expect(
iconWidth(tester, tab, icons[index]),
greaterThanOrEqualTo(iconSize - 0.01),
reason: 'tab $index popped again',
);
}
}
}
});
testWidgets('$host: a new set of tabs pops in again', (tester) async {
animate(tester, on: true);
var count = 3;
late StateSetter update;
Widget build() => StatefulBuilder(
builder: (context, setState) {
update = setState;
return Align(
alignment: Alignment.bottomCenter,
child: FloatingDestinationBar(
cupertino: cupertino,
currentIndex: 0,
onTap: (_) {},
items: items(count),
),
);
},
);
await tester.pumpWidget(
cupertino
? CupertinoApp(home: CupertinoPageScaffold(child: build()))
: MaterialApp(home: Scaffold(body: build())),
);
await tester.pumpAndSettle();
expect(opacityOf(tester, find.byKey(tabKey(2))), 1);
update(() => count = 4);
await tester.pump();
expect(opacityOf(tester, find.byKey(tabKey(3))), 0);
expect(opacityOf(tester, find.byKey(tabKey(2))), 0);
await tester.pumpAndSettle();
expect(opacityOf(tester, find.byKey(tabKey(3))), 1);
});
testWidgets('$host: the highlight rests on the selected tab as the old '
'circle did, glides and stretches between tabs, and the new icon '
'bounces', (tester) async {
animate(tester, on: true);
await pumpBar(tester, cupertino: cupertino);
await tester.pumpAndSettle();
expect(
highlight(tester),
rectMoreOrLessEquals(
Rect.fromCenter(
center: iconCentre(tester, 0),
width: size,
height: size,
),
epsilon: 0.01,
),
);
expect(find.byKey(FloatingDestinationBar.highlightKey), findsOneWidget);
await tester.tap(find.byKey(tabKey(2)));
await tester.pump();
await tester.pump(const Duration(milliseconds: 60));
final from = iconCentre(tester, 0).dx;
final to = iconCentre(tester, 2).dx;
final moving = highlight(tester);
expect(moving.center.dx, greaterThan(from + 1));
expect(moving.center.dx, lessThan(to - 1));
expect(moving.height, moreOrLessEquals(size));
expect(moving.width, greaterThan(size * 1.1));
expect(moving.width, lessThanOrEqualTo(size * 1.25 + 0.01));
expect(
iconWidth(tester, find.byKey(tabKey(2)), icons[2]),
greaterThan(iconSize * 1.02),
);
await tester.pumpAndSettle();
expect(
highlight(tester),
rectMoreOrLessEquals(
Rect.fromCenter(
center: iconCentre(tester, 2),
width: size,
height: size,
),
epsilon: 0.01,
),
);
expect(
iconWidth(tester, find.byKey(tabKey(2)), icons[2]),
moreOrLessEquals(iconSize),
);
});
testWidgets('$host: under reduced motion the highlight jumps and the '
'icons neither pop nor bounce', (tester) async {
animate(tester, on: false);
await pumpBar(tester, cupertino: cupertino);
await tester.pump();
expect(opacityOf(tester, find.byKey(tabKey(1))), 1);
await tester.tap(find.byKey(tabKey(2)));
await tester.pump();
expect(
highlight(tester),
rectMoreOrLessEquals(
Rect.fromCenter(
center: iconCentre(tester, 2),
width: size,
height: size,
),
epsilon: 0.01,
),
);
expect(
iconWidth(tester, find.byKey(tabKey(2)), icons[2]),
moreOrLessEquals(iconSize),
);
});
testWidgets('$host: switching the shell tabs never replays the main '
"bar's entrance", (tester) async {
animate(tester, on: true);
var destination = AppDestination.runs;
final shell = StatefulBuilder(
builder: (context, setState) => AdaptiveShell(
cupertino: cupertino,
destination: destination,
onDestinationSelected: (value) => setState(() => destination = value),
),
);
await tester.pumpWidget(
cupertino ? CupertinoApp(home: shell) : MaterialApp(home: shell),
);
await tester.pumpAndSettle();
for (final next in [
AppDestination.pipelines,
AppDestination.chat,
AppDestination.runs,
]) {
await tester.tap(
find.byKey(ValueKey('shell.destination.${next.name}')),
);
for (var frame = 0; frame < 12; frame += 1) {
await tester.pump(const Duration(milliseconds: 25));
for (final tab in shellTabDestinations) {
expect(
opacityOf(
tester,
find.byKey(ValueKey('shell.destination.${tab.name}')),
),
1,
reason: '${tab.name} faded switching to ${next.name}',
);
}
}
await tester.pumpAndSettle();
}
});
}
}