ev_lib 0.6.4

EV-invest shared Rust libraries, one per feature
Documentation
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
//! Toast notifications.
//!
//! Where the TS mirror exposes a module-global `toast(...)` function backed by a
//! singleton store, Dioxus has no clean cross-component mutable singleton, so the
//! Rust kit uses a [`ToasterProvider`] that owns a [`Toasts`] signal in context
//! plus a [`use_toaster`] hook returning a [`ToasterHandle`] with `.success`,
//! `.error`, `.info`, `.warning` and `.dismiss`.
//!
//! ## Stacking + animation
//!
//! Mirrors Sonner (and the TS port) via the shared `data-stack` CSS in
//! `tokens.css`: toasts are absolutely stacked at the pinned edge and pile up
//! collapsed (front [`VISIBLE_TOASTS`] peeking, scaled by depth), expanding into
//! a list on hover / keyboard focus — pure CSS, no host state. Each [`ToastItem`]
//! feeds the layout vars (`--index`, `--offset`, …); because heights can't be
//! measured here (that needs host-only `web-sys`), they're derived from a
//! constant [`TOAST_HEIGHT_EST`], so the collapsed pile is exact and the expanded
//! list is uniformly spaced.
//!
//! Animation stays host-timer-free: the enter is a CSS keyframe (it plays on DOM
//! insertion, so no host-only mount flip is needed — Dioxus effect timing can't
//! drive one), [`ToasterHandle::dismiss`] (and the close button) flip
//! [`ToastState`] to `Closing`/`data-state="closed"` to slide it out, and the
//! live node is dropped on the exit transform's `transitionend`
//! (`ontransitionend`, guarded to the closing state and the transform property)
//! rather than a `setTimeout`.
//! A `prefers-reduced-motion` block reduces the motion.
//!
//! Auto-dismiss is also host-timer-free: a no-op CSS `ev-toast-life` animation of
//! length `--life` runs, and its `animationend` closes the toast (`None` duration
//! = persistent, no life animation). Hovering/focusing the stack pauses just that
//! animation (`animation-play-state`), so the countdown holds and resumes with
//! the elapsed time preserved. Swipe-to-dismiss (pointer physics) stays TS-only;
//! the palette is the single dark theme (no `next-themes`). See the README
//! "Limitations".

use dioxus::prelude::*;

use crate::{
	cn,
	uikit::{TOAST_BASE, TOAST_CLOSE, TOAST_CONTENT, TOAST_TITLE, TOASTER_BASE, ToastPosition, ToastVariant},
};

/// Only the front three toasts show while the stack is collapsed.
const VISIBLE_TOASTS: usize = 3;
/// Gap (px) between toasts once the stack is expanded.
const GAP: u32 = 14;
/// Dioxus can't measure a toast's height (it needs host-only `web-sys`), so the
/// stack assumes this height (px) for the collapse clamp and the expanded
/// spacing: the collapsed pile is exact, the expanded list is uniformly spaced.
/// Tuned to a single-line toast (p-4 + one text-sm line).
const TOAST_HEIGHT_EST: u32 = 56;
/// Default auto-dismiss lifetime (ms). Mirrors the TS `DEFAULT_DURATION`.
const DEFAULT_DURATION_MS: u32 = 4000;

/// Lifecycle phase of a single toast. A toast mounts `Open` (plays the enter
/// keyframe); [`ToasterHandle::dismiss`] flips it to `Closing` (slides it out),
/// and it is dropped from the list once the exit `transitionend` fires. Mirrors
/// the TS `data-state` of `"open"` / `"closed"`.
#[derive(Clone, Copy, Default, PartialEq)]
pub enum ToastState {
	#[default]
	Open,
	Closing,
}

impl ToastState {
	fn as_str(&self) -> &'static str {
		match self {
			ToastState::Open => "open",
			ToastState::Closing => "closed",
		}
	}
}

#[derive(Clone, PartialEq)]
pub struct Toast {
	pub id: u64,
	pub message: String,
	pub variant: ToastVariant,
	pub state: ToastState,
	/// Auto-dismiss lifetime in ms, or `None` to persist until dismissed.
	pub duration: Option<u32>,
}

/// The live toast list, held in context by [`ToasterProvider`] alongside the
/// next-id counter.
#[derive(Clone, Copy)]
pub struct Toasts {
	items: Signal<Vec<Toast>>,
	next_id: Signal<u64>,
}

/// Imperative handle, the mirror of the TS global `toast` object. Obtained via
/// [`use_toaster`]; each method enqueues a toast of the matching variant, and
/// [`ToasterHandle::dismiss`] removes one by id.
#[derive(Clone, Copy)]
pub struct ToasterHandle {
	toasts: Toasts,
}

impl ToasterHandle {
	fn push(&self, message: impl Into<String>, variant: ToastVariant, duration: Option<u32>) -> u64 {
		let mut next_id = self.toasts.next_id;
		let id = *next_id.peek();
		next_id.set(id + 1);
		let mut items = self.toasts.items;
		items.write().push(Toast {
			id,
			message: message.into(),
			variant,
			state: ToastState::Open,
			duration,
		});
		id
	}

	pub fn toast(&self, message: impl Into<String>) -> u64 {
		self.push(message, ToastVariant::Default, Some(DEFAULT_DURATION_MS))
	}

	pub fn success(&self, message: impl Into<String>) -> u64 {
		self.push(message, ToastVariant::Success, Some(DEFAULT_DURATION_MS))
	}

	pub fn error(&self, message: impl Into<String>) -> u64 {
		self.push(message, ToastVariant::Error, Some(DEFAULT_DURATION_MS))
	}

	pub fn info(&self, message: impl Into<String>) -> u64 {
		self.push(message, ToastVariant::Info, Some(DEFAULT_DURATION_MS))
	}

	pub fn warning(&self, message: impl Into<String>) -> u64 {
		self.push(message, ToastVariant::Warning, Some(DEFAULT_DURATION_MS))
	}

	/// Full control over variant + lifetime. `duration` is ms, or `None` for a
	/// **persistent** toast that stays until the close button or
	/// [`ToasterHandle::dismiss`]. The convenience methods above use
	/// [`DEFAULT_DURATION_MS`]; this is the mirror of the TS `toast(msg, { duration })`.
	pub fn show(&self, message: impl Into<String>, variant: ToastVariant, duration: Option<u32>) -> u64 {
		self.push(message, variant, duration)
	}

	/// Begins the exit animation: the toast flips to [`ToastState::Closing`]
	/// (`data-state="closed"`) and stays mounted so the exit transition can play.
	/// The live node is removed by [`ToasterHandle::remove`] when that transition's
	/// `transitionend` fires — there is no host timer. A toast dismissed before it
	/// has ever painted mounts closed and so never transitions; [`ToastItem`] drops
	/// that one on mount instead.
	pub fn dismiss(&self, id: u64) {
		let mut items = self.toasts.items;
		if let Some(toast) = items.write().iter_mut().find(|t| t.id == id) {
			toast.state = ToastState::Closing;
		}
	}

	/// Drops a toast from the list outright. Wired to the exit `animationend`;
	/// the no-op-when-still-open guard lives at the call site (the enter
	/// `animationend` fires too, but only `Closing` toasts are removed).
	fn remove(&self, id: u64) {
		let mut items = self.toasts.items;
		items.write().retain(|t| t.id != id);
	}
}

/// Provides the [`Toasts`] context. Wrap the subtree that both enqueues toasts
/// (via [`use_toaster`]) and renders the [`Toaster`].
#[component]
pub fn ToasterProvider(children: Element) -> Element {
	let items = use_signal(Vec::new);
	let next_id = use_signal(|| 0u64);
	use_context_provider(|| Toasts { items, next_id });
	rsx! {
		{children}
	}
}

/// Returns the imperative [`ToasterHandle`] from the nearest
/// [`ToasterProvider`]. The mirror of importing the TS global `toast`.
pub fn use_toaster() -> ToasterHandle {
	ToasterHandle { toasts: use_context::<Toasts>() }
}

/// Renders the toast stack from context as a Sonner-style pile: collapsed by
/// default (front three peeking, scaled by depth), expanding into a list on
/// hover / keyboard focus (pure CSS). Fixed-positioned per `position` (default
/// bottom-right). Unlike the TS mirror there is no `setTimeout` auto-dismiss (so
/// nothing to pause on hover) and no swipe — the kit is render-only and
/// host-timer-free; dismiss happens on the close button or via
/// [`ToasterHandle::dismiss`], which slides the toast out and drops it on its
/// `transitionend`.
#[component]
pub fn Toaster(#[props(default)] position: ToastPosition, #[props(default)] class: String) -> Element {
	let toasts = use_context::<Toasts>();
	let y = match position {
		ToastPosition::TopLeft | ToastPosition::TopCenter | ToastPosition::TopRight => "top",
		_ => "bottom",
	};
	let cls = cn!(TOASTER_BASE, position.as_class(), class);
	let items = toasts.items.read();
	let total = items.len();
	rsx! {
		ol {
			class: cls,
			"data-slot": "toaster",
			"data-position": position.as_ref(),
			"data-y-position": y,
			"data-stack": "",
			style: "--front-height: {TOAST_HEIGHT_EST}px; --gap: {GAP}px;",
			// newest first → front of the stack (index 0)
			for (index, t) in items.iter().rev().cloned().enumerate() {
				ToastItem { key: "{t.id}", toast: t, index, total }
			}
		}
	}
}

/// Whether a `transitionend` is the toast's own exit transform finishing.
///
/// `transitionend` bubbles, so a closing toast also sees its descendants' — the
/// close button's 150ms `transition-colors`, a collapsed child's 300ms opacity
/// fade — and removing on those cuts the 350ms slide-out short. Mirrors the TS
/// guard (`e.propertyName === "transform"`).
///
/// Dioxus 0.7's `TransitionData` exposes no `property_name` accessor, so the name
/// is read off the concrete web event. Web-only: another renderer can't report it
/// and falls through to accepting the event, which is at worst the unguarded
/// behaviour — never a toast stranded on screen.
#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
fn is_transform_transition(e: &Event<TransitionData>) -> bool {
	e.downcast::<web_sys::TransitionEvent>().is_none_or(|t| t.property_name() == "transform")
}
#[cfg(not(all(target_arch = "wasm32", feature = "wasm")))]
fn is_transform_transition(_: &Event<TransitionData>) -> bool {
	true
}

/// One toast in the stack. Mirrors the TS `ToastItem`: the enter is a CSS
/// keyframe (plays on insertion), `data-state="closed"` slides it out, and the
/// live node is dropped on the exit transform's `transitionend` (guarded to the
/// closing state and to the transform property, so neither an open-state restack
/// nor a child's own transition removes it) — or straight away on mount, for a
/// toast dismissed before its first paint, which never transitions at all.
/// Layout vars come from the constant height — no measuring.
#[component]
fn ToastItem(toast: Toast, index: usize, total: usize) -> Element {
	let handle = use_toaster();
	let id = toast.id;
	let state = toast.state;
	// Dismissed before its first paint (pushed and dismissed in one handler), so it
	// mounts already closed: its computed style never changes, no transition runs,
	// and the `ontransitionend` exit path below would never fire — stranding it in
	// the list forever. Nothing was painted, so there is nothing to animate: drop it
	// once mounted. The effect never runs under SSR, which has no lifecycle to miss.
	let mounted_closing = use_hook(|| state == ToastState::Closing);
	use_effect(move || {
		if mounted_closing {
			handle.remove(id);
		}
	});
	let front = index == 0;
	let visible = index < VISIBLE_TOASTS;
	let offset = index as u32 * (TOAST_HEIGHT_EST + GAP);
	let z = total - index;
	// auto-dismiss is a CSS "life" animation (no host timer): its `animationend`
	// fires after `--life`, and hover pauses it via animation-play-state.
	let autodismiss = toast.duration.is_some();
	let life_ms = toast.duration.unwrap_or(0);

	rsx! {
		li {
			role: "status",
			"aria-live": "polite",
			"data-slot": "toast",
			"data-variant": toast.variant.as_ref(),
			"data-state": state.as_str(),
			"data-front": "{front}",
			"data-visible": "{visible}",
			"data-autodismiss": "{autodismiss}",
			style: "--index: {index}; --z-index: {z}; --offset: {offset}px; --initial-height: {TOAST_HEIGHT_EST}px; --life: {life_ms}ms;",
			onanimationend: move |e| {
				if e.animation_name() == "ev-toast-life" {
					handle.dismiss(id);
				}
			},
			ontransitionend: move |e| {
				if state == ToastState::Closing && is_transform_transition(&e) {
					handle.remove(id);
				}
			},
			class: cn!(TOAST_BASE, toast.variant.as_class()),
			div { class: TOAST_CONTENT,
				div { class: TOAST_TITLE, "{toast.message}" }
			}
			button {
				r#type: "button",
				"aria-label": "Close",
				"data-slot": "toast-close",
				class: TOAST_CLOSE,
				onclick: move |_| handle.dismiss(id),
				svg {
					xmlns: "http://www.w3.org/2000/svg",
					width: "16",
					height: "16",
					view_box: "0 0 24 24",
					fill: "none",
					stroke: "currentColor",
					"stroke-width": "2",
					"stroke-linecap": "round",
					"stroke-linejoin": "round",
					"aria-hidden": "true",
					path { d: "M18 6 6 18M6 6l12 12" }
				}
			}
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::uikit::test_util::render;

	#[test]
	fn enqueued_toast_renders_with_role_and_variant() {
		fn app() -> Element {
			rsx! {
				ToasterProvider {
					Seed {}
					Toaster {}
				}
			}
		}
		#[component]
		fn Seed() -> Element {
			let toaster = use_toaster();
			use_hook(move || toaster.success("Done"));
			rsx! {}
		}
		let html = render(app);
		assert!(html.contains("role=\"status\""), "{html}");
		assert!(html.contains("data-variant=\"success\""), "{html}");
		assert!(html.contains("data-state=\"open\""), "fresh toast mounts open: {html}");
		assert!(html.contains("Done"), "{html}");
		assert!(html.contains("data-slot=\"toast\""), "{html}");
	}

	#[test]
	fn close_button_carries_the_dismiss_path() {
		fn app() -> Element {
			rsx! {
				ToasterProvider {
					Seed {}
					Toaster {}
				}
			}
		}
		#[component]
		fn Seed() -> Element {
			let toaster = use_toaster();
			use_hook(move || toaster.error("Oops"));
			rsx! {}
		}
		let html = render(app);
		assert!(html.contains("M18 6 6 18M6 6l12 12"), "{html}");
		assert!(html.contains("aria-label=\"Close\""), "{html}");
	}

	#[test]
	fn every_variant_helper_enqueues() {
		fn app() -> Element {
			rsx! {
				ToasterProvider {
					Seed {}
					Toaster {}
				}
			}
		}
		#[component]
		fn Seed() -> Element {
			let toaster = use_toaster();
			use_hook(move || {
				toaster.toast("plain");
				toaster.info("info");
				toaster.warning("warning");
			});
			rsx! {}
		}
		let html = render(app);
		assert!(html.contains("data-variant=\"info\""), "{html}");
		assert!(html.contains("data-variant=\"warning\""), "{html}");
	}

	#[test]
	fn dismiss_marks_toast_closing_for_exit_animation() {
		fn app() -> Element {
			rsx! {
				ToasterProvider {
					Seed {}
					Toaster {}
				}
			}
		}
		#[component]
		fn Seed() -> Element {
			let toaster = use_toaster();
			use_hook(move || {
				let id = toaster.success("keep");
				toaster.dismiss(id);
			});
			rsx! {}
		}
		// Dismiss animates out rather than removing: the toast stays mounted in
		// the closing state (the live node is dropped on `transitionend`, which
		// the static SSR render cannot fire).
		let html = render(app);
		assert!(html.contains("keep"), "closing toast still mounted: {html}");
		assert!(html.contains("data-state=\"closed\""), "{html}");
	}

	#[test]
	fn a_toast_dismissed_before_first_paint_is_dropped_on_mount() {
		fn app() -> Element {
			rsx! {
				ToasterProvider {
					Seed {}
					Toaster {}
				}
			}
		}
		#[component]
		fn Seed() -> Element {
			let toaster = use_toaster();
			use_hook(move || {
				let id = toaster.info("cancelled");
				toaster.dismiss(id);
			});
			rsx! {}
		}
		// Mounted closed, it never transitions, so `ontransitionend` can't drop it —
		// the mount effect must, or it is stranded in the list forever. SSR runs no
		// effects, so drive it through a live VirtualDom.
		let mut dom = VirtualDom::new(app);
		dom.rebuild_in_place();
		dom.render_immediate(&mut dioxus_core::NoOpMutations);
		let html = dioxus_ssr::render(&dom);
		assert!(!html.contains("cancelled"), "ghost toast left mounted: {html}");
	}

	#[test]
	fn position_drives_the_root_attribute() {
		fn app() -> Element {
			rsx! {
				ToasterProvider {
					Toaster { position: ToastPosition::TopCenter }
				}
			}
		}
		let html = render(app);
		assert!(html.contains("data-position=\"top-center\""), "{html}");
		assert!(html.contains("data-y-position=\"top\""), "{html}");
		assert!(html.contains("data-stack"), "stack model is on: {html}");
		assert!(html.contains("data-slot=\"toaster\""), "{html}");
	}

	#[test]
	fn stack_marks_front_and_depth() {
		fn app() -> Element {
			rsx! {
				ToasterProvider {
					Seed {}
					Toaster {}
				}
			}
		}
		#[component]
		fn Seed() -> Element {
			let toaster = use_toaster();
			use_hook(move || {
				toaster.info("older");
				toaster.warning("newer");
			});
			rsx! {}
		}
		// newest toast is the front of the stack (index 0); both carry stacking vars
		let html = render(app);
		assert!(html.contains("data-front=\"true\""), "a front toast: {html}");
		assert!(html.contains("data-front=\"false\""), "a back toast: {html}");
		assert!(html.contains("--index: 0"), "{html}");
		assert!(html.contains("--index: 1"), "{html}");
		assert!(html.contains("data-visible=\"true\""), "{html}");
	}

	#[test]
	fn default_toasts_auto_dismiss_persistent_ones_do_not() {
		fn app() -> Element {
			rsx! {
				ToasterProvider {
					Seed {}
					Toaster {}
				}
			}
		}
		#[component]
		fn Seed() -> Element {
			let toaster = use_toaster();
			use_hook(move || {
				toaster.success("times out");
				toaster.show("sticky", ToastVariant::Info, None);
			});
			rsx! {}
		}
		let html = render(app);
		assert!(html.contains("data-autodismiss=\"true\""), "default auto-dismisses: {html}");
		assert!(html.contains("--life: 4000ms"), "{html}");
		assert!(html.contains("data-autodismiss=\"false\""), "persistent stays: {html}");
	}

	#[test]
	fn position_serializes_kebab() {
		assert_eq!(ToastPosition::TopLeft.as_ref(), "top-left");
	}
}