use std::{
sync::{
Arc, Mutex, PoisonError,
atomic::{AtomicU64, Ordering},
},
time::Duration,
};
use super::{
Button, Link,
icon::Icon,
icons, names,
part_style::Length,
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
shared::{IconChoice, fading, glyph, pressable},
theme::{Themed, current_breakpoint, current_theme},
};
use crate::{
animation::{AnimatableProperty, Animation, Easing, Keyframes, KeyframesId, Transition},
app::{
component::{Component, DevtoolsInspectable},
ctx::{Ctx, Modal, Root as Window, Timeout},
events::{SwipeDirection, SwipeEvent},
theme::{
BorderSize, IconSize, MotionDuration, MotionEasing, PaletteColor, RadiusSize, ShadowStyle, Theme, TypographyStyle,
},
},
components::{self, Column, Row, Stack},
core::{ElementRef, Signal},
layout::{Alignment, StackAlignment, layout_kind::Justify, text_style::FontWeight},
node::{CursorIcon, Element, HitTestBehavior, border::Border, dimension::Dimension, padding::Padding},
time::Instant,
};
pub const TOAST_DURATION: Duration = Duration::from_secs(5);
pub const TOASTS_SHOWN: usize = 3;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ToastPart {
Root,
Content,
Icon,
Text,
Title,
Description,
Action,
Close,
Timer,
Remaining,
Viewport,
List,
BehindNear,
BehindFar,
}
names!(ToastPart {
Root => "root",
Content => "content",
Icon => "icon",
Text => "text",
Title => "title",
Description => "description",
Action => "action",
Close => "close",
Timer => "timer",
Remaining => "remaining",
Viewport => "viewport",
List => "list",
BehindNear => "behind-near",
BehindFar => "behind-far",
});
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ToastVariant {
#[default]
Neutral,
Info,
Success,
Warning,
Destructive,
}
names!(ToastVariant {
Neutral => "neutral",
Info => "info",
Success => "success",
Warning => "warning",
Destructive => "destructive",
});
impl ToastVariant {
pub fn named(name: Name) -> Option<Self> {
Self::all().iter().copied().find(|variant| Name::from(*variant) == name)
}
pub fn icon(self) -> Option<&'static str> {
match self {
Self::Neutral => None,
Self::Info => Some(icons::INFO),
Self::Success => Some(icons::CHECK_CIRCLE),
Self::Warning => Some(icons::WARNING),
Self::Destructive => Some(icons::CLOSE_CIRCLE),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ToastState {
Action,
}
names!(ToastState {
Action => "action",
});
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ToastPosition {
TopLeft,
Top,
TopRight,
BottomLeft,
Bottom,
#[default]
BottomRight,
}
impl ToastPosition {
pub const ALL: [ToastPosition; 6] = [
Self::TopLeft,
Self::Top,
Self::TopRight,
Self::BottomLeft,
Self::Bottom,
Self::BottomRight,
];
fn at_bottom(self) -> bool {
matches!(self, Self::BottomLeft | Self::Bottom | Self::BottomRight)
}
fn across(self) -> Alignment {
match self {
Self::TopLeft | Self::BottomLeft => Alignment::Start,
Self::Top | Self::Bottom => Alignment::Center,
Self::TopRight | Self::BottomRight => Alignment::End,
}
}
}
#[derive(Clone)]
pub enum ToastAction {
Button(Button),
Link(Link),
}
impl ToastAction {
fn also(self, press: impl Fn() + Send + Sync + 'static) -> Self {
match self {
Self::Button(button) => Self::Button(button.on_click(move |_| press())),
Self::Link(link) => Self::Link(link.on_click(move |_| press())),
}
}
}
impl From<Button> for ToastAction {
fn from(button: Button) -> Self {
Self::Button(button)
}
}
impl From<Link> for ToastAction {
fn from(link: Link) -> Self {
Self::Link(link)
}
}
impl From<ToastAction> for Element {
fn from(action: ToastAction) -> Self {
match action {
ToastAction::Button(button) => button.into(),
ToastAction::Link(link) => link.into(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum TimeLeft {
All,
Part(f32),
RunningOut(Duration),
}
pub type ToastRenderer = Arc<dyn Fn(ToastView) -> Element + Send + Sync>;
#[derive(Clone)]
pub struct Toast {
title: Arc<str>,
description: Option<Arc<str>>,
variant: Name,
icon: Option<IconChoice>,
action: Option<ToastAction>,
close_button: bool,
label: Option<Arc<str>>,
timer: bool,
duration: Duration,
persistent: bool,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
on_close: Vec<Arc<dyn Fn() + Send + Sync>>,
left: TimeLeft,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Toast {
pub fn new(title: &str) -> Self {
Self {
title: Arc::from(title),
description: None,
variant: ToastVariant::Neutral.into(),
icon: None,
action: None,
close_button: true,
label: None,
timer: false,
duration: TOAST_DURATION,
persistent: false,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
on_close: Vec::new(),
left: TimeLeft::All,
id: None,
key: None,
}
}
pub fn description(mut self, description: &str) -> Self {
self.description = Some(Arc::from(description));
self
}
pub fn variant(mut self, variant: impl Into<Name>) -> Self {
self.variant = variant.into();
self
}
pub fn icon(mut self, icon: impl Into<IconChoice>) -> Self {
self.icon = Some(icon.into());
self
}
pub fn action(mut self, action: impl Into<ToastAction>) -> Self {
self.action = Some(action.into());
self
}
pub fn close_button(mut self, close_button: bool) -> Self {
self.close_button = close_button;
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn timer(mut self, timer: bool) -> Self {
self.timer = timer;
self
}
pub fn duration(mut self, duration: Duration) -> Self {
self.duration = duration;
self
}
pub fn persistent(mut self, persistent: bool) -> Self {
self.persistent = persistent;
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn on_close(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_close.push(Arc::new(handler));
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(super::PartStyle) -> super::PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
fn lasting(&self) -> Option<Duration> {
(!self.persistent).then_some(self.duration)
}
pub fn build(self, theme: &Theme) -> Element {
let case = Case {
variant: Some(self.variant),
size: None,
density: None,
breakpoint: current_breakpoint(),
states: self.states.clone(),
}
.state(ToastState::Action, self.action.is_some());
let icon = match self.icon {
Some(IconChoice(icon)) => icon,
None => ToastVariant::named(self.variant)
.and_then(ToastVariant::icon)
.map(Name::new),
};
let view = ToastView {
title: self.title,
description: self.description,
variant: self.variant,
icon,
action: self.action,
close_button: self.close_button,
label: self.label,
timer: self.timer,
recipe: theme
.resolve::<Toast>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
forced: self.forced,
on_close: self.on_close,
left: self.left,
id: self.id,
key: self.key,
};
match theme.renderer::<Toast>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<Toast> for Element {
fn from(toast: Toast) -> Self {
toast.build(¤t_theme())
}
}
pub struct ToastView {
pub title: Arc<str>,
pub description: Option<Arc<str>>,
pub variant: Name,
pub icon: Option<Name>,
pub action: Option<ToastAction>,
pub close_button: bool,
pub label: Option<Arc<str>>,
pub timer: bool,
pub recipe: ResolvedRecipe,
forced: Option<Interaction>,
on_close: Vec<Arc<dyn Fn() + Send + Sync>>,
left: TimeLeft,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl ToastView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part).forced(self.forced)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn icon(&self) -> Option<Element> {
self.icon.map(|icon| glyph(&self.part(ToastPart::Icon), icon, false))
}
pub fn text(&self) -> Column {
let title = self.part(ToastPart::Title);
let mut text = Column::new()
.flex(1.0)
.part(&self.part(ToastPart::Text))
.child(wrapping(&title, &self.title));
if let Some(description) = &self.description {
text = text.child(wrapping(&self.part(ToastPart::Description), description));
}
text
}
pub fn action(&self) -> Option<Row> {
let lent = self.recipe.lend(ToastPart::Action);
let action: Element = match self.action.clone()? {
ToastAction::Button(button) => button.rules(&lent).into(),
ToastAction::Link(link) => link.rules(&lent).into(),
};
Some(Row::new().part(&self.part(ToastPart::Action).unnamed()).child(action))
}
pub fn close(&self) -> components::Button {
let part = self.part(ToastPart::Close);
let side = part.rest().width.unwrap_or(Length::Icon(IconSize::Md));
let mut close = pressable(&part, false)
.describe("a11y_role", "button")
.describe("a11y_name", super::current_locale().common.close.clone())
.child(Icon::new(icons::CLOSE).size(side).build(self.theme()));
if !self.on_close.is_empty() {
let handlers = self.on_close.clone();
close = close.on_click(move |_| {
for handler in &handlers {
handler();
}
});
}
close
}
pub fn timer_width(&self) -> Option<f32> {
match self.part(ToastPart::Root).rest().width?.resolve(self.theme())? {
Dimension::Px(px) => Some(px),
_ => None,
}
}
pub fn timer(&self) -> Row {
let mut remaining = Row::new().part(&self.part(ToastPart::Remaining));
remaining = match self.left {
TimeLeft::All => remaining.width(Dimension::Pct(100.0)),
TimeLeft::Part(part) => remaining
.width(Dimension::Pct(100.0 * part.clamp(0.0, 1.0)))
.transition(Transition::width().duration(Duration::ZERO).linear()),
TimeLeft::RunningOut(left) => remaining
.width(Dimension::Pct(0.0))
.transition(Transition::width().duration(left).linear()),
};
Row::new()
.overflow_visible()
.part(&self.part(ToastPart::Timer))
.child(remaining)
}
pub fn render(self) -> Element {
let mut content = Row::new()
.align_items(if self.action.is_some() {
Alignment::Center
} else {
Alignment::Start
})
.part(&self.part(ToastPart::Content));
if let Some(icon) = self.icon() {
content = content.child(icon);
}
content = content.child(self.text());
if let Some(action) = self.action() {
content = content.child(action);
}
if self.close_button {
content = content.child(self.close());
}
let mut root = Column::new()
.part(&self.part(ToastPart::Root))
.describe("a11y_role", "status")
.describe("a11y_name", self.label.clone().unwrap_or_else(|| self.title.clone()))
.child(content);
if self.timer {
root = root.child(self.timer());
}
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root.into()
}
}
fn wrapping(part: &ResolvedPart, content: &str) -> Column {
let fill = Dimension::Pct(100.0);
Column::new()
.width(fill)
.part(part)
.child(part.text(content).width(fill))
}
impl crate::ui::Styled for Toast {
type Component = Self;
fn rules(self, rules: &crate::ui::Recipe) -> Self {
Self::rules(self, rules)
}
fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
Self::state(self, state, on)
}
}
impl Themed for Toast {
const NAME: &'static str = "toast";
type Renderer = ToastRenderer;
fn parts() -> crate::ui::Declared {
ToastPart::declared()
}
fn states() -> crate::ui::Declared {
ToastState::declared()
}
fn recipe() -> Recipe {
use PaletteColor::{
Destructive, Info, MutedForeground, Popover, PopoverForeground, Primary, Secondary, Success, Warning,
};
use ToastPart as P;
let edge = || Border::inside(BorderSize::Sm, PaletteColor::Border);
let behind = |s: super::PartStyle, width: f32, opacity: f32| {
s.width(width)
.height(8.0)
.background(Popover)
.border(edge())
.radius(RadiusSize::Lg)
.opacity(opacity)
};
Recipe::new()
.base(P::Root, |s| {
s.width(360.0)
.max_width(Length::Fill)
.background(Popover)
.foreground(PopoverForeground)
.border(edge())
.radius(RadiusSize::Lg)
.shadow(ShadowStyle::Lg)
})
.base(P::Content, |s| {
s.width(Length::Fill).padding_x(16.0).padding_y(16.0).gap(12.0)
})
.base(P::Icon, |s| {
s.square(Length::Icon(IconSize::Md)).foreground(PopoverForeground)
})
.base(P::Text, |s| s.gap(4.0))
.base(P::Title, |s| {
s.typography(TypographyStyle::Body)
.weight(FontWeight::Medium)
.foreground(PopoverForeground)
})
.base(P::Description, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.line_height(1.5)
.foreground(MutedForeground)
})
.base(P::Close, |s| {
fading(
s.square(Length::Icon(IconSize::Md))
.radius(RadiusSize::Sm)
.foreground(MutedForeground)
.cursor(CursorIcon::Pointer),
)
})
.hovered(P::Close, |s| s.foreground(PopoverForeground))
.focus_visible(P::Close, |s| s.focus_ring())
.base(P::Timer, |s| s.width(Length::Fill).height(2.0).background(Secondary))
.base(P::Remaining, |s| s.height(2.0).background(Primary))
.base(P::Viewport, |s| s.padding_x(16.0).padding_y(16.0))
.base(P::List, |s| s.gap(10.0))
.base(P::BehindNear, |s| behind(s, 336.0, 0.75))
.base(P::BehindFar, |s| behind(s, 312.0, 0.5))
.state(ToastState::Action, P::Content, |s| s.padding_y(14.0).padding_end(12.0))
.state(ToastState::Action, P::Text, |s| s.gap(2.0))
.variant(ToastVariant::Info, P::Icon, |s| s.foreground(Info))
.variant(ToastVariant::Success, P::Icon, |s| s.foreground(Success))
.variant(ToastVariant::Warning, P::Icon, |s| s.foreground(Warning))
.variant(ToastVariant::Destructive, P::Icon, |s| s.foreground(Destructive))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ToastId(u64);
#[derive(Clone)]
struct Shown {
id: ToastId,
toast: Arc<Mutex<Toast>>,
}
impl Shown {
fn toast(&self) -> Toast {
self.toast.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
}
impl DevtoolsInspectable for Shown {}
#[derive(Clone)]
pub struct Toasts {
shown: Signal<Vec<Shown>>,
paused: Signal<bool>,
next: Arc<AtomicU64>,
}
impl Toasts {
pub fn new() -> Self {
Self {
shown: Signal::new(Vec::new()),
paused: Signal::new(false),
next: Arc::new(AtomicU64::new(1)),
}
}
pub fn show(&self, toast: Toast) -> ToastId {
let id = ToastId(self.next.fetch_add(1, Ordering::Relaxed));
self.shown.update(|shown| {
shown.push(Shown {
id,
toast: Arc::new(Mutex::new(toast)),
})
});
id
}
pub fn dismiss(&self, id: ToastId) {
if !self
.shown
.with_untracked(|shown| shown.iter().any(|held| held.id == id))
{
return;
}
self.shown.update(|shown| shown.retain(|held| held.id != id));
if self.shown.with_untracked(Vec::is_empty) && self.paused.get_untracked() {
self.paused.set(false);
}
}
pub fn clear(&self) {
if self.shown.with_untracked(Vec::is_empty) {
return;
}
self.shown.set(Vec::new());
if self.paused.get_untracked() {
self.paused.set(false);
}
}
pub fn ids(&self) -> Vec<ToastId> {
self.shown.with(|shown| shown.iter().map(|held| held.id).collect())
}
pub fn len(&self) -> usize {
self.shown.with(Vec::len)
}
pub fn is_empty(&self) -> bool {
self.shown.with(Vec::is_empty)
}
pub fn mount(&self, ctx: &mut Ctx) -> Element {
self.mount_at(ctx, ToastPosition::default())
}
pub fn mount_at(&self, ctx: &mut Ctx, position: ToastPosition) -> Element {
ctx.mount::<ToastHost>(ToastHostProps {
toasts: self.clone(),
position,
})
}
fn same(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.next, &other.next)
}
}
impl Default for Toasts {
fn default() -> Self {
Self::new()
}
}
const ENTER_FROM_BELOW: KeyframesId = KeyframesId::new(0xFF11);
const ENTER_FROM_ABOVE: KeyframesId = KeyframesId::new(0xFF12);
const LEAVE_DOWNWARD: KeyframesId = KeyframesId::new(0xFF13);
const LEAVE_UPWARD: KeyframesId = KeyframesId::new(0xFF14);
const TRAVEL: f32 = 16.0;
pub(crate) fn keyframes() -> [Keyframes; 4] {
let slide = |id: KeyframesId, from: (f32, f32), to: (f32, f32)| {
Keyframes::new(id)
.frame(0.0, |frame| {
frame.set(AnimatableProperty::OffsetY, from.0);
frame.set(AnimatableProperty::Opacity, from.1);
})
.frame(1.0, |frame| {
frame.set(AnimatableProperty::OffsetY, to.0);
frame.set(AnimatableProperty::Opacity, to.1);
})
};
[
slide(ENTER_FROM_BELOW, (TRAVEL, 0.0), (0.0, 1.0)),
slide(ENTER_FROM_ABOVE, (-TRAVEL, 0.0), (0.0, 1.0)),
slide(LEAVE_DOWNWARD, (0.0, 1.0), (TRAVEL, 0.0)),
slide(LEAVE_UPWARD, (0.0, 1.0), (-TRAVEL, 0.0)),
]
}
#[derive(Clone)]
struct ToastHostProps {
toasts: Toasts,
position: ToastPosition,
}
impl PartialEq for ToastHostProps {
fn eq(&self, other: &Self) -> bool {
self.position == other.position && self.toasts.same(&other.toasts)
}
}
impl DevtoolsInspectable for ToastHostProps {}
struct ToastHost {
pile: Arc<Mutex<Pile>>,
settle: Timeout,
renders: Signal<u64>,
}
#[derive(Default)]
struct Pile {
front: Option<ToastId>,
open: bool,
spread: bool,
covered: Option<ToastId>,
fades: bool,
heights: Vec<(ToastId, ElementRef, f32)>,
}
impl Component for ToastHost {
type Props = ToastHostProps;
fn create(ctx: &mut Ctx) -> Self {
let renders = ctx.signal(0_u64);
let pile = Arc::new(Mutex::new(Pile::default()));
let settle = ctx.create_timeout(Duration::ZERO, {
let (renders, pile) = (renders.clone(), pile.clone());
move || {
let mut pile = pile.lock().unwrap_or_else(PoisonError::into_inner);
match pile.covered.take() {
Some(_) => pile.fades = true,
None => pile.open = false,
}
drop(pile);
renders.update(|count| *count += 1)
}
});
Self { pile, settle, renders }
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let _ = self.renders.get();
let ToastHostProps { toasts, position } = ctx.props::<ToastHostProps>().clone();
let front: Vec<(ToastId, Option<Duration>)> = toasts.shown.with(|shown| {
shown
.iter()
.rev()
.take(TOASTS_SHOWN)
.map(|held| (held.id, held.toast().lasting()))
.collect()
});
if front.is_empty() {
*self.pile.lock().unwrap_or_else(PoisonError::into_inner) = Pile::default();
return Element::from(Modal::new(Element::new()).open_when(false));
}
let paused = toasts.paused.get();
let theme = ctx.theme().clone();
let recipe = theme.resolve::<Toast>(
&Case {
breakpoint: current_breakpoint(),
..Case::default()
},
None,
);
let bottom = position.at_bottom();
let moving = theme.duration_value(MotionDuration::Base);
let (open, spread, covered, heights) = {
let mut pile = self.pile.lock().unwrap_or_else(PoisonError::into_inner);
pile
.heights
.retain(|(id, ..)| front.iter().any(|(shown, _)| shown == id));
for (id, _) in &front {
if !pile.heights.iter().any(|(held, ..)| held == id) {
pile.heights.push((*id, ElementRef::new(), 0.0));
}
}
let was = pile
.front
.filter(|was| *was != front[0].0 && front.iter().any(|(id, _)| id == was));
pile.front = Some(front[0].0);
if paused {
self.settle.cancel();
pile.open = true;
pile.covered = None;
} else if was.is_some() && !theme.reduced_motion() {
pile.open = true;
pile.covered = was;
self.settle.set_duration(theme.duration_value(MotionDuration::Slow));
self.settle.restart();
} else if pile.spread || pile.fades {
self.settle.set_duration(moving);
self.settle.restart();
}
pile.fades = false;
pile.spread = paused;
(pile.open, pile.spread, pile.covered, pile.heights.clone())
};
let height = |id: ToastId| {
heights
.iter()
.find(|(held, ..)| *held == id)
.map_or(0.0, |(.., height)| *height)
};
let gap = recipe
.part(ToastPart::List)
.rest()
.gap
.map_or(0.0, |gap| gap.resolve(&theme.spacing(), 0.0));
let away = if bottom { -1.0 } else { 1.0 };
let leave = (!theme.reduced_motion()).then(|| {
Animation::new(if bottom { LEAVE_DOWNWARD } else { LEAVE_UPWARD })
.duration(moving)
.easing(theme.easings().try_get(MotionEasing::Exit).unwrap_or(Easing::Linear))
});
let slide = Transition::offset_y().duration(moving).easing(
theme
.easings()
.try_get(MotionEasing::Standard)
.unwrap_or(Easing::Linear),
);
let fade = Transition::opacity().duration(moving).easing(
theme
.easings()
.try_get(MotionEasing::Standard)
.unwrap_or(Easing::Linear),
);
let behind = front.len() - 1;
let mut pile = Stack::new().overflow_visible().presence().stack_align(if bottom {
StackAlignment::BottomCenter
} else {
StackAlignment::TopCenter
});
if spread {
let all: f32 = front.iter().map(|(id, _)| height(*id)).sum::<f32>() + gap * behind as f32;
pile = pile.min_height(Dimension::Px(all));
}
let near = recipe.part(ToastPart::BehindNear);
let peek = match near.rest().height.and_then(|height| height.resolve(recipe.theme())) {
Some(Dimension::Px(px)) => px,
_ => 0.0,
};
let in_front = height(front[0].0);
let edge = |part: ToastPart, nth: f32| {
Row::new()
.overflow_visible()
.pointer_events_none()
.offset(0.0, away * (in_front + peek * nth - peek * 3.0))
.opacity(if spread { 0.0 } else { 1.0 })
.transition(Transition::opacity().duration(moving))
.child(Row::new().part(&recipe.part(part)).height(Dimension::Px(peek * 3.0)))
};
if in_front > 0.0 {
if behind >= 2 {
pile = pile.child(edge(ToastPart::BehindFar, 2.0).key("behind-far"));
}
if behind >= 1 {
pile = pile.child(edge(ToastPart::BehindNear, 1.0).key("behind-near"));
}
}
let mut before = vec![0.0; front.len()];
for nth in 1..front.len() {
before[nth] = before[nth - 1] + height(front[nth - 1].0) + gap;
}
for (nth, (id, duration)) in front.iter().copied().enumerate().rev() {
let drawn = nth == 0 || open;
let item = ctx.mount_keyed::<ToastItem>(
&id.0.to_string(),
ToastItemProps {
toasts: toasts.clone(),
id,
paused,
duration,
shown: drawn,
bottom,
},
);
let measured = heights
.iter()
.find(|(held, ..)| *held == id)
.map(|(_, measured, _)| measured.clone())
.unwrap_or_default();
let (held, renders) = (self.pile.clone(), self.renders.clone());
measured.observe_rect(move |rect| {
let mut pile = held.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(entry) = pile.heights.iter_mut().find(|(known, ..)| *known == id)
&& (entry.2 - rect.height).abs() >= 0.5
&& rect.height > 0.0
{
entry.2 = rect.height;
drop(pile);
renders.update(|count| *count += 1);
}
});
let place = Row::new()
.overflow_visible()
.key(id.0.to_string())
.ref_element(measured)
.offset(0.0, if spread { away * before[nth] } else { 0.0 })
.opacity(if nth == 0 || spread || covered == Some(id) { 1.0 } else { 0.0 })
.transition(slide.clone())
.transition(fade.clone());
let place = match &leave {
Some(leave) => place.exit_animation(leave.clone()),
None => place,
};
pile = pile.child(place.child(item));
}
let (enter, leave) = (toasts.paused.clone(), toasts.paused.clone());
let shown = Row::new()
.overflow_visible()
.on_mouse_enter(move || enter.set(true))
.on_mouse_leave(move || leave.set(false))
.child(pile);
let safe = ctx.safe_area();
let viewport = Column::new()
.size(Dimension::Pct(100.0), Dimension::Pct(100.0))
.hit_test(HitTestBehavior::ContentOnly)
.overflow_visible()
.padding(
Padding::new()
.top(safe.top)
.right(safe.right)
.bottom(safe.bottom + safe.keyboard)
.left(safe.left),
)
.child(
Column::new()
.size(Dimension::Pct(100.0), Dimension::Pct(100.0))
.hit_test(HitTestBehavior::ContentOnly)
.overflow_visible()
.justify(if bottom { Justify::End } else { Justify::Start })
.align_items(position.across())
.part(&recipe.part(ToastPart::Viewport))
.child(shown),
);
Element::from(
Modal::new(viewport)
.open_when(true)
.target(Window)
.dismiss_on_escape(false)
.window_chrome_layer(),
)
}
}
#[derive(Clone)]
struct ToastItemProps {
toasts: Toasts,
id: ToastId,
paused: bool,
duration: Option<Duration>,
shown: bool,
bottom: bool,
}
impl PartialEq for ToastItemProps {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
&& self.paused == other.paused
&& self.duration == other.duration
&& self.shown == other.shown
&& self.bottom == other.bottom
&& self.toasts.same(&other.toasts)
}
}
impl DevtoolsInspectable for ToastItemProps {}
struct Clock {
left: Duration,
since: Option<Instant>,
drawn: bool,
entered: Option<Instant>,
}
struct ToastItem {
timeout: Option<Timeout>,
clock: Mutex<Clock>,
again: Timeout,
renders: Signal<u64>,
}
impl Component for ToastItem {
type Props = ToastItemProps;
fn create(ctx: &mut Ctx) -> Self {
let props = ctx.props::<ToastItemProps>().clone();
let timeout = props.duration.map(|duration| {
let (toasts, id) = (props.toasts.clone(), props.id);
ctx.create_timeout(duration, move || toasts.dismiss(id))
});
let renders = ctx.signal(0_u64);
let again = ctx.create_timeout(Duration::ZERO, {
let renders = renders.clone();
move || renders.update(|count| *count += 1)
});
Self {
timeout,
clock: Mutex::new(Clock {
left: props.duration.unwrap_or_default(),
since: None,
drawn: false,
entered: None,
}),
again,
renders,
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let _ = self.renders.get();
let props = ctx.props::<ToastItemProps>().clone();
let now = Instant::now();
let mut clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(timeout) = &self.timeout {
match (props.paused, clock.since) {
(true, Some(since)) => {
clock.left = clock.left.saturating_sub(now.saturating_duration_since(since));
clock.since = None;
timeout.cancel();
}
(false, None) => {
clock.since = Some(now);
timeout.set_duration(clock.left);
timeout.start();
}
_ => {}
}
}
if !props.shown {
clock.drawn = false;
return Element::new();
}
let toast = props
.toasts
.shown
.with(|shown| shown.iter().find(|held| held.id == props.id).map(Shown::toast));
let Some(mut toast) = toast else {
return Element::new();
};
let left = match clock.since {
Some(since) => clock.left.saturating_sub(now.saturating_duration_since(since)),
None => clock.left,
};
toast.left = match props.duration {
None => TimeLeft::All,
Some(_) if clock.drawn && clock.since.is_some() => TimeLeft::RunningOut(left),
Some(duration) => TimeLeft::Part(left.as_secs_f32() / duration.as_secs_f32().max(f32::EPSILON)),
};
if !clock.drawn {
clock.drawn = true;
self.again.restart();
}
let theme = ctx.theme().clone();
let entered = *clock.entered.get_or_insert(now);
let coming = theme.duration_value(MotionDuration::Slow);
drop(clock);
let dismiss = {
let (toasts, id) = (props.toasts.clone(), props.id);
move || toasts.dismiss(id)
};
toast.action = toast.action.map(|action| action.also(dismiss.clone()));
let thrown = {
let (dismiss, bottom) = (dismiss.clone(), props.bottom);
move |swipe: SwipeEvent| {
let away = match swipe.direction {
SwipeDirection::Left | SwipeDirection::Right => true,
SwipeDirection::Down => bottom,
SwipeDirection::Up => !bottom,
};
if away {
dismiss();
}
}
};
let mut item = Row::new().overflow_visible().on_swipe(thrown);
if !theme.reduced_motion() && now.saturating_duration_since(entered) < coming {
item = item.animation(
Animation::new(if props.bottom {
ENTER_FROM_BELOW
} else {
ENTER_FROM_ABOVE
})
.duration(coming)
.easing(theme.easings().try_get(MotionEasing::Enter).unwrap_or(Easing::Linear)),
);
}
Element::from(item.child(toast.on_close(dismiss)))
}
}