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/theme/theme.dart';
5 :
6 : part 'foss_tabs_style.dart';
7 : part 'foss_tabs_view.dart';
8 : part 'foss_tabs_visuals.dart';
9 :
10 : /// The two tab looks.
11 : enum FossTabsVariant {
12 : /// A filled bar with an elevated pill sliding behind the active tab.
13 : segmented,
14 :
15 : /// A bare strip with a colored bar sliding along the active tab's edge.
16 : underline,
17 : }
18 :
19 : /// The axis the tab strip runs along.
20 : enum FossTabsOrientation {
21 : /// Tabs in a row, the panel below.
22 : horizontal,
23 :
24 : /// Tabs in a column, the panel beside.
25 : vertical,
26 : }
27 :
28 : /// One tab: its [value], [label], optional leading [icon] and [content] panel,
29 : /// and whether it is [enabled].
30 : ///
31 : /// This is data passed to [FossTabs.tabs], not a widget. The [content] is
32 : /// optional, so a strip can drive a panel laid out elsewhere.
33 : ///
34 : /// ```dart
35 : /// const FossTab(value: 'home', label: 'Home', content: HomeBody());
36 : /// ```
37 : @immutable
38 : class FossTab<T> {
39 : /// Creates a tab carrying [value] and [label].
40 1 : const FossTab({
41 : required this.value,
42 : required this.label,
43 : this.icon,
44 : this.content,
45 : this.enabled = true,
46 : });
47 :
48 : /// The value this tab selects. Unique within a [FossTabs].
49 : final T value;
50 :
51 : /// The text shown on the trigger.
52 : final String label;
53 :
54 : /// Optional leading glyph, sized to 18. Any widget; no icon dependency.
55 : final Widget? icon;
56 :
57 : /// The panel shown when this tab is active. Null leaves the panel to the
58 : /// caller.
59 : final Widget? content;
60 :
61 : /// Whether the tab accepts focus and selection. A disabled tab dims and is
62 : /// skipped by the keyboard.
63 : final bool enabled;
64 : }
65 :
66 : /// {@category Layout}
67 : /// {@template foss.tabs.preview}
68 : /// <img src="https://fossui.org/components/tabs/overview/light.png"
69 : /// alt="FossTabs, light theme" width="480"
70 : /// style="max-width:100%;height:auto" />
71 : /// <img src="https://fossui.org/components/tabs/overview/dark.png"
72 : /// alt="FossTabs, dark theme" width="480"
73 : /// style="max-width:100%;height:auto" />
74 : ///
75 : /// See the [tabs documentation ↗](https://fossui.org/docs/components/tabs) or
76 : /// try it live in the
77 : /// [playground ↗](https://play.fossui.org/components/#/?path=components/tabs/fosstabs/playground).
78 : /// {@endtemplate}
79 : ///
80 : /// A row or column of tabs that toggle between sibling panels, with an animated
81 : /// indicator marking the active tab.
82 : ///
83 : /// [FossTabs] owns the selection. Pass [value] with [onChanged] to control it,
84 : /// or leave [value] null and seed [initialValue] to let the widget hold its own
85 : /// selection. Each [FossTab] in [tabs] carries its label, optional icon and
86 : /// panel, and an enabled flag; only the active tab's panel renders.
87 : ///
88 : /// A horizontal panel sizes to its content, capped at the height left under a
89 : /// bounded parent, so a scrollable panel such as a `ListView` works inside a
90 : /// fixed-height box. A vertical panel fills the height beside the strip.
91 : ///
92 : /// [variant] picks the look and [orientation] the axis. Colors, type, and the
93 : /// indicator slide come from `context.fossTheme`; pass a [FossTabsStyle] to
94 : /// [style] for a one-off.
95 : ///
96 : /// {@macro foss.customize}
97 : ///
98 : /// ```dart
99 : /// FossTabs<String>(
100 : /// value: selected,
101 : /// onChanged: (v) => setState(() => selected = v),
102 : /// tabs: const [
103 : /// FossTab(value: 'overview', label: 'Overview', content: OverviewBody()),
104 : /// FossTab(value: 'activity', label: 'Activity', content: ActivityBody()),
105 : /// ],
106 : /// );
107 : /// ```
108 : class FossTabs<T> extends StatefulWidget {
109 : /// {@macro foss.tabs.preview}
110 : ///
111 : /// Creates a set of tabs over [tabs].
112 1 : const FossTabs({
113 : required this.tabs,
114 : this.value,
115 : this.onChanged,
116 : this.initialValue,
117 : this.variant = FossTabsVariant.segmented,
118 : this.orientation = FossTabsOrientation.horizontal,
119 : this.style,
120 : super.key,
121 : });
122 :
123 : /// The ordered tabs.
124 : final List<FossTab<T>> tabs;
125 :
126 : /// The selected value when controlled. Null hands selection to the widget,
127 : /// seeded by [initialValue].
128 : final T? value;
129 :
130 : /// Called with a tab's value when it is selected.
131 : final ValueChanged<T>? onChanged;
132 :
133 : /// The initial selection when uncontrolled ([value] is null). Falls back to
134 : /// the first enabled tab.
135 : final T? initialValue;
136 :
137 : /// The look. Defaults to [FossTabsVariant.segmented].
138 : final FossTabsVariant variant;
139 :
140 : /// The axis. Defaults to [FossTabsOrientation.horizontal].
141 : final FossTabsOrientation orientation;
142 :
143 : /// Per-instance overrides layered on the theme-resolved style.
144 : final FossTabsStyle? style;
145 :
146 1 : @override
147 1 : State<FossTabs<T>> createState() => _FossTabsState<T>();
148 : }
149 :
150 : class _FossTabsState<T> extends State<FossTabs<T>> {
151 : final GlobalKey _flexKey = GlobalKey();
152 : final Map<T, GlobalKey> _tabKeys = <T, GlobalKey>{};
153 : final Map<T, FocusNode> _nodes = <T, FocusNode>{};
154 :
155 : Rect? _activeRect;
156 : T? _internal;
157 : T? _hovered;
158 :
159 4 : bool get _horizontal => widget.orientation == FossTabsOrientation.horizontal;
160 :
161 4 : T? get _value => widget.value ?? _internal;
162 :
163 1 : @override
164 : void initState() {
165 1 : super.initState();
166 3 : _internal = _validInitial() ?? _firstEnabledValue();
167 : }
168 :
169 1 : @override
170 : void didUpdateWidget(FossTabs<T> oldWidget) {
171 1 : super.didUpdateWidget(oldWidget);
172 : // Drop keys and nodes for tabs that no longer exist.
173 6 : final values = widget.tabs.map((t) => t.value).toSet();
174 4 : _tabKeys.removeWhere((value, _) => !values.contains(value));
175 6 : final stale = _nodes.keys.where((v) => !values.contains(v)).toList();
176 2 : for (final value in stale) {
177 3 : _nodes.remove(value)?.dispose();
178 : }
179 : // Drop a hover pointing at a tab that no longer exists after a reorder.
180 1 : if (_hovered != null && !values.contains(_hovered)) _hovered = null;
181 : }
182 :
183 1 : @override
184 : void dispose() {
185 3 : for (final node in _nodes.values) {
186 1 : node.dispose();
187 : }
188 1 : super.dispose();
189 : }
190 :
191 1 : T? _firstEnabledValue() {
192 3 : for (final tab in widget.tabs) {
193 2 : if (tab.enabled) return tab.value;
194 : }
195 : return null;
196 : }
197 :
198 : // Honors [initialValue] only when it names an enabled tab; an absent or
199 : // disabled value would seed a selection with no panel to show.
200 1 : T? _validInitial() {
201 2 : final initial = widget.initialValue;
202 : if (initial == null) return null;
203 3 : for (final tab in widget.tabs) {
204 3 : if (tab.value == initial) return tab.enabled ? initial : null;
205 : }
206 : return null;
207 : }
208 :
209 3 : GlobalKey _keyFor(T value) => _tabKeys.putIfAbsent(value, GlobalKey.new);
210 :
211 3 : FocusNode _nodeFor(T value) => _nodes.putIfAbsent(value, FocusNode.new);
212 :
213 1 : void _select(T value) {
214 3 : widget.onChanged?.call(value);
215 4 : if (widget.value == null && value != _internal) {
216 3 : setState(() => _internal = value);
217 : }
218 : }
219 :
220 : // Reads the active tab's box in the strip's coordinate space after layout, so
221 : // the indicator can track it. Only commits when it actually moves, which
222 : // stops the post-frame callback from looping.
223 1 : void _scheduleMeasure() {
224 3 : WidgetsBinding.instance.addPostFrameCallback((_) {
225 1 : if (!mounted) return;
226 1 : final value = _value;
227 3 : final flex = _flexKey.currentContext?.findRenderObject();
228 : final tab = value == null
229 : ? null
230 4 : : _tabKeys[value]?.currentContext?.findRenderObject();
231 1 : if (flex is! RenderBox ||
232 1 : tab is! RenderBox ||
233 1 : !flex.hasSize ||
234 1 : !tab.hasSize) {
235 4 : if (_activeRect != null) setState(() => _activeRect = null);
236 : return;
237 : }
238 2 : final topLeft = flex.globalToLocal(tab.localToGlobal(Offset.zero));
239 2 : final rect = topLeft & tab.size;
240 5 : if (rect != _activeRect) setState(() => _activeRect = rect);
241 : });
242 : }
243 :
244 : // Walks from [from] by [step], skipping disabled tabs, without wrapping.
245 1 : int? _adjacent(int from, int step) {
246 7 : for (var i = from + step; i >= 0 && i < widget.tabs.length; i += step) {
247 4 : if (widget.tabs[i].enabled) return i;
248 : }
249 : return null;
250 : }
251 :
252 1 : int? _edge(bool last) {
253 : final range = last
254 6 : ? List<int>.generate(widget.tabs.length, (i) => i).reversed
255 5 : : List<int>.generate(widget.tabs.length, (i) => i);
256 2 : for (final i in range) {
257 4 : if (widget.tabs[i].enabled) return i;
258 : }
259 : return null;
260 : }
261 :
262 1 : KeyEventResult _onKey(KeyEvent event, int index) {
263 2 : if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
264 : return KeyEventResult.ignored;
265 : }
266 1 : final key = event.logicalKey;
267 2 : if (key == LogicalKeyboardKey.space || key == LogicalKeyboardKey.enter) {
268 5 : _select(widget.tabs[index].value);
269 : return KeyEventResult.handled;
270 : }
271 :
272 3 : final ltr = Directionality.of(context) == TextDirection.ltr;
273 : final target = switch (key) {
274 2 : LogicalKeyboardKey.home => _edge(false),
275 2 : LogicalKeyboardKey.end => _edge(true),
276 3 : LogicalKeyboardKey.arrowRight when _horizontal => _adjacent(
277 : index,
278 1 : ltr ? 1 : -1,
279 : ),
280 3 : LogicalKeyboardKey.arrowLeft when _horizontal => _adjacent(
281 : index,
282 1 : ltr ? -1 : 1,
283 : ),
284 3 : LogicalKeyboardKey.arrowDown when !_horizontal => _adjacent(index, 1),
285 4 : LogicalKeyboardKey.arrowUp when !_horizontal => _adjacent(index, -1),
286 : _ => null,
287 : };
288 : if (target == null) return KeyEventResult.ignored;
289 6 : _nodeFor(widget.tabs[target].value).requestFocus();
290 : return KeyEventResult.handled;
291 : }
292 :
293 1 : @override
294 : Widget build(BuildContext context) {
295 1 : final theme = context.fossTheme;
296 2 : final dark = theme.colors.isDark;
297 5 : final v = _resolve(theme, widget.variant, dark, widget.style);
298 : final reduceMotion =
299 2 : MediaQuery.maybeOf(context)?.disableAnimations ?? false;
300 :
301 : FossTab<T>? active;
302 3 : for (final tab in widget.tabs) {
303 3 : if (tab.value == _value) {
304 : active = tab;
305 : break;
306 : }
307 : }
308 :
309 1 : final stripVisual = _buildStrip(theme, v, reduceMotion);
310 1 : final strip = Semantics(
311 : role: SemanticsRole.tabBar,
312 : container: true,
313 : // A vertical strip sits in a Row, which hands a non-flex child unbounded
314 : // width; the strip hugs its widest tab, so cap it to the intrinsic width.
315 2 : child: _horizontal ? stripVisual : IntrinsicWidth(child: stripVisual),
316 : );
317 :
318 1 : _scheduleMeasure();
319 :
320 1 : final children = <Widget>[strip];
321 1 : if (active?.content case final content?) {
322 1 : final panel = Semantics(role: SemanticsRole.tabPanel, child: content);
323 : // A loose fit keeps a short panel content-sized while capping a
324 : // scrollable one to the height left under a bounded parent. Under an
325 : // unbounded parent the cap lifts and the panel sizes to its content.
326 1 : children.add(
327 3 : _horizontal ? Flexible(child: panel) : Expanded(child: panel),
328 : );
329 : }
330 :
331 1 : return _horizontal
332 1 : ? Column(
333 : mainAxisSize: MainAxisSize.min,
334 : crossAxisAlignment: CrossAxisAlignment.start,
335 2 : spacing: theme.spacing(2),
336 : children: children,
337 : )
338 1 : : Row(
339 : crossAxisAlignment: CrossAxisAlignment.start,
340 2 : spacing: theme.spacing(2),
341 : children: children,
342 : );
343 : }
344 :
345 1 : Widget _buildStrip(FossThemeData theme, _TabsVisuals v, bool reduceMotion) {
346 3 : final segmented = widget.variant == FossTabsVariant.segmented;
347 3 : final ltr = Directionality.of(context) == TextDirection.ltr;
348 :
349 1 : final tabs = <Widget>[
350 5 : for (var i = 0; i < widget.tabs.length; i++)
351 1 : KeyedSubtree(
352 5 : key: _keyFor(widget.tabs[i].value),
353 1 : child: _tabButton(theme, v, i),
354 : ),
355 : ];
356 :
357 1 : final flex = _horizontal
358 1 : ? Row(
359 1 : key: _flexKey,
360 : mainAxisSize: MainAxisSize.min,
361 2 : spacing: theme.spacing(0.5),
362 : children: tabs,
363 : )
364 1 : : Column(
365 1 : key: _flexKey,
366 : mainAxisSize: MainAxisSize.min,
367 : crossAxisAlignment: CrossAxisAlignment.stretch,
368 2 : spacing: theme.spacing(0.5),
369 : children: tabs,
370 : );
371 :
372 1 : final activeRect = _activeRect;
373 : final indicator = activeRect == null
374 : ? null
375 1 : : _TabIndicator(
376 : rect: activeRect,
377 2 : variant: widget.variant,
378 1 : horizontal: _horizontal,
379 : ltr: ltr,
380 : visuals: v,
381 2 : duration: reduceMotion ? Duration.zero : theme.motion.overlay,
382 : );
383 :
384 1 : final stack = Stack(
385 1 : children: <Widget>[
386 1 : if (segmented && indicator != null) indicator,
387 1 : flex,
388 1 : if (!segmented && indicator != null) indicator,
389 : ],
390 : );
391 :
392 : if (segmented) {
393 1 : return DecoratedBox(
394 1 : decoration: ShapeDecoration(
395 1 : color: v.barColor,
396 1 : shape: RoundedSuperellipseBorder(
397 2 : borderRadius: BorderRadius.circular(v.barRadius),
398 : ),
399 : ),
400 1 : child: Padding(
401 3 : padding: EdgeInsets.all(theme.spacing(0.5)),
402 : child: stack,
403 : ),
404 : );
405 : }
406 1 : return Padding(
407 1 : padding: _horizontal
408 3 : ? EdgeInsets.symmetric(vertical: theme.spacing(1))
409 3 : : EdgeInsets.symmetric(horizontal: theme.spacing(1)),
410 : child: stack,
411 : );
412 : }
413 :
414 1 : Widget _tabButton(FossThemeData theme, _TabsVisuals v, int index) {
415 3 : final tab = widget.tabs[index];
416 1 : return _TabButton(
417 1 : label: tab.label,
418 1 : icon: tab.icon,
419 1 : enabled: tab.enabled,
420 3 : selected: tab.value == _value,
421 3 : hovered: _hovered == tab.value,
422 2 : variant: widget.variant,
423 1 : horizontal: _horizontal,
424 : visuals: v,
425 2 : iconGap: theme.spacing(1.5),
426 2 : focusNode: _nodeFor(tab.value),
427 3 : onSelect: () => _select(tab.value),
428 5 : onEnter: () => setState(() => _hovered = tab.value),
429 1 : onExit: () {
430 6 : if (_hovered == tab.value) setState(() => _hovered = null);
431 : },
432 2 : onKeyEvent: (event) => _onKey(event, index),
433 : );
434 : }
435 : }
|