use std::{
any::Any,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::Duration,
};
use parking_lot::Mutex;
use super::router_component::render_route_match;
use crate::{
animation::{Easing, Transition},
app::{
component::Component,
ctx::{Ctx, Timeout},
events::{EdgePanEvent, GesturePhase, LongPressEvent, NavigationCommand, NavigationSource, ScreenEdge},
window::SafeAreaInsets,
},
components::{Column, KeyboardKind, ReturnKey, Row, ScrollVertical, Stack, Text, TextInput, TextOverflow},
core::{ElementRef, Signal},
layout::{
Alignment, StackAlignment,
layout_kind::{Justify, ScrollState},
text_style::{FontWeight, TextStyle},
},
node::{Element, color::Color, dimension::Dimension, transform::Transform2D},
router::{
Navigator, StackEntry,
route_match::{OutletDepth, RouteMatch, RouterMatches, StackState},
},
time::Instant,
ui::{Recipe, Themed, engine_look::EngineLook, names},
};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct StackMotion {
pub duration: Duration,
pub parallax: f32,
pub dim: f32,
pub back_share: f32,
pub back_speed: f32,
pub title_fade: Duration,
pub large_title_growth: f32,
pub large_title_pull: f32,
}
impl Default for StackMotion {
fn default() -> Self {
Self {
duration: Duration::from_millis(500),
parallax: 0.3,
dim: 0.1,
back_share: 0.5,
back_speed: 500.0,
title_fade: Duration::from_millis(200),
large_title_growth: 1.1,
large_title_pull: 150.0,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StackPart {
Shade,
MenuShade,
}
names!(StackPart {
Shade => "shade",
MenuShade => "menu_shade",
});
const LEGACY_SHADE: Color = Color::new(0, 0, 0, 255);
impl Themed for StackMotion {
const NAME: &'static str = "phone_stack";
type Renderer = ();
fn recipe() -> Recipe {
use crate::app::theme::PaletteColor::Scrim;
Recipe::new()
.base(StackPart::Shade, |s| s.background(Scrim).opacity(1.0))
.base(StackPart::MenuShade, |s| s.background(Scrim).opacity(1.0))
}
}
impl StackMotion {
pub(crate) fn legacy_recipe() -> Recipe {
Recipe::new()
.base(StackPart::Shade, |s| s.background(LEGACY_SHADE).opacity(1.0))
.base(StackPart::MenuShade, |s| s.background(LEGACY_SHADE).opacity(MENU_DIM))
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct StackShades {
pub(crate) shade: Color,
pub(crate) shade_opacity: f32,
pub(crate) menu: Color,
pub(crate) menu_opacity: f32,
}
impl StackShades {
pub(crate) fn current() -> Self {
let look = EngineLook::of::<StackMotion>(&[]);
Self {
shade: look.background(StackPart::Shade, LEGACY_SHADE),
shade_opacity: look.opacity(StackPart::Shade, 1.0),
menu: look.background(StackPart::MenuShade, LEGACY_SHADE),
menu_opacity: look.opacity(StackPart::MenuShade, MENU_DIM),
}
}
}
const BEGIN: Duration = Duration::from_millis(1);
const SETTLE_AFTER: Duration = Duration::from_millis(50);
const NO_DRAG: f32 = -1.0;
const CHEVRON_WIDTH: f32 = 11.0;
const CHEVRON_HEIGHT: f32 = 20.0;
const CHEVRON_STROKE: f32 = 2.6;
const BACK_SPACING: f32 = 5.0;
#[cfg(all(target_os = "ios", feature = "raster"))]
const CHEVRON_POINT_SIZE: f32 = 17.0;
const BACK_LEADING: f32 = 9.0 + CHEVRON_WIDTH + BACK_SPACING;
const BACK_GAP: f32 = 8.0;
const MENU_MOVE: Duration = Duration::from_millis(250);
const MENU_DIM: f32 = 0.2;
const MENU_OPENING: Duration = Duration::from_millis(400);
const BACK_WIDTH: f32 = 40.0;
const FILL: Dimension = Dimension::Pct(100.0);
#[derive(Clone, Debug, PartialEq)]
pub struct NavigationBar {
pub background: Color,
pub tint: Color,
pub title: Color,
pub border: Color,
pub blur: f32,
pub large_title_max_scale: f32,
pub height: f32,
pub low_height: f32,
pub low_window: f32,
pub title_size: f32,
pub title_weight: FontWeight,
pub text_size: f32,
pub large_title_size: f32,
pub large_title_weight: FontWeight,
pub large_title_height: f32,
pub inset: f32,
pub back: String,
pub back_menu: bool,
pub back_menu_width: f32,
pub prompt_size: f32,
pub prompt_height: f32,
pub toolbar_height: f32,
pub search_height: f32,
pub search_background: Option<Color>,
pub search_placeholder: Option<Color>,
}
impl NavigationBar {
fn adapted(mut self, system: &crate::app::window::SystemSettings, text_scale: f32) -> Self {
let scale = text_scale.clamp(1.0_f32.min(text_scale), self.large_title_max_scale.max(1.0));
self.large_title_size *= scale;
self.large_title_height *= scale;
if system.reduce_transparency || system.increase_contrast {
self.background = Color::new(self.background.r(), self.background.g(), self.background.b(), 255);
self.blur = 0.0;
}
if system.increase_contrast {
self.border = Color::new(self.border.r(), self.border.g(), self.border.b(), 255);
}
self
}
pub fn new() -> Self {
let look = EngineLook::of::<Self>(&[]);
Self {
background: look.background(NavigationBarPart::Root, legacy::BACKGROUND),
tint: look.foreground(NavigationBarPart::Action, legacy::TINT),
title: look.foreground(NavigationBarPart::Title, legacy::TITLE),
border: look.background(NavigationBarPart::Separator, legacy::BORDER),
blur: 40.0,
large_title_max_scale: 1.5,
height: 44.0,
low_height: 32.0,
low_window: 480.0,
title_size: 17.0,
title_weight: FontWeight::SemiBold,
text_size: 17.0,
large_title_size: 34.0,
large_title_weight: FontWeight::Bold,
large_title_height: 52.0,
inset: 16.0,
back: String::new(),
back_menu: true,
back_menu_width: 250.0,
prompt_size: 13.0,
prompt_height: 22.0,
toolbar_height: 44.0,
search_height: 36.0,
search_background: None,
search_placeholder: None,
}
}
pub(crate) fn legacy_recipe() -> Recipe {
Recipe::new()
.base(NavigationBarPart::Root, |s| s.background(legacy::BACKGROUND))
.base(NavigationBarPart::Separator, |s| s.background(legacy::BORDER))
.base(NavigationBarPart::Title, |s| s.foreground(legacy::TITLE))
.base(NavigationBarPart::Action, |s| s.foreground(legacy::TINT))
}
#[deprecated(
since = "0.63.0",
note = "the theme's appearance gives the dark colors: `NavigationBar::new()` built in a dark theme is dark"
)]
pub fn dark() -> Self {
Self {
background: Color::new(28, 28, 30, 204),
tint: Color::from_hex("#0a84ff"),
title: Color::from_hex("#ffffff"),
border: Color::from_hex("#38383a"),
..Self::new()
}
}
#[deprecated(
since = "0.63.0",
note = "the theme's appearance gives the colors: `NavigationBar::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 {
background: legacy::BACKGROUND,
tint: legacy::TINT,
title: legacy::TITLE,
border: legacy::BORDER,
..Self::new()
},
crate::app::window::Appearance::Dark => Self::dark(),
}
}
pub fn background(mut self, color: Color) -> Self {
self.background = color;
self
}
pub fn tint(mut self, color: Color) -> Self {
self.tint = color;
self
}
pub fn title(mut self, color: Color) -> Self {
self.title = 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 back(mut self, word: impl Into<String>) -> Self {
self.back = word.into();
self
}
pub fn back_menu(mut self, enabled: bool) -> Self {
self.back_menu = enabled;
self
}
}
impl Default for NavigationBar {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NavigationBarPart {
Root,
Separator,
Title,
Action,
}
names!(NavigationBarPart {
Root => "root",
Separator => "separator",
Title => "title",
Action => "action",
});
mod legacy {
use crate::node::color::Color;
pub(super) const BACKGROUND: Color = Color::new(249, 249, 249, 224);
pub(super) const TINT: Color = Color::new(0x00, 0x7a, 0xff, 255);
pub(super) const TITLE: Color = Color::new(0, 0, 0, 255);
pub(super) const BORDER: Color = Color::new(0xc6, 0xc6, 0xc8, 255);
}
impl Themed for NavigationBar {
const NAME: &'static str = "phone_navigation_bar";
type Renderer = ();
fn recipe() -> Recipe {
use crate::app::theme::PaletteColor::{Background, Border, Foreground};
Recipe::new()
.base(NavigationBarPart::Root, |s| s.background(Background))
.base(NavigationBarPart::Separator, |s| s.background(Border))
.base(NavigationBarPart::Title, |s| s.foreground(Foreground))
.base(NavigationBarPart::Action, |s| s.foreground(Foreground))
}
}
#[derive(Clone, Default)]
pub struct NavigationItem {
pub title: String,
pub back_title: Option<String>,
pub back_gesture: bool,
pub leading: Option<Element>,
pub trailing: Option<Element>,
pub title_view: Option<Element>,
pub bar_hidden: bool,
pub hides_tab_bar: bool,
pub large_title: bool,
pub prompt: Option<String>,
pub toolbar: Option<Element>,
pub search: Option<NavigationSearch>,
pub large_title_view: Option<Element>,
pub search_view: Option<Element>,
}
#[derive(Clone)]
pub struct NavigationSearch {
pub text: Signal<String>,
pub placeholder: String,
pub cancel: String,
pub hides_bar: bool,
}
impl NavigationSearch {
pub fn new(text: Signal<String>) -> Self {
Self {
text,
placeholder: crate::ui::current_locale().common.search.to_string(),
cancel: crate::ui::current_locale().common.cancel.to_string(),
hides_bar: true,
}
}
pub fn hides_bar(mut self, hides: bool) -> Self {
self.hides_bar = hides;
self
}
pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
self.placeholder = placeholder.into();
self
}
pub fn cancel(mut self, cancel: impl Into<String>) -> Self {
self.cancel = cancel.into();
self
}
fn key(&self) -> (usize, &str, &str, bool) {
(self.text.id(), &self.placeholder, &self.cancel, self.hides_bar)
}
}
impl NavigationItem {
pub fn new(title: impl Into<String>) -> Self {
Self {
title: title.into(),
back_title: None,
back_gesture: true,
leading: None,
trailing: None,
title_view: None,
bar_hidden: false,
hides_tab_bar: false,
large_title: false,
prompt: None,
toolbar: None,
search: None,
large_title_view: None,
search_view: None,
}
}
pub fn back_title(mut self, title: impl Into<String>) -> Self {
self.back_title = Some(title.into());
self
}
pub fn back_gesture(mut self, enabled: bool) -> Self {
self.back_gesture = enabled;
self
}
pub fn leading(mut self, element: impl Into<Element>) -> Self {
self.leading = Some(element.into());
self
}
pub fn trailing(mut self, element: impl Into<Element>) -> Self {
self.trailing = Some(element.into());
self
}
pub fn title_view(mut self, element: impl Into<Element>) -> Self {
self.title_view = Some(element.into());
self
}
pub fn bar_hidden(mut self, hidden: bool) -> Self {
self.bar_hidden = hidden;
self
}
pub fn hides_tab_bar(mut self, hides: bool) -> Self {
self.hides_tab_bar = hides;
self
}
pub fn large_title(mut self, large: bool) -> Self {
self.large_title = large;
self
}
pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
self.prompt = Some(prompt.into());
self
}
pub fn toolbar(mut self, element: impl Into<Element>) -> Self {
self.toolbar = Some(element.into());
self
}
pub fn search(mut self, search: NavigationSearch) -> Self {
self.search = Some(search);
self
}
pub fn large_title_view(mut self, element: impl Into<Element>) -> Self {
self.large_title_view = Some(element.into());
self.large_title = true;
self
}
pub fn search_view(mut self, element: impl Into<Element>) -> Self {
self.search_view = Some(element.into());
self
}
fn has_elements(&self) -> bool {
self.leading.is_some()
|| self.trailing.is_some()
|| self.title_view.is_some()
|| self.toolbar.is_some()
|| self.large_title_view.is_some()
|| self.search_view.is_some()
}
fn same_as(&self, other: &Self) -> bool {
self.title == other.title
&& self.back_title == other.back_title
&& self.back_gesture == other.back_gesture
&& self.leading.is_some() == other.leading.is_some()
&& self.trailing.is_some() == other.trailing.is_some()
&& self.title_view.is_some() == other.title_view.is_some()
&& self.bar_hidden == other.bar_hidden
&& self.hides_tab_bar == other.hides_tab_bar
&& self.large_title == other.large_title
&& self.prompt == other.prompt
&& self.toolbar.is_some() == other.toolbar.is_some()
&& self.large_title_view.is_some() == other.large_title_view.is_some()
&& self.search_view.is_some() == other.search_view.is_some()
&& self.search.as_ref().map(NavigationSearch::key) == other.search.as_ref().map(NavigationSearch::key)
}
}
#[derive(Clone)]
pub(crate) struct NavigationSlot {
item: Arc<Mutex<NavigationItem>>,
changed: Signal<u64>,
scroll: ScrollState,
pull: Signal<f32>,
large: ElementRef,
flying: Signal<bool>,
growth: (f32, f32),
style: Arc<NavigationBar>,
searching: Signal<bool>,
top: Signal<f32>,
under: Arc<AtomicBool>,
toolbars: bool,
bottom: Signal<(bool, bool)>,
front: crate::app::ctx::InFront,
}
impl NavigationSlot {
pub(crate) fn set(&self, item: NavigationItem) {
let same = {
let mut current = self.item.lock();
let same = current.same_as(&item) && !item.has_elements();
*current = item;
same
};
if !same {
self.changed.update(|version| *version += 1);
}
let bottom = {
let item = self.item.lock();
(item.toolbar.is_some() && !item.bar_hidden, item.hides_tab_bar)
};
if self.bottom.get_untracked() != bottom {
self.bottom.set(bottom);
}
}
}
#[derive(Clone)]
pub struct NavigationBarState {
pub top: NavigationBarScreen,
pub under: Option<NavigationBarScreen>,
pub out: f32,
pub duration: Duration,
pub easing: Easing,
pub width: f32,
pub safe_area: SafeAreaInsets,
pub navigator: Navigator,
pub under_titles: Vec<String>,
pub low: bool,
}
#[derive(Clone)]
pub struct NavigationBarScreen {
pub item: NavigationItem,
pub back_label: Option<String>,
pub large_title_in_view: bool,
pub searching: bool,
}
pub type NavigationBarBuilder = Arc<dyn Fn(&NavigationBarState) -> Element + Send + Sync>;
#[derive(Clone)]
enum Bar {
Standard(NavigationBar),
Custom(NavigationBarBuilder),
}
#[derive(Clone, Default)]
pub struct StackOutletProps {
bar: Option<Bar>,
background: Option<Color>,
motion: StackMotion,
}
impl PartialEq for StackOutletProps {
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)), Some(Bar::Custom(b))) => Arc::ptr_eq(a, b),
_ => false,
};
same_bar && self.background == other.background && self.motion == other.motion
}
}
impl std::fmt::Debug for StackOutletProps {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StackOutletProps")
.field("bar", &self.bar.is_some())
.field("background", &self.background)
.finish()
}
}
impl StackOutletProps {
pub fn new() -> Self {
Self::default()
}
pub fn bar(mut self, bar: NavigationBar) -> Self {
self.bar = Some(Bar::Standard(bar));
self
}
pub fn bar_with(mut self, builder: NavigationBarBuilder) -> Self {
self.bar = Some(Bar::Custom(builder));
self
}
pub fn motion(mut self, motion: StackMotion) -> Self {
self.motion = motion;
self
}
pub fn background(mut self, color: Color) -> Self {
self.background = Some(color);
self
}
}
#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for StackOutletProps {
fn write_info(&self, _buffer: &mut Vec<crate::app::component::ComponentInfo>) {}
}
struct Layer {
entry: StackEntry,
matches: Arc<Vec<RouteMatch>>,
bar: LayerBar,
}
#[derive(Clone)]
struct LayerBar {
item: Arc<Mutex<NavigationItem>>,
title: ElementRef,
back_probe: ElementRef,
label_fit: LabelFit,
scroll: ScrollState,
title_gone: Arc<AtomicBool>,
pull: Signal<f32>,
large: ElementRef,
label: ElementRef,
flying: Signal<bool>,
short_probe: ElementRef,
searching: Signal<bool>,
top_now: Arc<Mutex<f32>>,
top: Signal<f32>,
under: Arc<AtomicBool>,
bottom: Signal<(bool, bool)>,
front: Signal<bool>,
}
impl Default for LayerBar {
fn default() -> Self {
Self {
item: Arc::default(),
title: ElementRef::default(),
back_probe: ElementRef::default(),
label_fit: LabelFit::Whole,
scroll: ScrollState::new(),
title_gone: Arc::default(),
pull: Signal::new(0.0),
large: ElementRef::default(),
label: ElementRef::default(),
flying: Signal::new(false),
short_probe: ElementRef::default(),
searching: Signal::new(false),
top_now: Arc::default(),
top: Signal::new(0.0),
under: Arc::default(),
bottom: Signal::new((false, false)),
front: Signal::new(true),
}
}
}
#[derive(Clone, Copy, PartialEq)]
enum Motion {
None,
Entering {
started: bool,
},
Leaving {
started: bool,
},
Returning,
}
struct Shown {
layers: Vec<Layer>,
leaving: Option<Layer>,
motion: Motion,
width: f32,
begin_due: bool,
large_title_height: f32,
velocity: f64,
tab_bar: super::tabs::BarMove,
tab_link: Option<super::tabs::TabBarLink>,
last_scroll: f32,
scrolled_down: bool,
sheet: Option<super::sheet::SheetScroll>,
}
pub struct StackOutlet {
shown: Arc<Mutex<Shown>>,
changed: Signal<u64>,
drag: Signal<f32>,
begin: Timeout,
settle: Timeout,
origin: ElementRef,
menu: BackMenu,
screen: ElementRef,
}
type GoBack = Arc<dyn Fn() + Send + Sync>;
impl Component for StackOutlet {
type Props = StackOutletProps;
fn create(ctx: &mut Ctx) -> Self {
let shown = Arc::new(Mutex::new(Shown {
layers: Vec::new(),
leaving: None,
motion: Motion::None,
width: 0.0,
begin_due: false,
large_title_height: 0.0,
velocity: 0.0,
tab_bar: super::tabs::BarMove::SHOWN,
tab_link: None,
last_scroll: 0.0,
scrolled_down: false,
sheet: None,
}));
let changed = Signal::new(0u64);
let drag = Signal::new(NO_DRAG);
let begin = ctx.create_timeout(BEGIN, {
let (shown, changed, drag) = (shown.clone(), changed.clone(), drag.clone());
move || {
if let Motion::Entering { started } | Motion::Leaving { started } = &mut shown.lock().motion {
*started = true;
}
drag.set(NO_DRAG);
changed.update(|version| *version += 1);
}
});
let duration = ctx.props::<StackOutletProps>().motion.duration;
let settle = ctx.create_timeout(duration + SETTLE_AFTER, {
let (shown, changed) = (shown.clone(), changed.clone());
move || {
{
let mut shown = shown.lock();
shown.motion = Motion::None;
shown.leaving = None;
shown.velocity = 0.0;
}
changed.update(|version| *version += 1);
}
});
Self {
shown,
changed,
drag,
begin,
settle,
origin: ElementRef::default(),
screen: ElementRef::default(),
menu: BackMenu {
open: Signal::new(false),
opened_at: Arc::default(),
},
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let props = ctx.props::<StackOutletProps>().clone();
let motion = props.motion;
let shades = StackShades::current();
let depth = ctx.use_context::<OutletDepth>().unwrap_or(OutletDepth(0)).0 + 1;
let Some(navigator) = ctx.use_context::<Navigator>() else {
return ctx.children().first().cloned().unwrap_or_else(Element::new);
};
let around = ctx.use_context::<crate::app::ctx::InFront>();
let history = ctx.history_runner();
let go_back: GoBack = {
let (history, screen) = (history.clone(), self.screen.clone());
Arc::new(move || history.run_in(&screen, NavigationCommand::Back))
};
let _ = navigator.path().get();
let _ = self.changed.get();
let drag = self.drag.get();
let menu_open = self.menu.open.get();
let mut entries = Vec::new();
for entry in navigator.handle.stack().into_iter().rev() {
let matches = navigator.handle.inner.routes.resolve(&entry.path);
if matches.len() <= depth {
break;
}
entries.push((entry, Arc::new(matches)));
}
entries.reverse();
if entries.is_empty() {
return ctx.children().first().cloned().unwrap_or_else(Element::new);
}
let safe_area = ctx.safe_area();
let window = ctx.window();
let width = window.logical_width();
let system = window.system;
let reduce_motion = system.reduce_motion;
let text_scale = ctx.theme().text_scale();
let style = Arc::new(
match &props.bar {
Some(Bar::Standard(bar)) => bar.clone(),
_ => NavigationBar::new(),
}
.adapted(&system, text_scale),
);
let low = window.logical_height() < style.low_window;
let bar_height = if low { style.low_height } else { style.height };
let mut shown = self.shown.lock();
shown.width = width;
shown.large_title_height = style.large_title_height;
let before: Vec<u64> = shown.layers.iter().map(|layer| layer.entry.id).collect();
let after: Vec<u64> = entries.iter().map(|(entry, _)| entry.id).collect();
if before != after {
let pushed = !before.is_empty() && after.len() > before.len() && after[..before.len()] == before[..];
let popped = before.len() > after.len() && before[..after.len()] == after[..];
let mut old = std::mem::take(&mut shown.layers);
let top = old.pop();
shown.leaving = None;
shown.motion = Motion::None;
if popped {
shown.leaving = top;
shown.motion = Motion::Leaving { started: false };
if drag < 0.0 {
shown.velocity = 0.0;
}
} else {
old.extend(top);
if pushed {
shown.motion = Motion::Entering { started: false };
shown.velocity = 0.0;
}
}
shown.layers = entries
.into_iter()
.map(|(entry, matches)| {
let bar = old
.iter()
.find(|layer| layer.entry.id == entry.id)
.map(|layer| layer.bar.clone())
.unwrap_or_default();
Layer { entry, matches, bar }
})
.collect();
self.begin.cancel();
if shown.motion == Motion::None {
self.settle.cancel();
} else {
shown.begin_due = true;
self.settle.restart();
}
}
let count = shown.layers.len();
let dragged = if drag >= 0.0 && width > 0.0 {
(drag / width).clamp(0.0, 1.0)
} else {
0.0
};
let below = count.checked_sub(2).map(|index| shown.layers[index].entry.id);
let top = shown.layers.last().map(|layer| layer.entry.id);
let (front, back, out, moving) = match shown.motion {
Motion::Entering { started } => (top, below, if started { 0.0 } else { 1.0 }, started),
Motion::Leaving { started } => (
shown.leaving.as_ref().map(|layer| layer.entry.id),
top,
if started { 1.0 } else { dragged },
started,
),
Motion::Returning => (top, below, 0.0, true),
Motion::None if drag >= 0.0 && below.is_some() => (top, below, dragged, false),
Motion::None => (top, None, 0.0, false),
};
let pace = if moving { motion.duration } else { Duration::ZERO };
let curve = Easing::Spring {
velocity: shown.velocity,
};
let slide = Transition::transform().duration(pace).easing(curve);
let fade = Transition::opacity().duration(pace).easing(curve);
let mut screens = Stack::new().size(FILL, FILL).clip();
for layer in shown.layers.iter().chain(shown.leaving.iter()) {
let id = Some(layer.entry.id);
let top_of = |layer: &Layer| {
let (bar_hidden, prompted) = {
let item = layer.bar.item.lock();
(item.bar_hidden, item.prompt.is_some())
};
match &props.bar {
Some(Bar::Standard(_)) if !bar_hidden => {
let items = if layer.bar.searching.get() {
0.0
} else {
bar_height + if prompted { style.prompt_height } else { 0.0 }
};
safe_area.top + items + 0.5
}
_ => 0.0,
}
};
let before = top_of(layer);
if layer.bar.top.get_untracked() != before {
layer.bar.top.set(before);
}
let in_front = id == top;
if layer.bar.front.get_untracked() != in_front {
layer.bar.front.set(in_front);
}
let content = ctx.mount_keyed_offstage::<StackLayer>(
&layer.entry.id.to_string(),
StackLayerProps {
id: layer.entry.id,
path: layer.entry.path.clone(),
matches: layer.matches.clone(),
depth,
state: layer.entry.state.clone(),
slot: NavigationSlot {
item: layer.bar.item.clone(),
changed: self.changed.clone(),
scroll: layer.bar.scroll.clone(),
pull: layer.bar.pull.clone(),
large: layer.bar.large.clone(),
flying: layer.bar.flying.clone(),
growth: (motion.large_title_growth, motion.large_title_pull),
style: style.clone(),
searching: layer.bar.searching.clone(),
top: layer.bar.top.clone(),
under: layer.bar.under.clone(),
toolbars: matches!(props.bar, Some(Bar::Standard(_))),
bottom: layer.bar.bottom.clone(),
front: crate::app::ctx::InFront::new(layer.bar.front.clone(), around.clone()),
},
},
id == front || id == back,
);
let top = top_of(layer);
*layer.bar.top_now.lock() = top;
let clear = if layer.bar.under.load(Ordering::Acquire) {
0.0
} else {
top
};
let offset = if reduce_motion {
0.0
} else if id == front {
out * width
} else if id == back {
-motion.parallax * width * (1.0 - out)
} else {
0.0
};
let mut holder = Stack::new()
.key(format!("stack-screen-{}", layer.entry.id))
.size(FILL, FILL)
.padding_top(clear)
.child(content)
.ref_element(if shown.layers.last().is_some_and(|last| std::ptr::eq(last, layer)) {
self.screen.clone()
} else {
ElementRef::default()
})
.opacity(if reduce_motion && id == front { 1.0 - out } else { 1.0 })
.transform(Transform2D::translate(offset, 0.0));
if let Some(background) = props.background {
holder = holder.background(background);
}
if id == back {
let shade = Row::new()
.size(FILL, FILL)
.background(shades.shade)
.opacity(motion.dim * shades.shade_opacity * (1.0 - out))
.pointer_events_none();
holder = holder.child(shade.transition(fade.clone()));
}
screens = screens.child(holder.transition(slide.clone()).transition(fade.clone()));
}
let screens = screens.on_edge_pan({
let (shown, drag, changed) = (self.shown.clone(), self.drag.clone(), self.changed.clone());
let shown_all = self.shown.clone();
let (navigator, settle, history, screen) = (
navigator.clone(),
self.settle.clone(),
history.clone(),
self.screen.clone(),
);
move |event: EdgePanEvent| {
if event.edge != ScreenEdge::Left {
return;
}
let mut shown = shown.lock();
if shown.layers.len() < 2 {
return;
}
event.prevent_default();
event.stop_propagation();
let allowed = shown
.layers
.last()
.is_some_and(|layer| layer.bar.item.lock().back_gesture);
if !allowed || shown.motion != Motion::None {
return;
}
match event.phase {
GesturePhase::Start | GesturePhase::Change => {
drop(shown);
drag.set(event.translation.max(0.0));
}
GesturePhase::End => {
let far = event.translation > shown.width * motion.back_share || event.velocity > motion.back_speed;
let (towards, left) = if far {
(event.velocity, shown.width - event.translation)
} else {
(-event.velocity, event.translation)
};
shown.velocity = if left > 1.0 {
f64::from(towards.max(0.0) * motion.duration.as_secs_f32() / left)
} else {
0.0
};
if far {
drop(shown);
let before = navigator.handle.current_entry();
let (navigator, shown, drag, settle, changed) = (
navigator.clone(),
shown_all.clone(),
drag.clone(),
settle.clone(),
changed.clone(),
);
history.run_in_then(&screen, NavigationCommand::Back, NavigationSource::Edge, move |_| {
if navigator.handle.current_entry() != before {
return;
}
shown.lock().motion = Motion::Returning;
drag.set(NO_DRAG);
settle.restart();
changed.update(|version| *version += 1);
});
} else {
shown.motion = Motion::Returning;
drop(shown);
drag.set(NO_DRAG);
settle.restart();
changed.update(|version| *version += 1);
}
}
}
}
});
{
let hides = |id: Option<u64>| {
shown
.layers
.iter()
.chain(shown.leaving.iter())
.find(|layer| Some(layer.entry.id) == id)
.map(|layer| if layer.bar.item.lock().hides_tab_bar { 1.0 } else { 0.0 })
};
let front_hides: f32 = hides(front).unwrap_or(0.0);
let hidden = front_hides * (1.0 - out) + hides(back).unwrap_or(front_hides) * out;
shown.tab_bar = super::tabs::BarMove { hidden, pace, curve };
shown.tab_link = ctx.use_context::<super::tabs::TabBarLink>();
shown.sheet = ctx.use_context::<super::sheet::SheetScroll>();
}
let Some(bar) = props.bar else {
return screens.into();
};
let bar = match bar {
Bar::Standard(bar) => bar.adapted(&system, text_scale),
Bar::Custom(builder) => {
let layers: Vec<&Layer> = shown.layers.iter().chain(shown.leaving.iter()).collect();
let screen_of = |id: Option<u64>| {
let index = layers.iter().position(|layer| Some(layer.entry.id) == id)?;
let layer = layers[index];
let item = layer.bar.item.lock().clone();
Some(NavigationBarScreen {
large_title_in_view: item.large_title && !low && !layer.bar.title_gone.load(Ordering::Acquire),
searching: layer.bar.searching.get(),
item,
back_label: index
.checked_sub(1)
.map(|under| back_label_of(&layers[under].bar.item.lock(), &style.back)),
})
};
let Some(top) = screen_of(front) else {
return screens.into();
};
let state = NavigationBarState {
top,
under: screen_of(back),
out,
duration: pace,
easing: curve,
width,
safe_area,
navigator: navigator.clone(),
under_titles: shown
.layers
.iter()
.rev()
.skip(1)
.map(|layer| back_label_of(&layer.bar.item.lock(), &style.back))
.collect(),
low,
};
drop(shown);
return Column::new()
.size(FILL, FILL)
.child(builder(&state))
.child(Column::new().width(FILL).flex(1.0).child(screens))
.into();
}
};
let layers: Vec<&Layer> = shown.layers.iter().chain(shown.leaving.iter()).collect();
let part_of = |id: Option<u64>| {
let index = layers.iter().position(|layer| Some(layer.entry.id) == id)?;
let layer = layers[index];
let back_label = index
.checked_sub(1)
.map(|under| back_label_of(&layers[under].bar.item.lock(), &style.back));
let item = layer.bar.item.lock().clone();
let title_shown = !item.large_title || low || layer.bar.title_gone.load(Ordering::Acquire);
Some(BarPart {
item,
back_label,
label_fit: layer.bar.label_fit,
title: layer.bar.title.clone(),
back_probe: layer.bar.back_probe.clone(),
title_shown,
title_fade: motion.title_fade,
title_room: (width - safe_area.left - safe_area.right - 2.0 * (BACK_LEADING + BACK_WIDTH + BACK_GAP)).max(0.0),
label: layer.bar.label.clone(),
label_hidden: false,
short_probe: layer.bar.short_probe.clone(),
searching: layer.bar.searching.get(),
button_shapes: system.button_shapes,
})
};
let (back_part, mut front_part) = (part_of(back), part_of(front));
let menu_titles: Vec<String> = shown
.layers
.iter()
.rev()
.skip(1)
.map(|layer| back_label_of(&layer.bar.item.lock(), &style.back))
.collect();
let layer_of = |id: Option<u64>| layers.iter().copied().find(|layer| Some(layer.entry.id) == id);
let flight = match (layer_of(back), layer_of(front), &back_part, &front_part) {
(Some(under), Some(over), Some(under_part), Some(over_part))
if under_part.item.large_title
&& under_part.item.large_title_view.is_none()
&& !low
&& !under.bar.title_gone.load(Ordering::Acquire)
&& !under_part.item.bar_hidden
&& !over_part.item.bar_hidden
&& over_part.item.leading.is_none()
&& over_part.back_label.is_some()
&& under.bar.large.is_attached() =>
{
let origin = self.origin.rect();
let large = under.bar.large.rect();
let label = over.bar.label.rect();
let label = if over.bar.label.is_attached() && label.2 > 0.0 {
label
} else {
(
large.0,
large.1,
large.2 * bar.text_size / bar.large_title_size,
large.3 * bar.text_size / bar.large_title_size,
)
};
(large.2 > 0.0 && large.3 > 0.0).then(|| Flight {
title: under_part.item.title.clone(),
says: match over_part.label_fit {
LabelFit::Whole => over_part.back_label.clone().unwrap_or_default(),
LabelFit::Short => back_word(&bar),
LabelFit::Arrow => String::new(),
},
large: (large.0 - origin.0, large.1 - origin.1, large.2, large.3),
label: (label.0 - origin.0, label.1 - origin.1, label.2, label.3),
})
}
_ => None,
};
for layer in &layers {
let flying = flight.is_some() && Some(layer.entry.id) == back;
if layer.bar.flying.get_untracked() != flying {
layer.bar.flying.set(flying);
}
}
if let (Some(_), Some(part)) = (&flight, &mut front_part) {
part.label_hidden = true;
}
let overlay = Stack::new().size(FILL, FILL).pointer_events_none();
let overlay = match &flight {
Some(flight) => flight.draw(overlay, &bar, out, pace, curve),
None => overlay,
};
let between = |of: &dyn Fn(&BarPart) -> f32| {
let front = front_part.as_ref().map_or(1.0, of);
front * (1.0 - out) + back_part.as_ref().map_or(front, of) * out
};
let shown_share = between(&|part| if part.item.bar_hidden { 0.0 } else { 1.0 });
let bar_share = between(&|part| if part.searching { 0.0 } else { 1.0 });
let prompt_share = between(&|part| if part.item.prompt.is_some() { 1.0 } else { 0.0 });
let lined = between(&|part| if part.title_shown { 1.0 } else { 0.0 });
let toolbar_share = between(&|part| {
if part.item.toolbar.is_some() && !part.item.bar_hidden {
1.0
} else {
0.0
}
});
let (line_pace, line_curve) = if moving {
(pace, curve)
} else if back.is_some() {
(Duration::ZERO, curve)
} else {
(motion.title_fade, Easing::EASE)
};
let fade = |opacity: f32| {
move |element: Row| {
element
.opacity(opacity)
.transition(Transition::opacity().duration(pace).easing(curve))
}
};
let toolbar_of = |part: &Option<BarPart>, opacity: f32, front: bool| {
let tools = part.as_ref()?.item.toolbar.clone()?;
let row = Row::new()
.width(FILL)
.height(bar.toolbar_height)
.align_items(Alignment::Center)
.padding_horizontal(16.0)
.child(tools);
let row = if front { row } else { row.pointer_events_none() };
Some(fade(opacity)(row))
};
let mut tools = Stack::new().width(FILL).height(bar.toolbar_height);
for tool in [
toolbar_of(&back_part, out, false),
toolbar_of(&front_part, 1.0 - out, true),
]
.into_iter()
.flatten()
{
tools = tools.child(tool);
}
let items_height = bar_height + bar.prompt_height * prompt_share;
let mut items = Stack::new()
.width(FILL)
.height(items_height)
.stack_align(StackAlignment::BottomStart);
if let Some(part) = back_part {
items = items.child(bar_item(
&bar,
&go_back,
part,
out,
if reduce_motion {
0.0
} else {
-(1.0 - out) * width * motion.parallax
},
pace,
curve,
false,
&self.menu,
bar_height,
));
}
if let Some(part) = front_part {
items = items.child(bar_item(
&bar,
&go_back,
part,
1.0 - out,
if reduce_motion { 0.0 } else { out * width * 0.5 },
pace,
curve,
true,
&self.menu,
bar_height,
));
}
drop(shown);
let over = Column::new()
.width(FILL)
.child(
Column::new()
.width(FILL)
.height((safe_area.top + items_height * bar_share) * shown_share)
.clip()
.background(Color::new(
bar.background.r(),
bar.background.g(),
bar.background.b(),
(f32::from(bar.background.a()) * lined).round() as u8,
))
.backdrop_blur(bar.blur * lined)
.transition(Transition::height().duration(line_pace).easing(line_curve))
.transition(Transition::background_color().duration(line_pace).easing(line_curve))
.transition(Transition::backdrop_blur().duration(line_pace).easing(line_curve))
.child(
Column::new()
.width(FILL)
.padding_top(safe_area.top)
.padding_left(safe_area.left)
.padding_right(safe_area.right)
.child(items),
),
)
.child(
Row::new()
.width(FILL)
.height(0.5 * shown_share)
.background(bar.border)
.opacity(lined * bar_share)
.transition(Transition::opacity().duration(line_pace).easing(line_curve)),
);
let toolbar = Column::new()
.width(FILL)
.height((bar.toolbar_height + safe_area.bottom + 0.5) * toolbar_share)
.clip()
.align(Alignment::End)
.transition(Transition::height().duration(line_pace).easing(line_curve))
.background(bar.background)
.backdrop_blur(bar.blur)
.child(Row::new().width(FILL).height(0.5).background(bar.border))
.child(
Column::new()
.width(FILL)
.padding_left(safe_area.left)
.padding_right(safe_area.right)
.child(tools),
);
let mut whole = Stack::new()
.size(FILL, FILL)
.ref_element(self.origin.clone())
.stack_align(StackAlignment::TopStart)
.child(screens)
.child(toolbar)
.child(over)
.child(overlay);
if bar.back_menu && !menu_titles.is_empty() {
let opening = Transition::all()
.duration(MENU_MOVE)
.easing(Easing::Spring { velocity: 0.0 });
let mut list = Column::new()
.width(bar.back_menu_width)
.background(bar.background)
.backdrop_blur(bar.blur)
.border_inside(0.5, bar.border)
.rounded(13.0)
.clip()
.absolute_position(safe_area.left + 8.0, safe_area.top + bar_height + 4.0)
.opacity(if menu_open { 1.0 } else { 0.0 })
.transform(Transform2D::scale_uniform(if menu_open { 1.0 } else { 0.8 }))
.transition(opening);
for (steps, title) in menu_titles.iter().enumerate() {
let (navigator, open) = (navigator.clone(), self.menu.open.clone());
let steps = steps + 1;
if steps > 1 {
list = list.child(Row::new().width(FILL).height(0.5).background(bar.border));
}
list = list.child(
Row::new()
.width(FILL)
.height(bar.height)
.align_items(Alignment::Center)
.padding_horizontal(bar.inset)
.child(
Text::styled(
title,
TextStyle {
font_size: bar.text_size,
color: bar.title,
..TextStyle::default()
},
)
.nowrap(),
)
.on_click(move |_| {
open.set(false);
navigator.back_by(steps);
}),
);
}
let close = self.menu.clone();
let layer = Stack::new()
.size(FILL, FILL)
.child(
Row::new()
.size(FILL, FILL)
.background(shades.menu)
.opacity(if menu_open { shades.menu_opacity } else { 0.0 })
.transition(Transition::opacity().duration(MENU_MOVE))
.on_click(move |_| {
let just_opened = close.opened_at.lock().is_some_and(|at| at.elapsed() < MENU_OPENING);
if !just_opened {
close.open.set(false);
}
}),
)
.child(list);
whole = whole.child(if menu_open { layer } else { layer.pointer_events_none() });
}
whole.into()
}
fn after_layout(&self) {
let mut shown = self.shown.lock();
if std::mem::take(&mut shown.begin_due) {
self.begin.restart();
}
if let Some(link) = &shown.tab_link
&& link.0.get_untracked() != shown.tab_bar
{
link.0.set(shown.tab_bar);
}
if let (Some(sheet), Some(top)) = (&shown.sheet, shown.layers.last()) {
let list = top.bar.under.load(Ordering::Acquire).then(|| top.bar.scroll.clone());
let mut told = sheet.0.lock();
let same = match (&*told, &list) {
(Some(a), Some(b)) => a.same(b),
(None, None) => true,
_ => false,
};
if !same {
*told = list;
}
}
if let Some(at) = shown.layers.last().map(|layer| layer.bar.scroll.scroll_y()) {
let moved = at - shown.last_scroll;
if at <= 0.0 {
shown.scrolled_down = false;
} else if moved > 4.0 {
shown.scrolled_down = true;
} else if moved < -4.0 {
shown.scrolled_down = false;
}
if moved.abs() > 4.0 || at <= 0.0 {
shown.last_scroll = at;
}
if let Some(link) = &shown.tab_link
&& link.1.get_untracked() != shown.scrolled_down
{
link.1.set(shown.scrolled_down);
}
}
for layer in shown.layers.iter().chain(shown.leaving.iter()) {
let top = *layer.bar.top_now.lock();
if layer.bar.top.get_untracked() != top {
layer.bar.top.set(top);
}
}
let (width, large_title_height) = (shown.width, shown.large_title_height);
let shown = &mut *shown;
let mut changed = false;
for layer in shown.layers.iter_mut().chain(shown.leaving.iter_mut()) {
if !layer.bar.title.is_attached() || !layer.bar.back_probe.is_attached() {
continue;
}
let room = (width - layer.bar.title.width()) / 2.0 - BACK_LEADING - BACK_GAP;
let short = if layer.bar.short_probe.is_attached() {
layer.bar.short_probe.width()
} else {
BACK_WIDTH
};
let fit = if layer.bar.back_probe.width() <= room {
LabelFit::Whole
} else if short <= room {
LabelFit::Short
} else {
LabelFit::Arrow
};
changed |= std::mem::replace(&mut layer.bar.label_fit, fit) != fit;
}
for layer in shown.layers.iter().chain(shown.leaving.iter()) {
let gone = layer.bar.scroll.scroll_y() > large_title_height - 8.0;
changed |= layer.bar.title_gone.swap(gone, Ordering::AcqRel) != gone;
let pull = (-layer.bar.scroll.overscroll().1).max(0.0);
if (layer.bar.pull.get_untracked() - pull).abs() > 0.25 {
layer.bar.pull.set(pull);
}
}
if changed {
self.changed.update(|version| *version += 1);
}
}
}
#[derive(Clone, Copy, PartialEq)]
enum LabelFit {
Whole,
Short,
Arrow,
}
fn back_word(bar: &NavigationBar) -> String {
if bar.back.is_empty() {
crate::ui::current_locale().common.back.to_string()
} else {
bar.back.clone()
}
}
fn back_label_of(under: &NavigationItem, back: &str) -> String {
match &under.back_title {
Some(title) => title.clone(),
None if under.title.is_empty() && back.is_empty() => crate::ui::current_locale().common.back.to_string(),
None if under.title.is_empty() => back.to_owned(),
None => under.title.clone(),
}
}
#[derive(Clone)]
struct BackMenu {
open: Signal<bool>,
opened_at: Arc<Mutex<Option<Instant>>>,
}
struct Flight {
title: String,
says: String,
large: (f32, f32, f32, f32),
label: (f32, f32, f32, f32),
}
impl Flight {
fn draw(&self, overlay: Stack, bar: &NavigationBar, out: f32, pace: Duration, curve: Easing) -> Stack {
let between = |at_label: f32, at_large: f32| at_label + (at_large - at_label) * out;
let centre = (
between(self.label.0 + self.label.2 / 2.0, self.large.0 + self.large.2 / 2.0),
between(self.label.1 + self.label.3 / 2.0, self.large.1 + self.large.3 / 2.0),
);
let part = |says: &str, size: f32, weight: FontWeight, color: Color, laid: (f32, f32), scale: f32, opacity: f32| {
Text::styled(
says,
TextStyle {
font_size: size,
weight,
color,
..TextStyle::default()
},
)
.nowrap()
.transform(
Transform2D::translate(centre.0 - laid.0 / 2.0, centre.1 - laid.1 / 2.0)
.then(&Transform2D::scale_uniform(scale)),
)
.opacity(opacity)
.transition(Transition::transform().duration(pace).easing(curve))
.transition(Transition::opacity().duration(pace).easing(curve))
};
let ratio = if self.large.3 > 0.0 && self.label.3 > 0.0 {
self.label.3 / self.large.3
} else {
bar.text_size / bar.large_title_size
};
if self.says == self.title {
let mix = |at_label: u8, at_large: u8| between(f32::from(at_label), f32::from(at_large)).round() as u8;
let (label, large) = (bar.tint, bar.title);
return overlay.child(
part(
&self.title,
bar.large_title_size,
bar.large_title_weight,
TextStyle::default().color,
(self.large.2, self.large.3),
between(ratio, 1.0),
1.0,
)
.foreground(Color::new(
mix(label.r(), large.r()),
mix(label.g(), large.g()),
mix(label.b(), large.b()),
mix(label.a(), large.a()),
))
.transition(Transition::foreground().duration(pace).easing(curve)),
);
}
overlay
.child(part(
&self.title,
bar.large_title_size,
bar.large_title_weight,
bar.title,
(self.large.2, self.large.3),
between(ratio, 1.0),
out,
))
.child(part(
&self.says,
bar.text_size,
FontWeight::Normal,
bar.tint,
(self.label.2, self.label.3),
between(1.0, 1.0 / ratio),
1.0 - out,
))
}
}
struct BarPart {
item: NavigationItem,
back_label: Option<String>,
label_fit: LabelFit,
title: ElementRef,
back_probe: ElementRef,
title_shown: bool,
title_fade: Duration,
title_room: f32,
label: ElementRef,
label_hidden: bool,
short_probe: ElementRef,
searching: bool,
button_shapes: bool,
}
fn bar_item(
bar: &NavigationBar,
go_back: &GoBack,
part: BarPart,
opacity: f32,
shift: f32,
pace: Duration,
curve: Easing,
front: bool,
menu: &BackMenu,
bar_height: f32,
) -> Element {
let text = |content: &str, weight: FontWeight, color: Color| {
Text::styled(
content,
TextStyle {
font_size: if weight == bar.title_weight {
bar.title_size
} else {
bar.text_size
},
weight,
color,
..TextStyle::default()
},
)
.nowrap()
};
let middle: Element = match &part.item.title_view {
Some(view) => view.clone(),
None => text(&part.item.title, bar.title_weight, bar.title)
.max_width(part.title_room)
.text_overflow(TextOverflow::Elipsis)
.into(),
};
let title = Row::new()
.size(FILL, FILL)
.align_items(Alignment::Center)
.justify(Justify::Center)
.pointer_events_none()
.child(
Row::new()
.ref_element(part.title.clone())
.child(middle)
.opacity(if part.title_shown { 1.0 } else { 0.0 })
.transition(Transition::opacity().duration(part.title_fade)),
)
.transform(Transform2D::translate(shift, 0.0))
.transition(Transition::transform().duration(pace).easing(curve));
let mut whole = Stack::new().width(FILL).height(bar_height).child(title);
let mut sides = Row::new().size(FILL, FILL).align_items(Alignment::Center);
if let Some(leading) = &part.item.leading {
sides = sides.child(
Row::new()
.align_items(Alignment::Center)
.padding_left(8.0)
.child(leading.clone()),
);
} else if let Some(label) = &part.back_label {
let go_back = go_back.clone();
let short = back_word(bar);
let says = match part.label_fit {
LabelFit::Whole => label.as_str(),
LabelFit::Short => short.as_str(),
LabelFit::Arrow => "",
};
sides = sides.child(
Row::new()
.id("navigation-back")
.align_items(Alignment::Center)
.height(FILL)
.padding_left(BACK_LEADING - CHEVRON_WIDTH - BACK_SPACING)
.padding_right(12.0)
.spacing(BACK_SPACING)
.child(chevron(bar.tint))
.child(
Column::new()
.child(
text(says, FontWeight::Normal, bar.tint)
.ref_element(part.label.clone())
.opacity(if part.label_hidden { 0.0 } else { 1.0 }),
)
.child(Row::new().width(FILL).height(1.0).background(bar.tint).opacity(
if part.button_shapes && !part.label_hidden && !says.is_empty() {
1.0
} else {
0.0
},
)),
)
.on_click({
let menu = menu.clone();
move |_| {
if !menu.open.get_untracked() {
go_back();
}
}
})
.on_long_press({
let menu = menu.clone();
let enabled = bar.back_menu;
move |_: LongPressEvent| {
if enabled {
*menu.opened_at.lock() = Some(Instant::now());
menu.open.set(true);
}
}
}),
);
whole = whole.child(
Row::new().opacity(0.0).pointer_events_none().child(
Row::new()
.ref_element(part.short_probe.clone())
.child(text(&back_word(bar), FontWeight::Normal, bar.tint)),
),
);
whole =
whole.child(
Row::new().opacity(0.0).pointer_events_none().child(
Row::new()
.ref_element(part.back_probe.clone())
.child(text(label, FontWeight::Normal, bar.tint)),
),
);
}
sides = sides.child(Row::new().flex(1.0));
if let Some(trailing) = &part.item.trailing {
sides = sides.child(
Row::new()
.align_items(Alignment::Center)
.padding_right(8.0)
.child(trailing.clone()),
);
}
let main = whole.child(sides);
let mut whole = Column::new().width(FILL);
if let Some(prompt) = &part.item.prompt {
whole = whole.child(
Row::new()
.width(FILL)
.height(bar.prompt_height)
.align_items(Alignment::End)
.justify(Justify::Center)
.pointer_events_none()
.child(
Text::styled(
prompt,
TextStyle {
font_size: bar.prompt_size,
color: bar.title,
..TextStyle::default()
},
)
.nowrap(),
),
);
}
let mut whole = whole.child(main).opacity(opacity);
if !front {
whole = whole.pointer_events_none();
}
whole
.transition(Transition::opacity().duration(pace).easing(curve))
.into()
}
#[allow(deprecated)]
fn chevron(color: Color) -> Element {
#[cfg(all(target_os = "ios", feature = "raster"))]
if let Some(symbol) = crate::app::ios_symbol::symbol("chevron.backward", CHEVRON_POINT_SIZE, color) {
return crate::components::Image::new(symbol.image)
.width(symbol.width)
.height(symbol.height)
.into();
}
let (rise, run) = (
CHEVRON_HEIGHT / 2.0 - CHEVRON_STROKE / 2.0,
CHEVRON_WIDTH - CHEVRON_STROKE,
);
let length = rise.hypot(run) + CHEVRON_STROKE;
let angle = rise.atan2(run);
let stroke = |up: bool| {
let (centre_x, centre_y) = (
CHEVRON_STROKE / 2.0 + run / 2.0,
CHEVRON_HEIGHT / 2.0 + if up { -rise / 2.0 } else { rise / 2.0 },
);
Row::new()
.width(length)
.height(CHEVRON_STROKE)
.rounded(CHEVRON_STROKE / 2.0)
.background(color)
.transform(
Transform2D::translate(centre_x - length / 2.0, centre_y - CHEVRON_STROKE / 2.0)
.then(&Transform2D::rotate(if up { -angle } else { angle })),
)
};
Stack::new()
.width(CHEVRON_WIDTH)
.height(CHEVRON_HEIGHT)
.child(stroke(true))
.child(stroke(false))
.into()
}
impl StackOutlet {
pub fn large_title_scroll(ctx: &mut Ctx, content: impl Into<Element>) -> ScrollVertical {
let Some(slot) = ctx.use_context::<NavigationSlot>() else {
return ScrollVertical::new(content.into());
};
let item = slot.item.lock().clone();
let style = slot.style.clone();
let searching = (item.search.is_some() || item.search_view.is_some()) && slot.searching.get();
let mut over = Column::new().width(FILL);
let tall = ctx.window().logical_height() >= style.low_window;
if let (Some(view), true) = (&item.large_title_view, item.large_title && tall) {
over = over.child(
Row::new()
.width(FILL)
.ref_element(slot.large.clone())
.height(if searching { Dimension::Px(0.0) } else { Dimension::Auto })
.clip()
.child(view.clone()),
);
} else if item.large_title && tall {
over = over.child(ctx.mount_keyed::<LargeTitle>(
"navigation-large-title",
LargeTitleProps {
title: item.title.clone(),
style: style.clone(),
pull: slot.pull.clone(),
large: slot.large.clone(),
flying: slot.flying.clone(),
growth: slot.growth,
folded: searching,
},
));
}
if let Some(view) = &item.search_view {
over = over.child(Row::new().width(FILL).child(view.clone()));
} else if let Some(search) = &item.search {
over = over.child(ctx.mount_keyed::<SearchField>(
"navigation-search",
SearchFieldProps {
search: search.clone(),
style: style.clone(),
searching: slot.searching.clone(),
},
));
}
if !slot.under.swap(true, Ordering::AcqRel) {
slot.changed.update(|version| *version += 1);
}
let bottom = ctx.safe_area().bottom;
ScrollVertical::new(
Column::new()
.width(FILL)
.padding_top(slot.top.get())
.padding_bottom(bottom)
.child(over.child(content.into())),
)
.with_scroll_state(slot.scroll.clone())
}
pub fn searching(ctx: &mut Ctx) -> Option<Signal<bool>> {
ctx.use_context::<NavigationSlot>().map(|slot| slot.searching)
}
pub fn bar_inset(ctx: &mut Ctx) -> f32 {
ctx.use_context::<NavigationSlot>().map_or(0.0, |slot| slot.top.get())
}
pub fn screen_scroll(ctx: &mut Ctx) -> Option<ScrollState> {
ctx.use_context::<NavigationSlot>().map(|slot| slot.scroll)
}
pub fn mount(ctx: &mut Ctx) -> Element {
ctx.mount::<Self>(StackOutletProps::default())
}
pub fn mount_with(ctx: &mut Ctx, props: StackOutletProps) -> Element {
ctx.mount::<Self>(props)
}
}
#[derive(Clone)]
struct SearchFieldProps {
search: NavigationSearch,
style: Arc<NavigationBar>,
searching: Signal<bool>,
}
impl PartialEq for SearchFieldProps {
fn eq(&self, other: &Self) -> bool {
self.search.key() == other.search.key() && self.style == other.style && self.searching.id() == other.searching.id()
}
}
#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for SearchFieldProps {
fn write_info(&self, _buffer: &mut Vec<crate::app::component::ComponentInfo>) {}
}
struct SearchField {
cancelled: Signal<u64>,
acted: Mutex<u64>,
focused: Signal<bool>,
}
impl Component for SearchField {
type Props = SearchFieldProps;
fn create(_ctx: &mut Ctx) -> Self {
Self {
cancelled: Signal::new(0),
acted: Mutex::new(0),
focused: Signal::new(false),
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let props = ctx.props::<SearchFieldProps>().clone();
let searching = self.focused.get() || !props.search.text.get().is_empty();
let takes_bar = searching && props.search.hides_bar;
if props.searching.get_untracked() != takes_bar {
props.searching.set(takes_bar);
}
let cancelled = self.cancelled.get();
if std::mem::replace(&mut *self.acted.lock(), cancelled) != cancelled {
ctx.blur();
}
let bar = &props.style;
let faint = |alpha: u8| Color::new(bar.title.r(), bar.title.g(), bar.title.b(), alpha);
let (ground, placeholder) = (
bar.search_background.unwrap_or(faint(30)),
bar.search_placeholder.unwrap_or(faint(150)),
);
let style = |color: Color| TextStyle {
font_size: bar.text_size,
color,
..TextStyle::default()
};
let (focused, blurred) = (self.focused.clone(), self.focused.clone());
let field = Row::new()
.flex(1.0)
.height(bar.search_height)
.align_items(Alignment::Center)
.padding_horizontal(8.0)
.spacing(6.0)
.rounded(10.0)
.background(ground)
.child(magnifier(placeholder))
.child(
TextInput::new(props.search.text.clone())
.placeholder(&props.search.placeholder)
.placeholder_style(style(placeholder))
.text_style(style(bar.title))
.single_line()
.keyboard(KeyboardKind::Search)
.return_key(ReturnKey::Search)
.flex(1.0)
.on_focus(move || focused.set(true))
.on_blur(move || blurred.set(false)),
);
let mut row = Row::new()
.id("navigation-search")
.width(FILL)
.align_items(Alignment::Center)
.padding_horizontal(bar.inset)
.padding_top(if takes_bar { 8.0 } else { 0.0 })
.padding_bottom(8.0)
.spacing(12.0)
.child(field);
if searching {
let (text, cancelled) = (props.search.text.clone(), self.cancelled.clone());
row = row.child(
Row::new()
.id("navigation-search-cancel")
.height(bar.search_height)
.align_items(Alignment::Center)
.child(Text::styled(&props.search.cancel, style(bar.tint)).nowrap())
.on_click(move |_| {
text.set(String::new());
cancelled.update(|count| *count += 1);
}),
);
}
row
}
}
#[allow(deprecated)]
fn magnifier(color: Color) -> Element {
#[cfg(all(target_os = "ios", feature = "raster"))]
if let Some(symbol) = crate::app::ios_symbol::symbol("magnifyingglass", 15.0, color) {
return crate::components::Image::new(symbol.image)
.width(symbol.width)
.height(symbol.height)
.into();
}
Stack::new()
.width(16.0)
.height(16.0)
.child(
Row::new()
.width(11.0)
.height(11.0)
.rounded(5.5)
.border_inside(1.6, color)
.absolute_position(1.0, 1.0),
)
.child(
Row::new()
.width(6.0)
.height(1.6)
.rounded(0.8)
.background(color)
.absolute_position(9.5, 11.5)
.transform(Transform2D::rotate_deg(45.0)),
)
.into()
}
#[derive(Clone)]
struct LargeTitleProps {
title: String,
style: Arc<NavigationBar>,
pull: Signal<f32>,
large: ElementRef,
flying: Signal<bool>,
growth: (f32, f32),
folded: bool,
}
impl PartialEq for LargeTitleProps {
fn eq(&self, other: &Self) -> bool {
self.title == other.title
&& self.style == other.style
&& self.pull.id() == other.pull.id()
&& self.growth == other.growth
&& self.folded == other.folded
}
}
#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for LargeTitleProps {
fn write_info(&self, _buffer: &mut Vec<crate::app::component::ComponentInfo>) {}
}
struct LargeTitle;
impl Component for LargeTitle {
type Props = LargeTitleProps;
fn create(_ctx: &mut Ctx) -> Self {
Self
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let props = ctx.props::<LargeTitleProps>().clone();
let (growth, pull) = props.growth;
let grown = if pull > 0.0 {
1.0 + props.pull.get().min(pull) / pull * (growth - 1.0)
} else {
1.0
};
Row::new()
.width(FILL)
.height(if props.folded {
0.0
} else {
props.style.large_title_height
})
.clip()
.align_items(Alignment::Center)
.padding_horizontal(props.style.inset)
.child(
Text::styled(
&props.title,
TextStyle {
font_size: props.style.large_title_size * grown,
weight: props.style.large_title_weight,
color: props.style.title,
..TextStyle::default()
},
)
.nowrap()
.id("navigation-large-title")
.ref_element(props.large.clone())
.opacity(if props.flying.get() { 0.0 } else { 1.0 }),
)
}
}
#[derive(Clone)]
struct StackLayerProps {
id: u64,
path: String,
matches: Arc<Vec<RouteMatch>>,
depth: usize,
state: Option<Arc<dyn Any + Send + Sync>>,
slot: NavigationSlot,
}
impl PartialEq for StackLayerProps {
fn eq(&self, other: &Self) -> bool {
self.id == other.id && self.path == other.path && self.depth == other.depth && self.slot.style == other.slot.style
}
}
#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for StackLayerProps {
fn write_info(&self, _buffer: &mut Vec<crate::app::component::ComponentInfo>) {}
}
struct StackLayer;
impl Component for StackLayer {
type Props = StackLayerProps;
fn create(_ctx: &mut Ctx) -> Self {
Self
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let props = ctx.props::<StackLayerProps>().clone();
ctx.provide(RouterMatches(props.matches.clone()));
ctx.provide(OutletDepth(props.depth));
ctx.provide(StackState(props.state.clone()));
let (has_toolbar, hides_tab_bar) = props.slot.bottom.get();
let toolbar = props.slot.toolbars && has_toolbar;
if toolbar {
let under = match ctx.use_context::<crate::app::ctx::BottomBarInset>() {
Some(crate::app::ctx::BottomBarInset::Over(height)) if !hides_tab_bar => height,
_ => 0.0,
};
ctx.provide_if_changed(crate::app::ctx::BottomBarInset::Over(
under + props.slot.style.toolbar_height + 0.5,
));
} else if hides_tab_bar {
ctx.provide_if_changed(crate::app::ctx::BottomBarInset::Over(0.0));
}
ctx.provide(props.slot.front.clone());
ctx.provide(props.slot.clone());
match props.matches.get(props.depth) {
Some(route_match) => render_route_match(ctx, route_match),
None => Element::new(),
}
}
}