use std::{
sync::{
Arc,
atomic::{AtomicU64, Ordering},
},
time::Duration,
};
use parking_lot::Mutex;
use crate::{
animation::{Easing, Transition},
app::{
component::Component,
ctx::{BottomBarInset, Ctx},
window::SafeAreaInsets,
},
components::{Column, Router, Row, Stack, Text},
core::{ElementRef, Signal},
layout::{
Alignment, StackAlignment,
layout_kind::Justify,
text_style::{FontWeight, TextStyle},
},
node::{Element, color::Color, dimension::Dimension, transform::Transform2D},
router::RouterHandle,
ui::{Recipe, Themed, engine_look::EngineLook, names},
};
const FILL: Dimension = Dimension::Pct(100.0);
#[derive(Clone, Default)]
pub struct TabItem {
pub title: String,
pub icon: Option<Element>,
pub selected_icon: Option<Element>,
pub symbol: Option<String>,
pub selected_symbol: Option<String>,
pub badge: Option<String>,
pub search: bool,
}
impl TabItem {
pub fn new(title: impl Into<String>) -> Self {
Self {
title: title.into(),
..Self::default()
}
}
pub fn icon(mut self, icon: impl Into<Element>) -> Self {
self.icon = Some(icon.into());
self
}
pub fn selected_icon(mut self, icon: impl Into<Element>) -> Self {
self.selected_icon = Some(icon.into());
self
}
pub fn symbol(mut self, name: impl Into<String>) -> Self {
self.symbol = Some(name.into());
self
}
pub fn selected_symbol(mut self, name: impl Into<String>) -> Self {
self.selected_symbol = Some(name.into());
self
}
pub fn badge(mut self, badge: impl Into<String>) -> Self {
self.badge = Some(badge.into());
self
}
pub fn search(mut self) -> Self {
self.search = true;
if self.symbol.is_none() && self.icon.is_none() {
self.symbol = Some("magnifyingglass".to_owned());
self.selected_symbol = Some("magnifyingglass".to_owned());
}
self
}
}
struct Tab {
key: String,
item: TabItem,
router: RouterHandle,
bar_move: Signal<BarMove>,
scrolled: Signal<bool>,
front: Signal<bool>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct BarMove {
pub(crate) hidden: f32,
pub(crate) pace: Duration,
pub(crate) curve: Easing,
}
impl BarMove {
pub(crate) const SHOWN: Self = Self {
hidden: 0.0,
pace: Duration::ZERO,
curve: Easing::Linear,
};
}
#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for BarMove {
fn write_info(&self, _buffer: &mut Vec<crate::app::component::ComponentInfo>) {}
}
#[derive(Clone)]
pub(crate) struct TabBarLink(pub(crate) Signal<BarMove>, pub(crate) Signal<bool>);
struct TabsInner {
tabs: Mutex<Vec<Tab>>,
active: Signal<String>,
changed: Signal<u64>,
bar_hidden: Signal<bool>,
to_top: Signal<u64>,
}
#[derive(Clone)]
pub struct Tabs {
inner: Arc<TabsInner>,
}
impl Default for Tabs {
fn default() -> Self {
Self::new()
}
}
impl PartialEq for Tabs {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.inner, &other.inner)
}
}
#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for Tabs {
fn write_info(&self, _buffer: &mut Vec<crate::app::component::ComponentInfo>) {}
}
#[derive(Clone)]
pub struct TabEntry {
pub key: String,
pub item: TabItem,
pub router: RouterHandle,
pub active: bool,
bar_move: Signal<BarMove>,
scrolled: Signal<bool>,
front: Signal<bool>,
}
impl Tabs {
pub fn new() -> Self {
Self {
inner: Arc::new(TabsInner {
tabs: Mutex::new(Vec::new()),
active: Signal::new(String::new()),
changed: Signal::new(0),
bar_hidden: Signal::new(false),
to_top: Signal::new(0),
}),
}
}
fn bump(&self) {
self.inner.changed.update(|version| *version += 1);
}
pub fn add(&self, key: impl Into<String>, item: TabItem, router: RouterHandle) -> &Self {
let at = self.inner.tabs.lock().len();
self.insert(at, key, item, router)
}
pub fn insert(&self, index: usize, key: impl Into<String>, item: TabItem, router: RouterHandle) -> &Self {
let key = key.into();
let first = {
let mut tabs = self.inner.tabs.lock();
let mut tab = Tab {
key: key.clone(),
item,
router,
bar_move: Signal::new(BarMove::SHOWN),
scrolled: Signal::new(false),
front: Signal::new(false),
};
match tabs.iter().position(|tab| tab.key == key) {
Some(at) => {
tab.bar_move = tabs[at].bar_move.clone();
tab.scrolled = tabs[at].scrolled.clone();
tab.front = tabs[at].front.clone();
tabs[at] = tab;
}
None => {
let index = index.min(tabs.len());
tabs.insert(index, tab);
}
}
tabs.len() == 1
};
if first {
self.inner.active.set(key);
}
self.bump();
self
}
pub fn remove(&self, key: &str) {
let next = {
let mut tabs = self.inner.tabs.lock();
let Some(at) = tabs.iter().position(|tab| tab.key == key) else {
return;
};
tabs.remove(at);
(self.inner.active.get_untracked() == key).then(|| {
tabs
.get(at)
.or(tabs.last())
.map(|tab| tab.key.clone())
.unwrap_or_default()
})
};
if let Some(next) = next {
self.inner.active.set(next);
}
self.bump();
}
pub fn move_to(&self, key: &str, index: usize) {
{
let mut tabs = self.inner.tabs.lock();
let Some(from) = tabs.iter().position(|tab| tab.key == key) else {
return;
};
let to = index.min(tabs.len() - 1);
if from == to {
return;
}
let tab = tabs.remove(from);
tabs.insert(to, tab);
}
self.bump();
}
pub fn select(&self, key: &str) {
let known = self.inner.tabs.lock().iter().any(|tab| tab.key == key);
if known && self.inner.active.get_untracked() != key {
self.inner.active.set(key.to_owned());
}
}
pub fn press(&self, key: &str) {
if self.inner.active.get_untracked() != key {
self.select(key);
return;
}
let Some(router) = self.router(key) else {
return;
};
let above = router.stack().len().saturating_sub(1);
if above > 0 {
router.back_by(above);
} else {
self.inner.to_top.update(|version| *version += 1);
}
}
pub fn active(&self) -> String {
self.inner.active.get()
}
pub fn active_signal(&self) -> Signal<String> {
self.inner.active.clone()
}
pub fn router(&self, key: &str) -> Option<RouterHandle> {
self
.inner
.tabs
.lock()
.iter()
.find(|tab| tab.key == key)
.map(|tab| tab.router.clone())
}
pub fn active_router(&self) -> Option<RouterHandle> {
self.router(&self.inner.active.get_untracked())
}
pub fn list(&self) -> Vec<TabEntry> {
let _ = self.inner.changed.get();
let active = self.inner.active.get();
self
.inner
.tabs
.lock()
.iter()
.map(|tab| TabEntry {
key: tab.key.clone(),
item: tab.item.clone(),
router: tab.router.clone(),
active: tab.key == active,
bar_move: tab.bar_move.clone(),
scrolled: tab.scrolled.clone(),
front: tab.front.clone(),
})
.collect()
}
pub fn len(&self) -> usize {
self.inner.tabs.lock().len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn set_item(&self, key: &str, item: TabItem) {
if let Some(tab) = self.inner.tabs.lock().iter_mut().find(|tab| tab.key == key) {
tab.item = item;
}
self.bump();
}
pub fn set_badge(&self, key: &str, badge: Option<String>) {
if let Some(tab) = self.inner.tabs.lock().iter_mut().find(|tab| tab.key == key) {
tab.item.badge = badge;
}
self.bump();
}
pub fn set_bar_hidden(&self, hidden: bool) {
if self.inner.bar_hidden.get_untracked() != hidden {
self.inner.bar_hidden.set(hidden);
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TabBarPlace {
#[default]
Bottom,
Top,
}
#[derive(Clone, Debug, PartialEq)]
pub struct TabBar {
pub place: TabBarPlace,
pub background: Color,
pub border: Color,
pub tint: Color,
pub color: Color,
pub contrast_color: Color,
pub blur: f32,
pub height: f32,
pub low_height: f32,
pub low_window: f32,
pub low_title_size: f32,
pub low_symbol_size: f32,
pub hide_duration: Duration,
pub title_size: f32,
pub title_weight: FontWeight,
pub symbol_size: f32,
pub spacing: f32,
pub badge_background: Color,
pub badge_color: Color,
pub badge_size: f32,
pub item_max_width: f32,
pub hides_with_keyboard: bool,
pub max_items: usize,
pub more_title: String,
pub more_symbol: String,
pub minimizes_on_scroll: bool,
pub floating: bool,
pub floating_margin: f32,
pub floating_bottom: f32,
pub floating_height: f32,
pub floating_selection: Color,
}
impl TabBar {
fn more_title(&self) -> String {
if self.more_title.is_empty() {
crate::ui::current_locale().common.more.to_string()
} else {
self.more_title.clone()
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TabBarPart {
Root,
Separator,
Item,
ContrastItem,
SelectedItem,
Badge,
Selection,
}
names!(TabBarPart {
Root => "root",
Separator => "separator",
Item => "item",
ContrastItem => "contrast_item",
SelectedItem => "selected_item",
Badge => "badge",
Selection => "selection",
});
mod legacy {
use crate::node::color::Color;
pub(super) const BACKGROUND: Color = Color::new(249, 249, 249, 224);
pub(super) const BORDER: Color = Color::new(60, 60, 67, 74);
pub(super) const TINT: Color = Color::new(0x00, 0x7A, 0xFF, 255);
pub(super) const COLOR: Color = Color::new(0x99, 0x99, 0x99, 255);
pub(super) const CONTRAST: Color = Color::new(0x51, 0x51, 0x54, 255);
pub(super) const BADGE: Color = Color::new(0xFF, 0x3B, 0x30, 255);
pub(super) const BADGE_TEXT: Color = Color::new(255, 255, 255, 255);
pub(super) const SELECTION: Color = Color::new(120, 120, 128, 41);
}
impl Themed for TabBar {
const NAME: &'static str = "phone_tab_bar";
type Renderer = ();
fn recipe() -> Recipe {
use crate::app::theme::PaletteColor::{
Background, Border, Destructive, DestructiveForeground, Foreground, Muted, MutedForeground,
};
Recipe::new()
.base(TabBarPart::Root, |s| s.background(Background))
.base(TabBarPart::Separator, |s| s.background(Border))
.base(TabBarPart::Item, |s| s.foreground(MutedForeground))
.base(TabBarPart::ContrastItem, |s| s.foreground(Foreground))
.base(TabBarPart::SelectedItem, |s| s.foreground(Foreground))
.base(TabBarPart::Badge, |s| {
s.background(Destructive).foreground(DestructiveForeground)
})
.base(TabBarPart::Selection, |s| s.background(Muted))
}
}
impl Default for TabBar {
fn default() -> Self {
let look = EngineLook::of::<Self>(&[]);
Self {
place: TabBarPlace::Bottom,
background: look.background(TabBarPart::Root, legacy::BACKGROUND),
border: look.background(TabBarPart::Separator, legacy::BORDER),
tint: look.foreground(TabBarPart::SelectedItem, legacy::TINT),
color: look.foreground(TabBarPart::Item, legacy::COLOR),
contrast_color: look.foreground(TabBarPart::ContrastItem, legacy::CONTRAST),
blur: 40.0,
height: 49.0,
low_height: 32.0,
low_window: 480.0,
low_title_size: 12.0,
low_symbol_size: 13.0,
hide_duration: Duration::from_millis(250),
title_size: 10.0,
title_weight: FontWeight::Medium,
symbol_size: 18.0,
spacing: 2.0,
badge_background: look.background(TabBarPart::Badge, legacy::BADGE),
badge_color: look.foreground(TabBarPart::Badge, legacy::BADGE_TEXT),
badge_size: 13.0,
item_max_width: f32::INFINITY,
hides_with_keyboard: true,
max_items: 5,
more_title: String::new(),
more_symbol: "ellipsis".to_owned(),
minimizes_on_scroll: false,
floating: false,
floating_margin: 21.0,
floating_bottom: 21.0,
floating_height: 62.0,
floating_selection: look.background(TabBarPart::Selection, legacy::SELECTION),
}
}
}
impl TabBar {
pub fn new() -> Self {
Self::default()
}
pub(crate) fn legacy_recipe() -> Recipe {
Recipe::new()
.base(TabBarPart::Root, |s| s.background(legacy::BACKGROUND))
.base(TabBarPart::Separator, |s| s.background(legacy::BORDER))
.base(TabBarPart::Item, |s| s.foreground(legacy::COLOR))
.base(TabBarPart::ContrastItem, |s| s.foreground(legacy::CONTRAST))
.base(TabBarPart::SelectedItem, |s| s.foreground(legacy::TINT))
.base(TabBarPart::Badge, |s| {
s.background(legacy::BADGE).foreground(legacy::BADGE_TEXT)
})
.base(TabBarPart::Selection, |s| s.background(legacy::SELECTION))
}
fn legacy_light() -> Self {
Self {
background: legacy::BACKGROUND,
border: legacy::BORDER,
tint: legacy::TINT,
color: legacy::COLOR,
contrast_color: legacy::CONTRAST,
badge_background: legacy::BADGE,
badge_color: legacy::BADGE_TEXT,
floating_selection: legacy::SELECTION,
..Self::default()
}
}
#[deprecated(
since = "0.63.0",
note = "the theme's appearance gives the dark colors: `TabBar::new()` built in a dark theme is dark"
)]
pub fn dark() -> Self {
Self {
background: Color::new(22, 22, 22, 204),
border: Color::new(84, 84, 88, 153),
tint: Color::from_hex("#0A84FF"),
color: Color::from_hex("#8E8E93"),
contrast_color: Color::from_hex("#C7C7CC"),
..Self::legacy_light()
}
}
#[deprecated(
since = "0.63.0",
note = "the theme's appearance gives the colors: `TabBar::new()` is light or dark as the theme is"
)]
#[allow(deprecated)]
pub fn for_appearance(appearance: crate::app::window::Appearance) -> Self {
match appearance {
crate::app::window::Appearance::Light => Self::legacy_light(),
crate::app::window::Appearance::Dark => Self::dark(),
}
}
pub fn floating(mut self) -> Self {
self.floating = true;
self
}
pub fn minimizes_on_scroll(mut self, minimizes: bool) -> Self {
self.minimizes_on_scroll = minimizes;
self
}
pub fn place(mut self, place: TabBarPlace) -> Self {
self.place = place;
self
}
pub fn background(mut self, color: Color) -> Self {
self.background = color;
self
}
pub fn border(mut self, color: Color) -> Self {
self.border = color;
self
}
pub fn blur(mut self, radius: f32) -> Self {
self.blur = radius;
self
}
pub fn tint(mut self, color: Color) -> Self {
self.tint = color;
self
}
pub fn color(mut self, color: Color) -> Self {
self.color = color;
self
}
}
pub struct TabBarState {
pub tabs: Tabs,
pub entries: Vec<TabEntry>,
pub safe_area: SafeAreaInsets,
pub low: bool,
}
pub type TabBarBuilder = Arc<dyn Fn(&TabBarState) -> Element + Send + Sync>;
#[derive(Clone)]
enum Bar {
Standard(TabBar),
Custom(TabBarBuilder, TabBarPlace),
}
#[derive(Clone)]
pub struct TabOutletProps {
tabs: Tabs,
bar: Option<Bar>,
}
impl PartialEq for TabOutletProps {
fn eq(&self, other: &Self) -> bool {
let same_bar = match (&self.bar, &other.bar) {
(None, None) => true,
(Some(Bar::Standard(a)), Some(Bar::Standard(b))) => a == b,
(Some(Bar::Custom(a, at)), Some(Bar::Custom(b, bt))) => Arc::ptr_eq(a, b) && at == bt,
_ => false,
};
self.tabs == other.tabs && same_bar
}
}
#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for TabOutletProps {
fn write_info(&self, _buffer: &mut Vec<crate::app::component::ComponentInfo>) {}
}
impl TabOutletProps {
pub fn new(tabs: Tabs) -> Self {
Self { tabs, bar: None }
}
pub fn bar(mut self, bar: TabBar) -> Self {
self.bar = Some(Bar::Standard(bar));
self
}
pub fn bar_with(
mut self,
place: TabBarPlace,
builder: impl Fn(&TabBarState) -> Element + Send + Sync + 'static,
) -> Self {
self.bar = Some(Bar::Custom(Arc::new(builder), place));
self
}
}
pub struct TabOutlet {
to_top: AtomicU64,
bar: ElementRef,
bar_height: Signal<f32>,
more_open: Signal<bool>,
}
impl TabOutlet {
pub fn mount(ctx: &mut Ctx, props: TabOutletProps) -> Element {
ctx.mount::<Self>(props)
}
}
impl Component for TabOutlet {
type Props = TabOutletProps;
fn create(ctx: &mut Ctx) -> Self {
let tabs = ctx.props::<TabOutletProps>().tabs.clone();
let to_top = AtomicU64::new(tabs.inner.to_top.get_untracked());
ctx.provide(tabs);
Self {
to_top,
bar: ElementRef::default(),
bar_height: Signal::new(0.0),
more_open: Signal::new(false),
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let props = ctx.props::<TabOutletProps>().clone();
let tabs = props.tabs.clone();
let entries = tabs.list();
let hidden = tabs.inner.bar_hidden.get();
let to_top = tabs.inner.to_top.get();
if self.to_top.swap(to_top, Ordering::AcqRel) != to_top {
ctx.scroll_to_top();
}
let window = ctx.window();
let safe_area = window.safe_area;
let keyboard_up = safe_area.keyboard > 0.0;
let low = match &props.bar {
Some(Bar::Standard(bar)) => window.logical_height() < bar.low_window,
_ => false,
};
let (place, away, hide_duration) = match &props.bar {
None => (TabBarPlace::Bottom, true, Duration::ZERO),
Some(Bar::Standard(bar)) => (
bar.place,
hidden || (bar.hides_with_keyboard && keyboard_up),
bar.hide_duration,
),
Some(Bar::Custom(_, place)) => (*place, hidden || keyboard_up, TabBar::default().hide_duration),
};
let over = props.bar.is_some() && place == TabBarPlace::Bottom;
let bar_height = self.bar_height.get();
ctx.provide_if_changed(BottomBarInset::Over(if over && !away {
(bar_height - safe_area.bottom).max(0.0)
} else {
0.0
}));
let mut screens = Stack::new().size(FILL, FILL);
let mut moved = BarMove::SHOWN;
let mut scrolled = false;
let around = ctx.use_context::<crate::app::ctx::InFront>();
for entry in &entries {
if entry.front.get_untracked() != entry.active {
entry.front.set(entry.active);
}
let host = ctx.mount_keyed_offstage::<TabHost>(
&entry.key,
TabHostProps {
router: entry.router.clone(),
bar_move: entry.bar_move.clone(),
scrolled: entry.scrolled.clone(),
front: crate::app::ctx::InFront::new(entry.front.clone(), around.clone()),
},
entry.active,
);
if entry.active {
moved = entry.bar_move.get();
scrolled = entry.scrolled.get();
}
let holder = Stack::new()
.key(format!("tab-{}", entry.key))
.size(FILL, FILL)
.child(host);
screens = screens.child(if entry.active {
holder
} else {
holder.pointer_events_none()
});
}
let minimized =
matches!(&props.bar, Some(Bar::Standard(bar)) if bar.minimizes_on_scroll) && scrolled && !self.more_open.get();
let drawn_in = minimized && matches!(&props.bar, Some(Bar::Standard(bar)) if bar.floating);
let minimized = minimized && !drawn_in;
let bar: Option<Element> = match &props.bar {
None => None,
_ if away && !over => None,
Some(Bar::Custom(builder, _)) => Some(builder(&TabBarState {
tabs: tabs.clone(),
entries: entries.clone(),
safe_area,
low,
})),
Some(Bar::Standard(bar)) => {
let mut bar = bar.clone();
if window.system.reduce_transparency || window.system.increase_contrast {
let solid = |color: Color| Color::new(color.r(), color.g(), color.b(), 255);
bar.background = solid(bar.background);
bar.blur = 0.0;
if window.system.increase_contrast {
bar.border = solid(bar.border);
bar.color = bar.contrast_color;
}
}
Some(standard_bar(
&bar,
&tabs,
&entries,
safe_area,
low,
&self.more_open,
drawn_in,
window.logical_width(),
))
}
};
let more_open = self.more_open.get();
let more: Option<Element> = match &props.bar {
Some(Bar::Standard(bar)) if more_open && entries.len() > bar.max_items.max(2) => {
Some(more_list(bar, &tabs, &entries, safe_area, bar_height, &self.more_open))
}
_ => None,
};
let whole = Stack::new().size(FILL, FILL);
match (bar, place) {
(None, _) => whole.child(screens),
(Some(bar), TabBarPlace::Top) => whole.child(
Column::new()
.size(FILL, FILL)
.child(bar)
.child(Column::new().width(FILL).flex(1.0).child(screens)),
),
(Some(bar), TabBarPlace::Bottom) => {
let (share, pace, curve) = if away || minimized {
(1.0, hide_duration, Easing::EASE)
} else if moved.pace.is_zero() && moved.hidden == 0.0 {
(0.0, hide_duration, Easing::EASE)
} else {
(moved.hidden, moved.pace, moved.curve)
};
let pace = if window.system.reduce_motion {
Duration::ZERO
} else {
pace
};
let bar = Row::new()
.ref_element(self.bar.clone())
.width(FILL)
.hit_test(crate::node::HitTestBehavior::ContentOnly)
.child(bar)
.transform(Transform2D::translate(0.0, share * bar_height))
.transition(Transition::transform().duration(pace).easing(curve));
let mut whole = whole.stack_align(StackAlignment::BottomStart).child(screens);
if let Some(more) = more {
whole = whole.child(more);
}
whole.child(if share >= 1.0 { bar.pointer_events_none() } else { bar })
}
}
}
fn after_layout(&self) {
if self.bar.is_attached() {
let height = self.bar.rect().3;
if (self.bar_height.get_untracked() - height).abs() > 0.25 {
self.bar_height.set(height);
}
}
}
}
#[allow(unused_variables)]
#[allow(deprecated)]
fn symbol(name: &str, size: f32, color: Color) -> Option<Element> {
#[cfg(all(target_os = "ios", feature = "raster"))]
if let Some(symbol) = crate::app::ios_symbol::symbol(name, size, color) {
return Some(
crate::components::Image::new(symbol.image)
.width(symbol.width)
.height(symbol.height)
.into(),
);
}
None
}
fn place_content(bar: &TabBar, item: &TabItem, active: bool, low: bool) -> Column {
let color = if active { bar.tint } else { bar.color };
let symbol_size = if low { bar.low_symbol_size } else { bar.symbol_size };
let picture = match (active, &item.selected_icon, &item.selected_symbol) {
(true, Some(icon), _) => Some(icon.clone()),
(true, None, Some(name)) => symbol(name, symbol_size, color),
(true, None, None) => item
.symbol
.as_ref()
.and_then(|name| symbol(&format!("{name}.fill"), symbol_size, color)),
_ => None,
}
.or_else(|| item.icon.clone())
.or_else(|| item.symbol.as_ref().and_then(|name| symbol(name, symbol_size, color)));
let mut content = Column::new()
.align_items(Alignment::Center)
.spacing(bar.spacing)
.overflow_visible();
let badge = item.badge.as_ref().map(|badge| {
let side = if badge.is_empty() {
bar.badge_size * 0.7
} else {
bar.badge_size + 5.0
};
let mark = Row::new()
.min_width(side)
.height(side)
.align_items(Alignment::Center)
.justify(Justify::Center)
.rounded(side / 2.0)
.background(bar.badge_background);
if badge.is_empty() {
mark
} else {
mark.padding_horizontal(5.0).child(
Text::styled(
badge,
TextStyle {
font_size: bar.badge_size,
color: bar.badge_color,
..TextStyle::default()
},
)
.nowrap(),
)
}
});
let title = Text::styled(
&item.title,
TextStyle {
font_size: if low { bar.low_title_size } else { bar.title_size },
weight: bar.title_weight,
color,
..TextStyle::default()
},
)
.nowrap();
match (picture, badge) {
(Some(picture), badge) => {
let mut over = Stack::new()
.stack_align(StackAlignment::TopEnd)
.overflow_visible()
.child(picture);
if let Some(badge) = badge {
over = over.child(badge.transform(Transform2D::translate(bar.badge_size * 0.7, -bar.badge_size * 0.3)));
}
if low {
let mut row = Row::new()
.align_items(Alignment::Center)
.spacing(6.0)
.overflow_visible()
.child(over);
if !item.title.is_empty() {
row = row.child(title);
}
content.child(row)
} else {
content = content.child(over);
if item.title.is_empty() {
content
} else {
content.child(title)
}
}
}
(None, badge) => {
let mut row = Row::new().align_items(Alignment::Center).spacing(4.0).child(title);
if let Some(badge) = badge {
row = row.child(badge);
}
content.child(row)
}
}
}
fn placed<'a>(bar: &TabBar, entries: &'a [TabEntry]) -> (&'a [TabEntry], &'a [TabEntry]) {
let places = bar.max_items.max(2);
if entries.len() > places {
entries.split_at(places - 1)
} else {
(entries, &[])
}
}
fn standard_bar(
bar: &TabBar,
tabs: &Tabs,
entries: &[TabEntry],
safe_area: SafeAreaInsets,
low: bool,
more_open: &Signal<bool>,
drawn_in: bool,
window_width: f32,
) -> Element {
let floating = bar.floating && bar.place == TabBarPlace::Bottom;
let (shown, rest) = placed(bar, entries);
let height = if floating {
bar.floating_height
} else if low {
bar.low_height
} else {
bar.height
};
let opened = more_open.get_untracked();
let apart_there = floating && shown.iter().any(|entry| entry.item.search);
let count = shown.iter().filter(|entry| !(floating && entry.item.search)).count() + usize::from(!rest.is_empty());
let full = (window_width
- safe_area.left
- safe_area.right
- 2.0 * bar.floating_margin
- if apart_there { height + 10.0 } else { 0.0 })
.max(0.0);
let each = ((full - 8.0) / count.max(1) as f32).max(0.0);
let alone = (height + 12.0).min(each.max(height));
let resize = Transition::width().duration(bar.hide_duration).easing(Easing::EASE);
let fade = Transition::opacity().duration(bar.hide_duration).easing(Easing::EASE);
let place = |id: String, content: Column, chosen: bool, in_row: bool, press: Box<dyn Fn() + Send + Sync>| {
let mut place = Row::new().id(id);
place = if floating && in_row {
let (width, seen) = match (drawn_in, chosen) {
(false, _) => (each, 1.0),
(true, true) => (alone, 1.0),
(true, false) => (0.0, 0.0),
};
place
.width(width)
.opacity(seen)
.transition(resize.clone())
.transition(fade.clone())
} else {
place.flex(1.0).max_width(bar.item_max_width)
};
let mut place = place
.height(FILL)
.align_items(Alignment::Center)
.justify(Justify::Center)
.overflow_visible()
.child(content)
.on_click(move |_| press());
if floating {
place = place.rounded((height - 8.0) / 2.0).background(if chosen {
bar.floating_selection
} else {
Color::new(0, 0, 0, 0)
});
}
place
};
let mut places = Row::new()
.height(if floating { height - 8.0 } else { height })
.justify(Justify::Center);
let mut apart: Option<Element> = None;
for entry in shown {
let chosen = entry.active && !opened;
let (tabs, key, open) = (tabs.clone(), entry.key.clone(), more_open.clone());
let (scrolled, opens) = (entry.scrolled.clone(), drawn_in && entry.active && !entry.item.search);
let made = place(
format!("tab-{}", entry.key),
place_content(bar, &entry.item, chosen, low),
chosen,
!entry.item.search,
Box::new(move || {
if opens {
scrolled.set(false);
return;
}
open.set(false);
tabs.press(&key);
}),
);
if floating && entry.item.search {
apart = Some(
Row::new()
.width(height)
.height(height)
.padding(4.0)
.rounded(height / 2.0)
.background(bar.background)
.backdrop_blur(bar.blur)
.border_inside(0.5, bar.border)
.child(made)
.into(),
);
} else {
places = places.child(made);
}
}
if !rest.is_empty() {
let chosen = opened || rest.iter().any(|entry| entry.active);
let item = TabItem::new(bar.more_title()).symbol(bar.more_symbol.clone());
let open = more_open.clone();
places = places.child(place(
"tab-more-places".to_owned(),
place_content(bar, &item, chosen, low),
chosen,
true,
Box::new(move || open.set(!open.get_untracked())),
));
}
if floating {
let capsule = places
.width(if drawn_in { alone + 8.0 } else { full })
.transition(resize.clone())
.height(height)
.padding(4.0)
.rounded(height / 2.0)
.background(bar.background)
.backdrop_blur(bar.blur)
.border_inside(0.5, bar.border);
let mut row = Row::new()
.width(FILL)
.hit_test(crate::node::HitTestBehavior::ContentOnly)
.padding_left(safe_area.left + bar.floating_margin)
.padding_right(safe_area.right + bar.floating_margin)
.padding_bottom(bar.floating_bottom)
.child(capsule);
if let Some(apart) = apart {
row = row
.child(Row::new().flex(1.0).min_width(10.0).pointer_events_none())
.child(apart);
}
return row.into();
}
let places = places
.width(FILL)
.padding_left(safe_area.left)
.padding_right(safe_area.right);
let line = Row::new().width(FILL).height(0.5).background(bar.border);
let column = Column::new()
.width(FILL)
.background(bar.background)
.backdrop_blur(bar.blur);
match bar.place {
TabBarPlace::Bottom => column.child(line).child(places).padding_bottom(safe_area.bottom),
TabBarPlace::Top => column.padding_top(safe_area.top).child(places).child(line),
}
.into()
}
fn more_list(
bar: &TabBar,
tabs: &Tabs,
entries: &[TabEntry],
safe_area: SafeAreaInsets,
bar_height: f32,
more_open: &Signal<bool>,
) -> Element {
let (_, rest) = placed(bar, entries);
let solid = Color::new(bar.background.r(), bar.background.g(), bar.background.b(), 255);
let mut rows = Column::new().width(FILL);
for entry in rest {
let (tabs, key, open) = (tabs.clone(), entry.key.clone(), more_open.clone());
let color = if entry.active { bar.tint } else { bar.color };
let mut row = Row::new()
.id(format!("tab-{}", entry.key))
.width(FILL)
.height(44.0)
.align_items(Alignment::Center)
.spacing(12.0)
.padding_horizontal(16.0);
if let Some(picture) = entry.item.icon.clone().or_else(|| {
entry
.item
.symbol
.as_ref()
.and_then(|name| symbol(name, bar.symbol_size, color))
}) {
row = row.child(picture);
}
row = row.child(
Text::styled(
&entry.item.title,
TextStyle {
font_size: 17.0,
color: bar.tint,
..TextStyle::default()
},
)
.nowrap(),
);
rows = rows
.child(row.on_click(move |_| {
open.set(false);
tabs.select(&key);
}))
.child(Row::new().width(FILL).height(0.5).background(bar.border));
}
Column::new()
.id("tab-more-list")
.size(FILL, FILL)
.background(solid)
.padding_top(safe_area.top + 16.0)
.padding_left(safe_area.left)
.padding_right(safe_area.right)
.padding_bottom(bar_height)
.child(
Row::new().padding_horizontal(16.0).padding_bottom(8.0).child(
Text::styled(
&bar.more_title(),
TextStyle {
font_size: 34.0,
weight: FontWeight::Bold,
color: bar.tint,
..TextStyle::default()
},
)
.nowrap(),
),
)
.child(crate::components::ScrollVertical::new(rows).width(FILL).flex(1.0))
.on_click(|_| {})
.into()
}
#[derive(Clone)]
struct TabHostProps {
router: RouterHandle,
bar_move: Signal<BarMove>,
scrolled: Signal<bool>,
front: crate::app::ctx::InFront,
}
impl PartialEq for TabHostProps {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.router.inner, &other.router.inner)
}
}
#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for TabHostProps {
fn write_info(&self, _buffer: &mut Vec<crate::app::component::ComponentInfo>) {}
}
struct TabHost;
impl Component for TabHost {
type Props = TabHostProps;
fn create(ctx: &mut Ctx) -> Self {
let props = ctx.props::<TabHostProps>();
let link = TabBarLink(props.bar_move.clone(), props.scrolled.clone());
let front = props.front.clone();
ctx.provide(link);
ctx.provide(front);
Self
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let router = ctx.props::<TabHostProps>().router.clone();
Router::mount(ctx, router)
}
}