use std::hash::Hash;
use super::{
item::TabItem,
options::{Config, TabActivation, TabBarOutput, TabVariant, TabWidth},
show,
};
use crate::{
components::{sanitize, theme::TabsStyle},
Id, Ui,
};
type Trailing<'a> = Box<dyn FnOnce(&mut Ui<'_>) + 'a>;
pub struct TabBar<'a, T> {
pub(super) selected: &'a mut T,
pub(super) tabs: Vec<TabItem<T>>,
pub(super) cfg: Config,
pub(super) trailing: Option<Trailing<'a>>,
}
impl<'a, T: PartialEq + Hash> TabBar<'a, T> {
pub fn new<I: Into<TabItem<T>>>(
id_source: impl Hash,
selected: &'a mut T,
tabs: impl IntoIterator<Item = I>,
) -> Self {
Self {
selected,
tabs: tabs.into_iter().map(Into::into).collect(),
cfg: Config::new(Id::new(id_source)),
trailing: None,
}
}
pub fn variant(mut self, variant: TabVariant) -> Self {
self.cfg.variant = variant;
self
}
pub fn closable(mut self, closable: bool) -> Self {
self.cfg.closable = closable;
self
}
#[track_caller]
pub fn width(mut self, width: TabWidth) -> Self {
match width {
TabWidth::Fixed(w) => {
if let Some(w) = sanitize::positive("TabBar::width", w) {
self.cfg.width = TabWidth::Fixed(w);
}
}
other => self.cfg.width = other,
}
self
}
#[track_caller]
pub fn min_width(mut self, width: f32) -> Self {
self.cfg.min_width =
sanitize::non_negative("TabBar::min_width", width).or(self.cfg.min_width);
self
}
#[track_caller]
pub fn max_width(mut self, width: f32) -> Self {
self.cfg.max_width =
sanitize::non_negative("TabBar::max_width", width).or(self.cfg.max_width);
self
}
pub fn activation(mut self, activation: TabActivation) -> Self {
self.cfg.activation = activation;
self
}
pub fn group(mut self, group: impl Hash) -> Self {
self.cfg.group = Some(Id::new(group));
self
}
pub fn reorderable(mut self, reorderable: bool) -> Self {
self.cfg.reorderable = reorderable;
self
}
pub fn window_drag(mut self, drag: bool) -> Self {
self.cfg.window_drag = drag;
self
}
pub fn keyboard_close(mut self, enabled: bool) -> Self {
self.cfg.keyboard_close = enabled;
self
}
pub fn trailing(mut self, build: impl FnOnce(&mut Ui<'_>) + 'a) -> Self {
self.trailing = Some(Box::new(build));
self
}
pub fn overflow_menu(mut self, menu: bool) -> Self {
self.cfg.overflow_menu = menu;
self
}
pub fn style(mut self, style: TabsStyle) -> Self {
self.cfg.style = style;
self
}
pub fn show(self, ui: &mut Ui<'_>) -> TabBarOutput {
show::run(self, ui)
}
}
impl Ui<'_> {
pub fn tab_bar<T: PartialEq + Hash, L: Into<String>>(
&mut self,
selected: &mut T,
tabs: impl IntoIterator<Item = (T, L)>,
) -> Vec<crate::Response> {
let tabs: Vec<TabItem<T>> = tabs.into_iter().map(Into::into).collect();
let first = tabs.first().map(TabItem::key);
TabBar::new(first, selected, tabs).show(self).responses
}
}