Line data Source code
1 : import 'package:flutter/semantics.dart' show SemanticsRole;
2 : import 'package:flutter/services.dart';
3 : import 'package:flutter/widgets.dart';
4 : import 'package:fossui/src/foundation/foss_since.dart';
5 : import 'package:fossui/src/theme/theme.dart';
6 :
7 : part 'foss_bottom_nav_bar_style.dart';
8 : part 'foss_bottom_nav_bar_view.dart';
9 : part 'foss_bottom_nav_bar_visuals.dart';
10 :
11 : /// One destination in a [FossBottomNavBar]: its [value], [label], glyphs, an
12 : /// optional [badge], and whether it is [enabled].
13 : ///
14 : /// This is data passed to [FossBottomNavBar.items], not a widget, so the bar
15 : /// owns the icon size, the colors, and the layout of every cell. [label] is
16 : /// required: it is the name the cell announces.
17 : ///
18 : /// ```dart
19 : /// const FossBottomNavItem(
20 : /// value: 'home',
21 : /// label: 'Home',
22 : /// icon: Icon(homeIcon),
23 : /// );
24 : /// ```
25 : @immutable
26 : @FossSince('0.1.3')
27 : class FossBottomNavItem<T> {
28 : /// Creates a destination carrying [value] and [label].
29 1 : const FossBottomNavItem({
30 : required this.value,
31 : required this.label,
32 : this.icon,
33 : this.selectedIcon,
34 : this.badge,
35 : this.enabled = true,
36 : });
37 :
38 : /// The value this destination reports. Unique within a [FossBottomNavBar].
39 : final T value;
40 :
41 : /// The text under the glyph, and the name the cell announces.
42 : final String label;
43 :
44 : /// The glyph above the label, sized and colored by the bar. Any widget; no
45 : /// icon dependency.
46 : final Widget? icon;
47 :
48 : /// Replaces [icon] while this destination is current, for a filled variant
49 : /// of an outline glyph. Null keeps [icon] and changes only its color.
50 : final Widget? selectedIcon;
51 :
52 : /// A marker pinned just outside the glyph's top end corner, for a count or a
53 : /// dot. Decorative: put anything it conveys into [label].
54 : final Widget? badge;
55 :
56 : /// Whether the destination accepts focus and taps. A disabled cell dims and
57 : /// is skipped by the keyboard.
58 : final bool enabled;
59 : }
60 :
61 : /// {@category Layout}
62 : /// {@template foss.bottom_nav_bar.preview}
63 : /// <img src="https://fossui.org/components/bottom-nav-bar/overview/light.png"
64 : /// alt="FossBottomNavBar, light theme" width="480"
65 : /// style="max-width:100%;height:auto" />
66 : /// <img src="https://fossui.org/components/bottom-nav-bar/overview/dark.png"
67 : /// alt="FossBottomNavBar, dark theme" width="480"
68 : /// style="max-width:100%;height:auto" />
69 : ///
70 : /// See the
71 : /// [bottom nav bar documentation ↗](https://fossui.org/docs/components/bottom-nav-bar)
72 : /// or try it live in the
73 : /// [playground ↗](https://play.fossui.org/components/#/?path=components/bottom_nav_bar/fossbottomnavbar/playground).
74 : /// {@endtemplate}
75 : ///
76 : /// A strip of top-level destinations for the bottom of a phone screen: three to
77 : /// five cells, each a glyph over a short label, one of them current.
78 : ///
79 : /// The bar is controlled. Pass [value] for the current destination and
80 : /// [onChanged] to hear about taps; it holds no selection state of its own,
81 : /// because the current destination is usually owned by a route or a restored
82 : /// session. Each [FossBottomNavItem] in [items] carries its label, its glyphs,
83 : /// an optional badge, and an enabled flag.
84 : ///
85 : /// [onChanged] fires on every tap, including a tap on the destination that is
86 : /// already current, so an app can hang "scroll to top" or "pop to root" off the
87 : /// second tap. A null [onChanged] dims every destination and takes no input; a
88 : /// single one goes inert through [FossBottomNavItem.enabled].
89 : ///
90 : /// The bar adds the bottom safe-area inset below itself and paints its fill
91 : /// through it, so place it at the bottom of the screen without wrapping it in a
92 : /// `SafeArea`. Colors and type come from `context.fossTheme`; pass a
93 : /// [FossBottomNavBarStyle] to [style] for a one-off.
94 : ///
95 : /// {@macro foss.customize}
96 : ///
97 : /// ```dart
98 : /// FossBottomNavBar<String>(
99 : /// value: section,
100 : /// onChanged: (v) => setState(() => section = v),
101 : /// items: const [
102 : /// FossBottomNavItem(value: 'home', label: 'Home', icon: Icon(homeIcon)),
103 : /// FossBottomNavItem(value: 'you', label: 'You', icon: Icon(userIcon)),
104 : /// ],
105 : /// );
106 : /// ```
107 : @FossSince('0.1.3')
108 : class FossBottomNavBar<T> extends StatefulWidget {
109 : /// {@macro foss.bottom_nav_bar.preview}
110 : ///
111 : /// Creates a bottom navigation bar over [items], with [value] current.
112 1 : const FossBottomNavBar({
113 : required this.items,
114 : required this.value,
115 : this.onChanged,
116 : this.style,
117 : super.key,
118 : });
119 :
120 : /// The ordered destinations. Two at minimum; three to five reads best, past
121 : /// which the labels stop fitting on a phone.
122 : final List<FossBottomNavItem<T>> items;
123 :
124 : /// The current destination. Matches the [FossBottomNavItem.value] of one of
125 : /// [items].
126 : final T value;
127 :
128 : /// Called with a destination's value on every tap, including a tap on the
129 : /// current one. Null makes the bar inert.
130 : final ValueChanged<T>? onChanged;
131 :
132 : /// Per-instance overrides layered on the theme-resolved style.
133 : final FossBottomNavBarStyle? style;
134 :
135 1 : @override
136 1 : State<FossBottomNavBar<T>> createState() => _FossBottomNavBarState<T>();
137 : }
138 :
139 : class _FossBottomNavBarState<T> extends State<FossBottomNavBar<T>> {
140 : final Map<T, FocusNode> _nodes = <T, FocusNode>{};
141 :
142 3 : bool get _live => widget.onChanged != null;
143 :
144 1 : @override
145 : void initState() {
146 1 : super.initState();
147 1 : assert(_debugItemsValid(), 'Invalid items.');
148 : }
149 :
150 1 : @override
151 : void didUpdateWidget(FossBottomNavBar<T> oldWidget) {
152 1 : super.didUpdateWidget(oldWidget);
153 1 : assert(_debugItemsValid(), 'Invalid items.');
154 : // Drop nodes for destinations that no longer exist.
155 6 : final values = widget.items.map((i) => i.value).toSet();
156 6 : final stale = _nodes.keys.where((v) => !values.contains(v)).toList();
157 2 : for (final value in stale) {
158 3 : _nodes.remove(value)?.dispose();
159 : }
160 : }
161 :
162 1 : @override
163 : void dispose() {
164 3 : for (final node in _nodes.values) {
165 1 : node.dispose();
166 : }
167 1 : super.dispose();
168 : }
169 :
170 : // These checks cannot live in the constructor without giving up `const`: a
171 : // list's length and contents are not const expressions. A duplicate value
172 : // collides in the focus-node map and a value outside the set leaves no cell
173 : // current, so both are caught here instead.
174 1 : bool _debugItemsValid() {
175 6 : final values = widget.items.map((i) => i.value).toList();
176 : assert(
177 3 : values.length >= 2,
178 : 'A bottom nav bar needs at least 2 items.',
179 : );
180 : assert(
181 5 : values.toSet().length == values.length,
182 : 'Item values must be unique.',
183 : );
184 4 : assert(values.contains(widget.value), 'value must match one of the items.');
185 : return true;
186 : }
187 :
188 3 : FocusNode _nodeFor(T value) => _nodes.putIfAbsent(value, FocusNode.new);
189 :
190 : // Reports every tap, with no guard on the tapped value already being current:
191 : // apps hang scroll-to-top and pop-to-root off the second tap.
192 4 : void _select(T value) => widget.onChanged?.call(value);
193 :
194 : // Walks from [from] by [step], skipping disabled destinations, without
195 : // wrapping.
196 1 : int? _adjacent(int from, int step) {
197 7 : for (var i = from + step; i >= 0 && i < widget.items.length; i += step) {
198 4 : if (widget.items[i].enabled) return i;
199 : }
200 : return null;
201 : }
202 :
203 1 : int? _edge(bool last) {
204 5 : final indices = List<int>.generate(widget.items.length, (i) => i);
205 3 : for (final i in last ? indices.reversed : indices) {
206 4 : if (widget.items[i].enabled) return i;
207 : }
208 : return null;
209 : }
210 :
211 1 : KeyEventResult _onKey(KeyEvent event, int index) {
212 2 : if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
213 : return KeyEventResult.ignored;
214 : }
215 1 : final key = event.logicalKey;
216 2 : if (key == LogicalKeyboardKey.space || key == LogicalKeyboardKey.enter) {
217 5 : _select(widget.items[index].value);
218 : return KeyEventResult.handled;
219 : }
220 :
221 3 : final ltr = Directionality.of(context) == TextDirection.ltr;
222 : final target = switch (key) {
223 2 : LogicalKeyboardKey.home => _edge(false),
224 2 : LogicalKeyboardKey.end => _edge(true),
225 3 : LogicalKeyboardKey.arrowRight => _adjacent(index, ltr ? 1 : -1),
226 3 : LogicalKeyboardKey.arrowLeft => _adjacent(index, ltr ? -1 : 1),
227 : _ => null,
228 : };
229 : if (target == null) return KeyEventResult.ignored;
230 6 : _nodeFor(widget.items[target].value).requestFocus();
231 : return KeyEventResult.handled;
232 : }
233 :
234 1 : @override
235 : Widget build(BuildContext context) {
236 1 : final theme = context.fossTheme;
237 3 : final v = _resolve(theme, widget.style);
238 :
239 1 : return DecoratedBox(
240 1 : decoration: BoxDecoration(
241 1 : color: v.backgroundColor,
242 1 : border: v.showTopBorder
243 3 : ? Border(top: BorderSide(color: v.borderColor))
244 : : null,
245 : ),
246 1 : child: SafeArea(
247 : top: false,
248 : left: false,
249 : right: false,
250 1 : child: Semantics(
251 : role: SemanticsRole.tabBar,
252 : container: true,
253 1 : child: Row(
254 1 : children: <Widget>[
255 5 : for (var i = 0; i < widget.items.length; i++)
256 2 : Expanded(child: _cell(theme, v, i)),
257 : ],
258 : ),
259 : ),
260 : ),
261 : );
262 : }
263 :
264 1 : Widget _cell(FossThemeData theme, _NavVisuals v, int index) {
265 3 : final item = widget.items[index];
266 1 : return _NavCell(
267 1 : label: item.label,
268 5 : icon: item.selectedIcon != null && item.value == widget.value
269 1 : ? item.selectedIcon
270 1 : : item.icon,
271 1 : badge: item.badge,
272 2 : enabled: item.enabled && _live,
273 4 : selected: item.value == widget.value,
274 : visuals: v,
275 2 : gap: theme.spacing(1),
276 2 : padY: theme.spacing(1.5),
277 2 : badgeOffset: theme.spacing(0.5),
278 2 : focusNode: _nodeFor(item.value),
279 3 : onSelect: () => _select(item.value),
280 2 : onKeyEvent: (event) => _onKey(event, index),
281 : );
282 : }
283 : }
|