ailloli_ui_widgets/controls/
tabs.rs

1//! Immediate-mode drawing and hit geometry for a compact tab bar.
2
3use ailloli_ui_core::{Color, FontId, IconId, Rect, TextStyle};
4use ailloli_ui_runtime::{DrawCmd, DrawImage, DrawRRect, DrawRect, DrawText};
5use ailloli_ui_text::{TextLayoutParams, TextSystem, WrapMode};
6
7/// Default tab-bar height in logical pixels.
8///
9/// The drawing functions still use the height of the supplied [`Rect`]; this
10/// constant is a caller convention rather than an enforced constraint.
11///
12/// # Examples
13///
14/// ```
15/// use ailloli_ui_widgets::controls::tabs::TABS_BAR_H;
16/// assert_eq!(TABS_BAR_H, 36.0);
17/// ```
18pub const TABS_BAR_H: f32 = 36.0;
19
20/// Read-only data source for one immediate-mode tab.
21///
22/// IDs are cloned into [`TabsLayout::tab_rects`] and should be unique if the
23/// caller uses them for hit routing. The renderer does not validate uniqueness.
24///
25/// # Examples
26///
27/// ```
28/// use ailloli_ui_widgets::controls::tabs::TabsItem;
29/// struct Tab;
30/// impl TabsItem for Tab {
31///     fn id(&self) -> &str { "docs" }
32///     fn title(&self) -> &str { "Docs" }
33///     fn selected(&self) -> bool { true }
34/// }
35/// assert!(Tab.selected());
36/// ```
37pub trait TabsItem {
38    /// Returns the stable identity copied into output hit geometry.
39    ///
40    /// # Examples
41    ///
42    /// ```
43    /// use ailloli_ui_widgets::controls::tabs::TabsItem;
44    /// struct Tab;
45    /// impl TabsItem for Tab {
46    ///     fn id(&self) -> &str { "one" }
47    ///     fn title(&self) -> &str { "One" }
48    ///     fn selected(&self) -> bool { false }
49    /// }
50    /// assert_eq!(Tab.id(), "one");
51    /// ```
52    fn id(&self) -> &str;
53    /// Returns the visible title; empty text is rendered as `"Conversation"`.
54    ///
55    /// # Examples
56    ///
57    /// ```
58    /// use ailloli_ui_widgets::controls::tabs::TabsItem;
59    /// struct Tab;
60    /// impl TabsItem for Tab {
61    ///     fn id(&self) -> &str { "one" }
62    ///     fn title(&self) -> &str { "One" }
63    ///     fn selected(&self) -> bool { false }
64    /// }
65    /// assert_eq!(Tab.title(), "One");
66    /// ```
67    fn title(&self) -> &str;
68    /// Returns whether selected background and border colors are used.
69    ///
70    /// The renderer permits zero, one, or multiple selected items.
71    ///
72    /// # Examples
73    ///
74    /// ```
75    /// use ailloli_ui_widgets::controls::tabs::TabsItem;
76    /// struct Tab;
77    /// impl TabsItem for Tab {
78    ///     fn id(&self) -> &str { "one" }
79    ///     fn title(&self) -> &str { "One" }
80    ///     fn selected(&self) -> bool { true }
81    /// }
82    /// assert!(Tab.selected());
83    /// ```
84    fn selected(&self) -> bool;
85
86    /// Returns an optional 14-logical-pixel icon before the title.
87    ///
88    /// The default is `None` and reserves no icon space.
89    ///
90    /// # Examples
91    ///
92    /// ```
93    /// use ailloli_ui_widgets::controls::tabs::TabsItem;
94    /// struct Tab;
95    /// impl TabsItem for Tab {
96    ///     fn id(&self) -> &str { "one" }
97    ///     fn title(&self) -> &str { "One" }
98    ///     fn selected(&self) -> bool { false }
99    /// }
100    /// assert!(Tab.leading_icon().is_none());
101    /// ```
102    fn leading_icon(&self) -> Option<&IconId> {
103        None
104    }
105
106    /// Returns an optional icon tint; `None` uses [`TabsStyle::text_muted`].
107    ///
108    /// The value has no effect when [`Self::leading_icon`] returns `None`.
109    ///
110    /// # Examples
111    ///
112    /// ```
113    /// use ailloli_ui_widgets::controls::tabs::TabsItem;
114    /// struct Tab;
115    /// impl TabsItem for Tab {
116    ///     fn id(&self) -> &str { "one" }
117    ///     fn title(&self) -> &str { "One" }
118    ///     fn selected(&self) -> bool { false }
119    /// }
120    /// assert!(Tab.leading_icon_tint().is_none());
121    /// ```
122    fn leading_icon_tint(&self) -> Option<Color> {
123        None
124    }
125
126    /// Returns the exact scope sentinel used to color the optional strip.
127    ///
128    /// Accepted colored sentinels are `"app_global"`, `"workspace_global"`,
129    /// `"server"`, `"path"`, `"file"`, and `"task"`. Empty or any other value
130    /// uses neutral gray. Disable the strip with [`TabsBarOptions::show_scope_strip`].
131    ///
132    /// # Examples
133    ///
134    /// ```
135    /// use ailloli_ui_widgets::controls::tabs::TabsItem;
136    /// struct Tab;
137    /// impl TabsItem for Tab {
138    ///     fn id(&self) -> &str { "one" }
139    ///     fn title(&self) -> &str { "One" }
140    ///     fn selected(&self) -> bool { false }
141    ///     fn scope_kind(&self) -> &str { "workspace_global" }
142    /// }
143    /// assert_eq!(Tab.scope_kind(), "workspace_global");
144    /// ```
145    fn scope_kind(&self) -> &str {
146        ""
147    }
148
149    /// Returns whether the shared unread/processing dot should be shown.
150    ///
151    /// The default is `false`.
152    ///
153    /// # Examples
154    ///
155    /// ```
156    /// use ailloli_ui_widgets::controls::tabs::TabsItem;
157    /// struct Tab;
158    /// impl TabsItem for Tab {
159    ///     fn id(&self) -> &str { "one" }
160    ///     fn title(&self) -> &str { "One" }
161    ///     fn selected(&self) -> bool { false }
162    /// }
163    /// assert!(!Tab.unread());
164    /// ```
165    fn unread(&self) -> bool {
166        false
167    }
168
169    /// Returns whether the same status dot used for unread state is shown.
170    ///
171    /// `unread() || processing()` produces one dot, never two. The default is
172    /// `false`; this helper does not animate processing state.
173    ///
174    /// # Examples
175    ///
176    /// ```
177    /// use ailloli_ui_widgets::controls::tabs::TabsItem;
178    /// struct Tab;
179    /// impl TabsItem for Tab {
180    ///     fn id(&self) -> &str { "one" }
181    ///     fn title(&self) -> &str { "One" }
182    ///     fn selected(&self) -> bool { false }
183    ///     fn processing(&self) -> bool { true }
184    /// }
185    /// assert!(Tab.processing());
186    /// ```
187    fn processing(&self) -> bool {
188        false
189    }
190}
191
192#[derive(Debug, Clone, Copy)]
193/// Visibility switches for optional tab-bar affordances.
194///
195/// All three options default to `true`.
196///
197/// # Examples
198///
199/// ```
200/// use ailloli_ui_widgets::controls::TabsBarOptions;
201/// let options = TabsBarOptions::default();
202/// assert!(options.show_trailing_actions);
203/// assert!(options.show_tab_close_affordance);
204/// assert!(options.show_scope_strip);
205/// ```
206pub struct TabsBarOptions {
207    /// Paint new-tab/history buttons and reserve their 62-pixel region.
208    pub show_trailing_actions: bool,
209    /// Paint an `x` label in each tab; hit geometry is returned regardless.
210    pub show_tab_close_affordance: bool,
211    /// Paint the semantic scope strip and reserve its title inset.
212    pub show_scope_strip: bool,
213}
214
215impl Default for TabsBarOptions {
216    fn default() -> Self {
217        Self {
218            show_trailing_actions: true,
219            show_tab_close_affordance: true,
220            show_scope_strip: true,
221        }
222    }
223}
224
225#[derive(Debug, Clone, Copy)]
226/// Colors used by [`draw_tabs_bar`] and [`draw_tabs_bar_with_options`].
227///
228/// Geometry and typography are fixed by the drawing helper.
229///
230/// # Examples
231///
232/// ```
233/// use ailloli_ui_widgets::controls::tabs::TabsStyle;
234/// let style = TabsStyle::default();
235/// assert_ne!(style.tab_bg, style.tab_bg_selected);
236/// ```
237pub struct TabsStyle {
238    /// Whole-bar background.
239    pub bar_bg: Color,
240    /// Unselected tab background.
241    pub tab_bg: Color,
242    /// Selected tab background.
243    pub tab_bg_selected: Color,
244    /// Unselected one-pixel tab border color.
245    pub tab_border: Color,
246    /// Selected one-pixel tab border color.
247    pub tab_border_selected: Color,
248    /// Tab title and trailing action icon color.
249    pub text_fg: Color,
250    /// Default leading-icon tint and close-affordance color.
251    pub text_muted: Color,
252    /// Shared unread-or-processing dot color.
253    pub unread_dot: Color,
254}
255
256impl Default for TabsStyle {
257    fn default() -> Self {
258        Self {
259            bar_bg: Color::rgba(11, 16, 32, 1.0),
260            tab_bg: Color::rgba(17, 24, 40, 1.0),
261            tab_bg_selected: Color::rgba(31, 38, 55, 1.0),
262            tab_border: Color::rgba(31, 38, 55, 1.0),
263            tab_border_selected: Color::rgba(37, 99, 235, 1.0),
264            text_fg: Color::rgba(243, 246, 251, 1.0),
265            text_muted: Color::rgba(156, 163, 175, 1.0),
266            unread_dot: Color::rgba(245, 158, 11, 1.0),
267        }
268    }
269}
270
271#[derive(Debug, Clone)]
272/// Hit geometry returned alongside tab-bar draw commands.
273///
274/// Each tab tuple contains `(owned_id, whole_tab_rect, close_rect)` in visible
275/// input order. Tabs that do not fit are absent.
276///
277/// # Examples
278///
279/// ```
280/// use ailloli_ui_core::Rect;
281/// use ailloli_ui_widgets::controls::tabs::{TabsControls, TabsLayout};
282/// let layout = TabsLayout {
283///     tab_rects: vec![("one".into(), Rect::new(0.0, 0.0, 120.0, 28.0), Rect::new(98.0, 0.0, 22.0, 28.0))],
284///     controls: TabsControls {
285///         new_tab_rect: Rect::new(0.0, 0.0, 0.0, 0.0),
286///         history_rect: Rect::new(0.0, 0.0, 0.0, 0.0),
287///         can_create_path_tab: false,
288///     },
289/// };
290/// assert_eq!(layout.tab_rects[0].0, "one");
291/// ```
292pub struct TabsLayout {
293    /// Visible tab identities and their tab/close hit rectangles.
294    pub tab_rects: Vec<(String, Rect, Rect)>,
295    /// Trailing-control geometry and caller-supplied capability flag.
296    pub controls: TabsControls,
297}
298
299#[derive(Debug, Clone, Copy)]
300/// Hit geometry and capability metadata for trailing tab actions.
301///
302/// When trailing actions are hidden, both rectangles are the zero rectangle.
303/// `can_create_path_tab` is returned unchanged but does not alter painting.
304///
305/// # Examples
306///
307/// ```
308/// use ailloli_ui_core::Rect;
309/// use ailloli_ui_widgets::controls::tabs::TabsControls;
310/// let controls = TabsControls {
311///     new_tab_rect: Rect::new(8.0, 4.0, 28.0, 28.0),
312///     history_rect: Rect::new(42.0, 4.0, 28.0, 28.0),
313///     can_create_path_tab: true,
314/// };
315/// assert!(controls.can_create_path_tab);
316/// ```
317pub struct TabsControls {
318    /// New-tab button rectangle in the same coordinate space as the input bar.
319    pub new_tab_rect: Rect,
320    /// History button rectangle in the same coordinate space as the input bar.
321    pub history_rect: Rect,
322    /// Caller-supplied permission for path-tab creation; not a disabled style.
323    pub can_create_path_tab: bool,
324}
325
326/// Draws a tab bar with every optional affordance enabled.
327///
328/// This is equivalent to [`draw_tabs_bar_with_options`] with
329/// [`TabsBarOptions::default`]. It returns commands plus hit geometry and does
330/// not handle input. Only complete tabs with at least 120 logical pixels fit;
331/// visible tabs target 220 pixels and preserve input order.
332///
333/// # Examples
334///
335/// ```
336/// use ailloli_ui_core::Rect;
337/// use ailloli_ui_text::TextSystem;
338/// use ailloli_ui_widgets::controls::tabs::{draw_tabs_bar, TabsItem, TabsStyle};
339/// struct Tab;
340/// impl TabsItem for Tab {
341///     fn id(&self) -> &str { "one" }
342///     fn title(&self) -> &str { "One" }
343///     fn selected(&self) -> bool { true }
344/// }
345/// let mut text = TextSystem::new();
346/// let (commands, layout) = draw_tabs_bar(
347///     Rect::new(0.0, 0.0, 400.0, 36.0), &[Tab], true, TabsStyle::default(), &mut text,
348/// );
349/// assert!(!commands.is_empty());
350/// assert_eq!(layout.tab_rects.len(), 1);
351/// ```
352pub fn draw_tabs_bar<T: TabsItem>(
353    rect: Rect,
354    tabs: &[T],
355    can_create_path_tab: bool,
356    style: TabsStyle,
357    text: &mut TextSystem,
358) -> (Vec<DrawCmd>, TabsLayout) {
359    draw_tabs_bar_with_options(
360        rect,
361        tabs,
362        can_create_path_tab,
363        style,
364        text,
365        TabsBarOptions::default(),
366    )
367}
368
369/// Draws a tab bar and returns matching hit geometry.
370///
371/// The helper does not clip commands or process events. With trailing actions
372/// visible it reserves two 28-pixel buttons plus a 6-pixel gap. Close hit rects
373/// remain in `tab_rects` even when their `x` labels are hidden. An empty title
374/// paints as `"Conversation"`; unread and processing share one status dot.
375///
376/// # Examples
377///
378/// ```
379/// use ailloli_ui_core::Rect;
380/// use ailloli_ui_text::TextSystem;
381/// use ailloli_ui_widgets::controls::{draw_tabs_bar_with_options, TabsBarOptions};
382/// use ailloli_ui_widgets::controls::tabs::{TabsItem, TabsStyle};
383/// struct Tab;
384/// impl TabsItem for Tab {
385///     fn id(&self) -> &str { "one" }
386///     fn title(&self) -> &str { "" }
387///     fn selected(&self) -> bool { false }
388/// }
389/// let options = TabsBarOptions { show_trailing_actions: false, ..TabsBarOptions::default() };
390/// let mut text = TextSystem::new();
391/// let (_, layout) = draw_tabs_bar_with_options(
392///     Rect::new(0.0, 0.0, 240.0, 36.0), &[Tab], false, TabsStyle::default(), &mut text, options,
393/// );
394/// assert_eq!(layout.tab_rects.len(), 1);
395/// assert_eq!(layout.controls.new_tab_rect.w, 0.0);
396/// ```
397pub fn draw_tabs_bar_with_options<T: TabsItem>(
398    rect: Rect,
399    tabs: &[T],
400    can_create_path_tab: bool,
401    style: TabsStyle,
402    text: &mut TextSystem,
403    options: TabsBarOptions,
404) -> (Vec<DrawCmd>, TabsLayout) {
405    let mut out = Vec::new();
406
407    out.push(DrawCmd::Rect(DrawRect {
408        rect,
409        color: style.bar_bg,
410    }));
411
412    let pad_x = 8.0;
413    let pad_y = 4.0;
414    let btn = 28.0;
415    let gap = 6.0;
416    let mut x = rect.x + pad_x;
417    let y = rect.y + pad_y;
418    let h = rect.h - pad_y * 2.0;
419
420    let right_controls_w = if options.show_trailing_actions {
421        btn * 2.0 + gap
422    } else {
423        0.0
424    };
425    let max_tabs_w = (rect.w - pad_x * 2.0 - right_controls_w).max(0.0);
426    let x_end = x + max_tabs_w;
427
428    let mut tab_rects = Vec::new();
429    /// Appends one unwrapped text command at an already resolved baseline.
430    fn push_text(
431        out: &mut Vec<DrawCmd>,
432        text: &mut TextSystem,
433        pos: [f32; 2],
434        color: Color,
435        font: FontId,
436        px_size: u16,
437        s: &str,
438    ) {
439        out.push(DrawCmd::Text(DrawText {
440            pos,
441            color,
442            decoration: ailloli_ui_core::TextDecoration::None,
443            layout: text.layout_cached(TextLayoutParams {
444                text: s,
445                style: TextStyle::new(font, px_size, color),
446                max_width: None,
447                wrap_mode: WrapMode::NoWrap,
448            }),
449        }));
450    }
451
452    for tab in tabs {
453        if x + 120.0 > x_end {
454            break;
455        }
456        let w = 220.0_f32.min((x_end - x).max(120.0));
457        let tab_r = Rect::new(x, y, w, h);
458        tab_rects.push((
459            tab.id().to_string(),
460            tab_r,
461            Rect::new(tab_r.x + tab_r.w - 22.0, tab_r.y, 22.0, tab_r.h),
462        ));
463
464        let bg = if tab.selected() {
465            style.tab_bg_selected
466        } else {
467            style.tab_bg
468        };
469        let border = if tab.selected() {
470            style.tab_border_selected
471        } else {
472            style.tab_border
473        };
474
475        out.push(DrawCmd::RRect(DrawRRect {
476            rect: tab_r,
477            radius: 6.0,
478            color: bg,
479        }));
480        out.push(DrawCmd::Rect(DrawRect {
481            rect: Rect::new(tab_r.x, tab_r.y, tab_r.w, 1.0),
482            color: border,
483        }));
484        out.push(DrawCmd::Rect(DrawRect {
485            rect: Rect::new(tab_r.x, tab_r.y + tab_r.h - 1.0, tab_r.w, 1.0),
486            color: border,
487        }));
488        out.push(DrawCmd::Rect(DrawRect {
489            rect: Rect::new(tab_r.x, tab_r.y, 1.0, tab_r.h),
490            color: border,
491        }));
492        out.push(DrawCmd::Rect(DrawRect {
493            rect: Rect::new(tab_r.x + tab_r.w - 1.0, tab_r.y, 1.0, tab_r.h),
494            color: border,
495        }));
496
497        if options.show_scope_strip {
498            out.push(DrawCmd::RRect(DrawRRect {
499                rect: Rect::new(tab_r.x + 6.0, tab_r.y + 4.0, 6.0, tab_r.h - 8.0),
500                radius: 3.0,
501                color: scope_color(tab.scope_kind()),
502            }));
503        }
504
505        let title = if tab.title().is_empty() {
506            "Conversation"
507        } else {
508            tab.title()
509        };
510        let title_x = if options.show_scope_strip {
511            tab_r.x + 18.0
512        } else {
513            tab_r.x + 8.0
514        };
515        let title_x = if let Some(icon) = tab.leading_icon() {
516            let icon_size = 14.0;
517            out.push(DrawCmd::Image(DrawImage {
518                rect: Rect::new(
519                    title_x,
520                    tab_r.y + (tab_r.h - icon_size) * 0.5,
521                    icon_size,
522                    icon_size,
523                ),
524                icon: icon.clone(),
525                tint: tab.leading_icon_tint().unwrap_or(style.text_muted),
526                rotation_rad: 0.0,
527            }));
528            title_x + icon_size + 6.0
529        } else {
530            title_x
531        };
532        push_text(
533            &mut out,
534            text,
535            [title_x, tab_r.y + 18.0],
536            style.text_fg,
537            FontId::Ui,
538            12,
539            title,
540        );
541
542        if tab.unread() || tab.processing() {
543            out.push(DrawCmd::RRect(DrawRRect {
544                rect: Rect::new(
545                    tab_r.x + tab_r.w - 34.0,
546                    tab_r.y + (tab_r.h - 8.0) / 2.0,
547                    8.0,
548                    8.0,
549                ),
550                radius: 4.0,
551                color: style.unread_dot,
552            }));
553        }
554
555        if options.show_tab_close_affordance {
556            push_text(
557                &mut out,
558                text,
559                [tab_r.x + tab_r.w - 16.0, tab_r.y + 18.0],
560                style.text_muted,
561                FontId::Ui,
562                14,
563                "x",
564            );
565        }
566
567        x += w + gap;
568    }
569
570    let (history_rect, new_tab_rect) = if options.show_trailing_actions {
571        let history_rect = Rect::new(rect.x + rect.w - pad_x - btn, y, btn, btn);
572        let new_tab_rect = Rect::new(history_rect.x - gap - btn, y, btn, btn);
573        (history_rect, new_tab_rect)
574    } else {
575        let empty = Rect::new(0.0, 0.0, 0.0, 0.0);
576        (empty, empty)
577    };
578
579    let controls = TabsControls {
580        new_tab_rect,
581        history_rect,
582        can_create_path_tab,
583    };
584
585    if options.show_trailing_actions {
586        out.push(DrawCmd::RRect(DrawRRect {
587            rect: new_tab_rect,
588            radius: 8.0,
589            color: style.tab_bg,
590        }));
591        out.push(DrawCmd::Image(DrawImage {
592            rect: Rect::new(new_tab_rect.x + 6.0, new_tab_rect.y + 6.0, 16.0, 16.0),
593            icon: IconId::Plus,
594            tint: style.text_fg,
595            rotation_rad: 0.0,
596        }));
597
598        out.push(DrawCmd::RRect(DrawRRect {
599            rect: history_rect,
600            radius: 8.0,
601            color: style.tab_bg,
602        }));
603        out.push(DrawCmd::Image(DrawImage {
604            rect: Rect::new(history_rect.x + 6.0, history_rect.y + 6.0, 16.0, 16.0),
605            icon: IconId::History,
606            tint: style.text_fg,
607            rotation_rad: 0.0,
608        }));
609    }
610
611    (
612        out,
613        TabsLayout {
614            tab_rects,
615            controls,
616        },
617    )
618}
619
620/// Maps the six documented scope sentinels to colors; all others use gray.
621fn scope_color(kind: &str) -> Color {
622    match kind {
623        "app_global" => Color::rgba(139, 92, 246, 1.0),
624        "workspace_global" => Color::rgba(37, 99, 235, 1.0),
625        "server" => Color::rgba(249, 115, 38, 1.0),
626        "path" => Color::rgba(16, 185, 129, 1.0),
627        "file" => Color::rgba(245, 158, 11, 1.0),
628        "task" => Color::rgba(236, 60, 153, 1.0),
629        _ => Color::rgba(75, 85, 102, 1.0),
630    }
631}