ltk/widget/toast/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>

//! Toast / Snackbar — short-lived bottom-anchored message overlay.
//!
//! [`Toast`] is **not** an [`Element`]; it is a builder that produces
//! an [`OverlaySpec`] for the application to return from
//! [`App::overlays`](crate::App::overlays). The widget itself is
//! stateless: the application owns the visibility / timer state and
//! returns the overlay only while a toast is pending.
//!
//! Auto-dismissal is the application's responsibility. A typical
//! pattern is to spawn a `calloop` timer (or use the channel sender
//! from [`App::set_channel_sender`](crate::App::set_channel_sender))
//! that fires a "toast expired" message after [`Toast::duration`]
//! elapses.
//!
//! ```rust,no_run
//! # use ltk::{ toast, OverlaySpec, WidgetId };
//! # #[ derive( Clone ) ] enum Msg {}
//! # struct ToastState { message: String }
//! # struct App { toast: Option<ToastState> }
//! # impl App {
//! fn overlays( &self ) -> Vec<OverlaySpec<Msg>>
//! {
//!     match &self.toast
//!     {
//!         Some( t ) => vec![ toast( &t.message ).id( WidgetId( "toast/main" ) ).overlay() ],
//!         None      => vec![],
//!     }
//! }
//! # }
//! ```

use std::collections::hash_map::DefaultHasher;
use std::hash::{ Hash, Hasher };
use std::time::Duration;

use crate::app::{ Anchor, Layer, OverlayId, OverlaySpec };
use crate::types::{ Color, WidgetId };
use super::Element;

mod theme;

#[ cfg( test ) ]
mod tests;

/// Builder for a transient bottom-anchored notification overlay.
///
/// `Toast` does not own its own timer — the application is responsible
/// for clearing the toast (typically by storing its `message` in an
/// `Option` and resetting it via a delayed message).
pub struct Toast<Msg: Clone>
{
	/// Stable id for the overlay. Used to derive the [`OverlayId`] so
	/// the same toast persists across frames when the message stays the
	/// same.
	pub id:        WidgetId,
	/// Body text rendered inside the pill.
	pub message:   String,
	/// Display duration. The runtime does **not** consume this — it is
	/// returned through [`Toast::duration_value`] so the app's timer
	/// scheduler can read it back.
	pub duration:  Duration,
	/// Optional message fired when the user taps anywhere outside the
	/// pill. Convenient for "tap anywhere to dismiss" behaviour.
	pub on_dismiss: Option<Msg>,
	/// Optional override for the pill background colour.
	pub bg:        Option<Color>,
	/// Optional override for the body text colour.
	pub fg:        Option<Color>,
}

impl<Msg: Clone + 'static> Toast<Msg>
{
	/// Create a toast with the given message text. The default id is
	/// `"toast/default"`; override with [`Self::id`] when more than one
	/// toast variant might coexist.
	pub fn new( message: impl Into<String> ) -> Self
	{
		Self
		{
			id:         WidgetId( "toast/default" ),
			message:    message.into(),
			duration:   Duration::from_secs( 2 ),
			on_dismiss: None,
			bg:         None,
			fg:         None,
		}
	}

	/// Override the stable id used to derive the [`OverlayId`].
	pub fn id( mut self, id: WidgetId ) -> Self
	{
		self.id = id;
		self
	}

	/// Set the display duration. The toast itself does not auto-hide;
	/// this value is stored so the application's timer scheduler can
	/// read it back via [`Self::duration_value`].
	pub fn duration( mut self, secs: f32 ) -> Self
	{
		self.duration = Duration::from_secs_f32( secs.max( 0.0 ) );
		self
	}

	/// Read back the configured duration. Lets the app delegate timer
	/// setup to a helper that does not need to know how the toast was
	/// configured.
	pub fn duration_value( &self ) -> Duration
	{
		self.duration
	}

	/// Set the dismiss message fired on a tap outside the pill.
	pub fn on_dismiss( mut self, msg: Msg ) -> Self
	{
		self.on_dismiss = Some( msg );
		self
	}

	/// Override the pill background colour.
	pub fn background( mut self, c: Color ) -> Self
	{
		self.bg = Some( c );
		self
	}

	/// Override the body text colour.
	pub fn color( mut self, c: Color ) -> Self
	{
		self.fg = Some( c );
		self
	}

	/// Build an [`Element`] that paints the toast pill bottom-anchored
	/// inside its parent rect. The intended pattern is to push it on
	/// top of the main view via a [`Stack`](crate::stack):
	///
	/// ```text
	/// fn view( &self ) -> Element<Msg>
	/// {
	///     let body = column().push( … );
	///     let mut s = stack().push( body );
	///     if self.toast_until.is_some()
	///     {
	///         s = s.push( toast( "Saved" ).view() );
	///     }
	///     s.into()
	/// }
	/// ```
	///
	/// Works on every compositor — no `wlr-layer-shell` needed —
	/// because the pill is just a regular widget tree drawn on top of
	/// the existing canvas. Use [`Self::overlay`] only when you
	/// specifically need the toast to render *above other windows*
	/// (notification-style), which requires `wlr-layer-shell`.
	pub fn view( self ) -> Element<Msg>
	{
		use super::{ container, text };
		use crate::layout::stack::stack;
		use crate::layout::stack::{ HAlign, VAlign };

		let bg = self.bg.unwrap_or_else( theme::bg );
		let fg = self.fg.unwrap_or_else( theme::text );

		let pill: Element<Msg> = container(
				text( self.message.clone() )
					.size( theme::FONT_SIZE )
					.color( fg )
			)
			.background( bg )
			.padding_h( theme::PAD_H )
			.padding_v( 12.0 )
			.radius( theme::RADIUS )
			.into();

		stack::<Msg>()
			.push_aligned_margin( pill, HAlign::Center, VAlign::Bottom, theme::BOTTOM_MARGIN as f32 )
			.into()
	}

	/// Build the [`OverlaySpec`] the application returns from
	/// [`App::overlays`](crate::App::overlays). The overlay is anchored
	/// to the bottom edge of the screen with a small breathing margin.
	///
	/// Requires the compositor to advertise `wlr-layer-shell`. For a
	/// portable variant that works everywhere — at the cost of being
	/// confined to the application's surface — use [`Self::view`].
	pub fn overlay( self ) -> OverlaySpec<Msg>
	{
		use super::{ container, text };
		use crate::layout::stack::stack;

		let mut hasher = DefaultHasher::new();
		self.id.0.hash( &mut hasher );
		let overlay_id = OverlayId( hasher.finish() as u32 );

		let bg = self.bg.unwrap_or_else( theme::bg );
		let fg = self.fg.unwrap_or_else( theme::text );

		let pill: Element<Msg> = container(
				text( self.message.clone() )
					.size( theme::FONT_SIZE )
					.color( fg )
			)
			.background( bg )
			.padding_h( theme::PAD_H )
			.padding_v( 12.0 )
			.radius( theme::RADIUS )
			.into();

		// Centre horizontally, anchor to the bottom with a small margin.
		let body: Element<Msg> = stack()
			.push_aligned_margin(
				pill,
				crate::layout::stack::HAlign::Center,
				crate::layout::stack::VAlign::Bottom,
				theme::BOTTOM_MARGIN as f32,
			)
			.into();

		OverlaySpec
		{
			id:                 overlay_id,
			layer:              Layer::Overlay,
			anchor:             Anchor::BOTTOM,
			size:               ( 0, theme::HEIGHT + theme::BOTTOM_MARGIN as u32 + 24 ),
			exclusive_zone:     0,
			keyboard_exclusive: false,
			input_region:       None,
			view:               body,
			on_dismiss:         self.on_dismiss,
			anchor_widget_id:   None,
		}
	}
}

/// Create a [`Toast`] with the given message.
pub fn toast<Msg: Clone + 'static>( message: impl Into<String> ) -> Toast<Msg>
{
	Toast::new( message )
}