Skip to main content

bhoo/systems/material/
tabs.rs

1use crate::*;
2
3/// Material 3 navigation tab styles (`Primary`: 3dp top-rounded label-width; `Secondary`: 2dp full-width).
4#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
5pub enum TabStyle {
6    #[default]
7    Primary,
8    Secondary,
9}
10
11/// Tab descriptor pairing a label with an optional Material icon for `Frame::tabs_with_icons`.
12#[derive(Clone, Copy, Debug)]
13pub struct TabItem<'a> {
14    pub label: &'a str,
15    pub icon: Option<MaterialIcon>,
16}
17
18/// Configuration for Material 3 tabs rendered via `Frame::tabs_with_options`.
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub struct TabOptions {
21    pub style: TabStyle,
22    pub scrollable: bool,
23    pub enabled: bool,
24}
25impl Default for TabOptions {
26    fn default() -> Self {
27        Self {
28            style: TabStyle::Primary,
29            scrollable: false,
30            enabled: true,
31        }
32    }
33}
34
35impl Frame<'_> {
36    /// A horizontal single-selection group. Tab enters the group; arrows move selection.
37    pub fn tabs(
38        &mut self,
39        id: u64,
40        labels: &[&str],
41        selected: &mut usize,
42        enabled: bool,
43    ) -> Response {
44        let b = self.allocate(49.0);
45        let mut r = self.interact(id, b, enabled && !labels.is_empty());
46        if labels.is_empty() {
47            return r;
48        }
49        *selected = (*selected).min(labels.len() - 1);
50        let old = *selected;
51        if r.clicked
52            && self.input.released
53            && self.ui.capture == Capture::Pointer
54            && let Some(p) = self.input.pointer
55        {
56            *selected = (((p[0] - b.x) / b.width.max(1.0)) * labels.len() as f32)
57                .floor()
58                .max(0.0) as usize;
59            *selected = (*selected).min(labels.len() - 1);
60        }
61        if let Some(key) = self.key_for(r) {
62            match key {
63                Key::Right | Key::Down => *selected = (*selected + 1) % labels.len(),
64                Key::Left | Key::Up => *selected = (*selected + labels.len() - 1) % labels.len(),
65                Key::Home => *selected = 0,
66                Key::End => *selected = labels.len() - 1,
67                _ => {}
68            }
69        }
70        r.changed = old != *selected;
71        let t = self.ui.theme;
72        self.rect(
73            Rect {
74                y: b.y + 48.0,
75                height: 1.0,
76                ..b
77            },
78            0.0,
79            t.outline_variant,
80        );
81        let width = b.width / labels.len() as f32;
82        let target = if labels.len() > 1 {
83            *selected as f32 / (labels.len() - 1) as f32
84        } else {
85            0.0
86        };
87        let a = self.animate_geometry(id, 3, target, target);
88        self.rect(
89            Rect {
90                x: b.x + a * (b.width - width),
91                y: b.y + 46.0,
92                width,
93                height: 2.0,
94            },
95            0.0,
96            t.primary.opacity(if r.enabled { 1.0 } else { 0.38 }),
97        );
98        self.semantic(r, Role::TabList, "Tabs", false, None, None, None);
99        for (index, label) in labels.iter().enumerate() {
100            let bounds = Rect {
101                x: b.x + width * index as f32,
102                width,
103                ..b
104            };
105            if r.enabled {
106                let hovered = self.input.pointer.is_some_and(|p| bounds.contains(p));
107                let focused = r.focused && self.ui.keyboard_focus && index == *selected;
108                let alpha = if focused {
109                    0.12
110                } else if hovered {
111                    0.08
112                } else {
113                    0.0
114                };
115                if alpha > 0.0 {
116                    self.rect(bounds, 0.0, t.primary.opacity(alpha));
117                }
118            }
119            self.ink_part(
120                Response {
121                    bounds,
122                    focused: r.focused && index == *selected,
123                    ..r
124                },
125                index as u32 + 1,
126                0.0,
127                t.primary,
128                false,
129            );
130            self.styled_text(
131                Rect {
132                    height: 48.0,
133                    ..bounds
134                },
135                label,
136                t.text.opacity(if r.enabled { 1.0 } else { 0.38 }),
137                TextStyle::LABEL,
138            );
139            let child = Response {
140                id,
141                bounds,
142                focused: r.focused && index == *selected,
143                ..r
144            };
145            self.semantic(
146                child,
147                Role::Tab,
148                label,
149                index == *selected,
150                None,
151                None,
152                None,
153            );
154            if let Some(node) = self.ui.semantics.last_mut() {
155                node.part = index as u32 + 1;
156            }
157        }
158        self.focus_ring(r);
159        r
160    }
161    /// Material 3 navigation tabs supporting Primary (3dp top-rounded label-width indicator),
162    /// Secondary (2dp full-tab-width indicator), and horizontal scrollable overflow.
163    pub fn tabs_with_options(
164        &mut self,
165        id: u64,
166        labels: &[&str],
167        selected: &mut usize,
168        options: TabOptions,
169    ) -> Response {
170        let b = self.allocate(49.0);
171        if labels.is_empty() {
172            return self.interact(id, b, false);
173        }
174        let mut widths = Vec::with_capacity(labels.len());
175        let mut offsets = Vec::with_capacity(labels.len());
176        let mut cursor_x = 0.0_f32;
177        if options.scrollable {
178            for label in labels {
179                let w = (self.text_width(label, TextStyle::LABEL) + 32.0).clamp(72.0, 264.0);
180                offsets.push(cursor_x);
181                widths.push(w);
182                cursor_x += w;
183            }
184        } else {
185            let w = b.width / labels.len() as f32;
186            for _ in labels {
187                offsets.push(cursor_x);
188                widths.push(w);
189                cursor_x += w;
190            }
191        }
192        let total_width = cursor_x.max(1.0);
193        let max_scroll = if options.scrollable {
194            (total_width - b.width).max(0.0)
195        } else {
196            0.0
197        };
198        let mut scroll_offset = if options.scrollable {
199            self.ui
200                .scrolls
201                .get(&id)
202                .map_or(0.0, |s| s.offset)
203                .clamp(0.0, max_scroll)
204        } else {
205            0.0
206        };
207        let saved_input = self.input;
208        let dragged = if options.scrollable && options.enabled && self.enabled {
209            self.scroll_viewport_horizontal(id, b, &mut scroll_offset, max_scroll)
210        } else {
211            false
212        };
213        let mut r = self.interact(id, b, options.enabled);
214        if dragged {
215            self.input = saved_input;
216        }
217        *selected = (*selected).min(labels.len() - 1);
218        let old = *selected;
219        if r.clicked
220            && self.input.released
221            && self.ui.capture == Capture::Pointer
222            && let Some(p) = self.input.pointer
223        {
224            let local_x = p[0] - b.x + scroll_offset;
225            if let Some(idx) = offsets
226                .iter()
227                .zip(widths.iter())
228                .position(|(&x, &w)| local_x >= x && local_x < x + w)
229            {
230                *selected = idx;
231            } else if local_x >= total_width {
232                *selected = labels.len() - 1;
233            } else {
234                *selected = 0;
235            }
236        }
237        if let Some(key) = self.key_for(r) {
238            match key {
239                Key::Right | Key::Down => *selected = (*selected + 1) % labels.len(),
240                Key::Left | Key::Up => *selected = (*selected + labels.len() - 1) % labels.len(),
241                Key::Home => *selected = 0,
242                Key::End => *selected = labels.len() - 1,
243                _ => {}
244            }
245        }
246        r.changed = old != *selected;
247        if options.scrollable {
248            if r.changed && max_scroll > 0.0 {
249                let tab_x = offsets[*selected];
250                let tab_w = widths[*selected];
251                if tab_x < scroll_offset {
252                    scroll_offset = tab_x;
253                } else if tab_x + tab_w > scroll_offset + b.width {
254                    scroll_offset = (tab_x + tab_w - b.width).min(max_scroll);
255                }
256            }
257            scroll_offset = scroll_offset.clamp(0.0, max_scroll);
258            self.ui.scrolls.entry(id).or_default().offset = scroll_offset;
259        }
260        let t = self.ui.theme;
261        self.rect(
262            Rect {
263                y: b.y + 48.0,
264                height: 1.0,
265                ..b
266            },
267            0.0,
268            t.outline_variant,
269        );
270        let sel_tab_x = offsets[*selected];
271        let sel_tab_w = widths[*selected];
272        let (target_ind_x, target_ind_w) = match options.style {
273            TabStyle::Primary => {
274                let label_w = self.text_width(labels[*selected], TextStyle::LABEL);
275                let ind_w = label_w
276                    .max(24.0)
277                    .min((sel_tab_w - 4.0).max(0.0));
278                (sel_tab_x + (sel_tab_w - ind_w) * 0.5, ind_w)
279            }
280            TabStyle::Secondary => (sel_tab_x, sel_tab_w),
281        };
282        let norm_x = (target_ind_x / total_width).clamp(0.0, 1.0);
283        let norm_w = (target_ind_w / total_width).clamp(0.0, 1.0);
284        let anim_x = self.animate_geometry(id, 3, norm_x, norm_x) * total_width;
285        let anim_w = self.animate_geometry(id, 4, norm_w, norm_w) * total_width;
286        let indicator_color = t.primary.opacity(if r.enabled { 1.0 } else { 0.38 });
287        let bar_clip = b.intersect(self.clip);
288        self.commands.push(DrawCommand::PushClip(bar_clip));
289        match options.style {
290            TabStyle::Primary => {
291                let ind_clip = bar_clip.intersect(Rect {
292                    x: b.x,
293                    y: b.y + 45.0,
294                    width: b.width,
295                    height: 3.0,
296                });
297                self.commands.push(DrawCommand::PushClip(ind_clip));
298                self.rect(
299                    Rect {
300                        x: b.x + anim_x - scroll_offset,
301                        y: b.y + 45.0,
302                        width: anim_w,
303                        height: 6.0,
304                    },
305                    3.0,
306                    indicator_color,
307                );
308                self.commands.push(DrawCommand::PopClip);
309            }
310            TabStyle::Secondary => {
311                self.rect(
312                    Rect {
313                        x: b.x + anim_x - scroll_offset,
314                        y: b.y + 46.0,
315                        width: anim_w,
316                        height: 2.0,
317                    },
318                    0.0,
319                    indicator_color,
320                );
321            }
322        }
323        self.semantic(r, Role::TabList, "Tabs", false, None, None, None);
324        for (index, label) in labels.iter().enumerate() {
325            let bounds = Rect {
326                x: b.x + offsets[index] - scroll_offset,
327                y: b.y,
328                width: widths[index],
329                height: 48.0,
330            };
331            let is_selected = index == *selected;
332            let state_color = match options.style {
333                TabStyle::Primary if is_selected => t.primary,
334                _ => t.text,
335            };
336            if r.enabled {
337                let hovered = self
338                    .input
339                    .pointer
340                    .is_some_and(|p| bar_clip.contains(p) && bounds.contains(p));
341                let focused = r.focused && self.ui.keyboard_focus && is_selected;
342                let alpha = if focused {
343                    0.12
344                } else if hovered {
345                    0.08
346                } else {
347                    0.0
348                };
349                if alpha > 0.0 {
350                    self.rect(bounds, 0.0, state_color.opacity(alpha));
351                }
352            }
353            self.ink_part(
354                Response {
355                    bounds,
356                    focused: r.focused && is_selected,
357                    ..r
358                },
359                index as u32 + 1,
360                0.0,
361                state_color,
362                false,
363            );
364            let label_color = if !r.enabled {
365                t.text.opacity(0.38)
366            } else if is_selected {
367                match options.style {
368                    TabStyle::Primary => t.primary,
369                    TabStyle::Secondary => t.text,
370                }
371            } else {
372                t.on_surface_variant
373            };
374            self.styled_text(bounds, label, label_color, TextStyle::LABEL);
375            let child = Response {
376                id,
377                bounds,
378                focused: r.focused && is_selected,
379                ..r
380            };
381            self.semantic(child, Role::Tab, label, is_selected, None, None, None);
382            if let Some(node) = self.ui.semantics.last_mut() {
383                node.part = index as u32 + 1;
384            }
385        }
386        self.commands.push(DrawCommand::PopClip);
387        self.focus_ring(r);
388        r
389    }
390
391    /// Primary Material 3 tabs with stacked top icon + label, `Role::TabList` container semantics,
392    /// arrow/Home/End keyboard navigation, and animated 3dp bottom indicator.
393    pub fn tabs_with_icons(
394        &mut self,
395        id: u64,
396        items: &[TabItem<'_>],
397        selected: &mut usize,
398        enabled: bool,
399    ) -> bool {
400        self.tabs_with_icons_options(id, items, selected, enabled, TabOptions::default())
401    }
402
403    /// Material 3 icon + label tabs with configurable `TabOptions` (primary/secondary indicator, RTL).
404    pub fn tabs_with_icons_options(
405        &mut self,
406        id: u64,
407        items: &[TabItem<'_>],
408        selected: &mut usize,
409        enabled: bool,
410        options: TabOptions,
411    ) -> bool {
412        if items.is_empty() {
413            return false;
414        }
415        let has_icons = items.iter().any(|it| it.icon.is_some());
416        let bar = self.reserve(if has_icons { 64.0 } else { 48.0 });
417        self.tabs_with_icons_at(id, bar, items, selected, enabled, options)
418    }
419
420    /// Positioned Material 3 icon + label tabs inside caller-supplied `bounds`, with `Role::TabList`
421    /// semantics, roving arrow/Home/End navigation, `TabOptions` styling, and animated indicator.
422    pub fn tabs_with_icons_at(
423        &mut self,
424        id: u64,
425        bar: Rect,
426        items: &[TabItem<'_>],
427        selected: &mut usize,
428        enabled: bool,
429        options: TabOptions,
430    ) -> bool {
431        if items.is_empty() {
432            return false;
433        }
434        let count = items.len();
435        *selected = (*selected).min(count - 1);
436        let t = self.theme();
437        self.paint_rect(bar, 0.0, t.surface_low);
438        self.paint_rect(Rect { y: bar.y + bar.height - 1.0, height: 1.0, ..bar }, 0.0, t.outline_variant);
439        let cell_w = bar.width / count as f32;
440        let mut changed = false;
441        let mut nav_handled = false;
442
443        let enabled = enabled && options.enabled;
444        self.semantic(
445            Response { id: id.wrapping_add(0x5441_424c), bounds: bar, enabled: enabled && self.enabled, ..Response::default() },
446            Role::TabList,
447            "Tabs",
448            false,
449            None,
450            None,
451            None,
452        );
453
454        for (i, item) in items.iter().enumerate() {
455            let cell = Rect { x: bar.x + i as f32 * cell_w, width: cell_w, ..bar };
456            let is_sel = i == *selected;
457            let tab_id = id.wrapping_add(i as u64);
458            let r = self.interact(tab_id, cell, enabled);
459            if !is_sel && !r.focused && !r.clicked && self.ui.next_focus_order.last() == Some(&tab_id) {
460                self.ui.next_focus_order.pop();
461            }
462            let fg = if !r.enabled {
463                t.text.opacity(0.38)
464            } else if is_sel {
465                match options.style {
466                    TabStyle::Primary => t.primary,
467                    TabStyle::Secondary => t.text,
468                }
469            } else {
470                t.on_surface_variant
471            };
472            self.state_layer(r, 0.0, fg);
473            self.focus_ring(r);
474            if let Some(icon) = item.icon {
475                let icon_rect = Rect {
476                    x: cell.x + (cell.width - 24.0) * 0.5,
477                    y: cell.y + 10.0,
478                    width: 24.0,
479                    height: 24.0,
480                };
481                self.paint_material_icon(icon_rect, icon, fg);
482                self.styled_text(
483                    Rect { y: cell.y + 36.0, height: 20.0, ..cell },
484                    item.label,
485                    fg,
486                    TextStyle { size: 12.0, weight: 500, align: 1, ..TextStyle::default() },
487                );
488            } else {
489                self.styled_text(cell, item.label, fg, TextStyle::LABEL);
490            }
491            self.semantic(r, Role::Tab, item.label, is_sel, None, None, None);
492            if r.clicked && *selected != i {
493                *selected = i;
494                changed = true;
495            }
496            if r.focused && r.enabled && !nav_handled {
497                let next = if self.pressed_key(Key::Right) {
498                    Some((i + 1) % count)
499                } else if self.pressed_key(Key::Left) {
500                    Some((i + count - 1) % count)
501                } else if self.pressed_key(Key::Home) {
502                    Some(0)
503                } else if self.pressed_key(Key::End) {
504                    Some(count - 1)
505                } else {
506                    None
507                };
508                if let Some(target_idx) = next {
509                    if *selected != target_idx {
510                        *selected = target_idx;
511                        changed = true;
512                    }
513                    self.request_focus(id.wrapping_add(target_idx as u64));
514                    nav_handled = true;
515                }
516            }
517        }
518        let anim_x = self.animate_geometry(id, 88, *selected as f32, *selected as f32);
519        let ind_w = match options.style {
520            TabStyle::Primary => (cell_w * 0.5).clamp(24.0, cell_w.max(24.0)),
521            TabStyle::Secondary => cell_w,
522        };
523        let ind_h = match options.style {
524            TabStyle::Primary => 3.0,
525            TabStyle::Secondary => 2.0,
526        };
527        let ind_x = bar.x + anim_x * cell_w + (cell_w - ind_w) * 0.5;
528        self.paint_rect(
529            Rect { x: ind_x, y: bar.y + bar.height - ind_h, width: ind_w, height: ind_h },
530            if options.style == TabStyle::Primary { 1.5 } else { 0.0 },
531            t.primary,
532        );
533        changed
534    }
535}
536
537#[cfg(test)]
538#[path = "tabs.spec.rs"]
539mod tests;