1use std::{
2 collections::HashMap,
3 sync::{
4 Arc, Mutex,
5 atomic::{AtomicU64, Ordering},
6 },
7};
8
9use sui_core::{
10 Event, Rect, SemanticsLiveRegion, SemanticsNode, SemanticsRole, Size, TimerToken, WakeEvent,
11 WidgetId,
12};
13use sui_layout::Constraints;
14use sui_reactive::Signal;
15use sui_runtime::{
16 ArrangeCtx, Command, EventCtx, LayerOptions, MeasureCtx, OverlayDismissPolicy,
17 OverlayFocusBehavior, OverlayKind, OverlayOptions, PaintBoundaryMode, PaintCtx,
18 REACTIVE_CHANGED, SemanticsCtx, SingleChild, StackHostOptions, StackSurfaceOptions, Widget,
19 WidgetPod, WidgetPodMutVisitor, WidgetPodVisitor,
20};
21use sui_scene::{Border, LayerCompositionMode};
22
23use crate::DefaultTheme;
24
25use sui_core::Point;
26
27pub struct OverlayHost {
33 child: SingleChild,
34}
35
36impl OverlayHost {
37 pub fn new<W>(child: W) -> Self
38 where
39 W: Widget + 'static,
40 {
41 Self {
42 child: SingleChild::new(child),
43 }
44 }
45
46 pub fn child(&self) -> &WidgetPod {
47 self.child.child()
48 }
49
50 pub fn child_mut(&mut self) -> &mut WidgetPod {
51 self.child.child_mut()
52 }
53}
54
55impl Widget for OverlayHost {
56 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
57 self.child.measure(ctx, constraints)
58 }
59
60 fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
61 self.child.arrange(ctx, bounds);
62 }
63
64 fn paint(&self, ctx: &mut PaintCtx) {
65 self.child.paint(ctx);
66 }
67
68 fn semantics(&self, ctx: &mut SemanticsCtx) {
69 self.child.semantics(ctx);
70 }
71
72 fn stack_host_options(&self) -> Option<StackHostOptions> {
73 Some(StackHostOptions::default())
74 }
75
76 fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
77 self.child.visit_children(visitor);
78 }
79
80 fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
81 self.child.visit_children_mut(visitor);
82 }
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
86pub enum OverlaySide {
87 Top,
88 Bottom,
89 Left,
90 Right,
91}
92
93impl OverlaySide {
94 pub const fn opposite(self) -> Self {
95 match self {
96 Self::Top => Self::Bottom,
97 Self::Bottom => Self::Top,
98 Self::Left => Self::Right,
99 Self::Right => Self::Left,
100 }
101 }
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
105pub enum OverlayAlignment {
106 Start,
107 Center,
108 End,
109}
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
112pub struct OverlayPlacement {
113 pub side: OverlaySide,
114 pub alignment: OverlayAlignment,
115}
116
117impl OverlayPlacement {
118 pub const TOP_START: Self = Self::new(OverlaySide::Top, OverlayAlignment::Start);
119 pub const TOP_CENTER: Self = Self::new(OverlaySide::Top, OverlayAlignment::Center);
120 pub const TOP_END: Self = Self::new(OverlaySide::Top, OverlayAlignment::End);
121 pub const BOTTOM_START: Self = Self::new(OverlaySide::Bottom, OverlayAlignment::Start);
122 pub const BOTTOM_CENTER: Self = Self::new(OverlaySide::Bottom, OverlayAlignment::Center);
123 pub const BOTTOM_END: Self = Self::new(OverlaySide::Bottom, OverlayAlignment::End);
124 pub const LEFT_START: Self = Self::new(OverlaySide::Left, OverlayAlignment::Start);
125 pub const LEFT_CENTER: Self = Self::new(OverlaySide::Left, OverlayAlignment::Center);
126 pub const LEFT_END: Self = Self::new(OverlaySide::Left, OverlayAlignment::End);
127 pub const RIGHT_START: Self = Self::new(OverlaySide::Right, OverlayAlignment::Start);
128 pub const RIGHT_CENTER: Self = Self::new(OverlaySide::Right, OverlayAlignment::Center);
129 pub const RIGHT_END: Self = Self::new(OverlaySide::Right, OverlayAlignment::End);
130
131 pub const fn new(side: OverlaySide, alignment: OverlayAlignment) -> Self {
132 Self { side, alignment }
133 }
134
135 pub const fn flipped(self) -> Self {
136 Self::new(self.side.opposite(), self.alignment)
137 }
138}
139
140#[derive(Debug, Clone, Copy, PartialEq)]
141pub struct OverlayCollisionPolicy {
142 pub flip: bool,
143 pub shift: bool,
144 pub resize: bool,
145}
146
147impl OverlayCollisionPolicy {
148 pub const NONE: Self = Self {
149 flip: false,
150 shift: false,
151 resize: false,
152 };
153
154 pub const ADAPTIVE: Self = Self {
155 flip: true,
156 shift: true,
157 resize: true,
158 };
159}
160
161impl Default for OverlayCollisionPolicy {
162 fn default() -> Self {
163 Self::ADAPTIVE
164 }
165}
166
167#[derive(Debug, Clone, PartialEq)]
168pub struct OverlayPlacementRequest {
169 pub anchor: Rect,
170 pub overlay_size: Size,
171 pub viewport: Rect,
172 pub preferred: OverlayPlacement,
173 pub fallbacks: Vec<OverlayPlacement>,
174 pub gap: f32,
175 pub margin: f32,
176 pub collision: OverlayCollisionPolicy,
177}
178
179impl OverlayPlacementRequest {
180 pub fn new(
181 anchor: Rect,
182 overlay_size: Size,
183 viewport: Rect,
184 preferred: OverlayPlacement,
185 ) -> Self {
186 Self {
187 anchor,
188 overlay_size,
189 viewport,
190 preferred,
191 fallbacks: Vec::new(),
192 gap: 0.0,
193 margin: 4.0,
194 collision: OverlayCollisionPolicy::ADAPTIVE,
195 }
196 }
197
198 pub fn fallbacks(mut self, fallbacks: impl IntoIterator<Item = OverlayPlacement>) -> Self {
199 self.fallbacks = fallbacks.into_iter().collect();
200 self
201 }
202
203 pub fn gap(mut self, gap: f32) -> Self {
204 self.gap = gap.max(0.0);
205 self
206 }
207
208 pub fn margin(mut self, margin: f32) -> Self {
209 self.margin = margin.max(0.0);
210 self
211 }
212
213 pub fn collision(mut self, collision: OverlayCollisionPolicy) -> Self {
214 self.collision = collision;
215 self
216 }
217}
218
219#[derive(Debug, Clone, Copy, PartialEq)]
220pub struct OverlayPlacementResult {
221 pub bounds: Rect,
222 pub placement: OverlayPlacement,
223 pub shifted: bool,
224 pub resized: bool,
225 pub overflow: f32,
226}
227
228pub fn place_overlay(request: &OverlayPlacementRequest) -> OverlayPlacementResult {
233 if !request.viewport.width().is_finite()
234 || !request.viewport.height().is_finite()
235 || request.viewport.width() <= 0.0
236 || request.viewport.height() <= 0.0
237 {
238 return OverlayPlacementResult {
239 bounds: placement_rect(
240 request.anchor,
241 request.overlay_size,
242 request.preferred,
243 request.gap,
244 ),
245 placement: request.preferred,
246 shifted: false,
247 resized: false,
248 overflow: 0.0,
249 };
250 }
251 let safe_viewport = inset_rect(request.viewport, request.margin);
252 let mut size = request.overlay_size;
253 let mut resized = false;
254 if request.collision.resize {
255 let next = Size::new(
256 size.width.min(safe_viewport.width()).max(0.0),
257 size.height.min(safe_viewport.height()).max(0.0),
258 );
259 resized = next != size;
260 size = next;
261 }
262
263 let mut candidates = vec![request.preferred];
264 candidates.extend(request.fallbacks.iter().copied());
265 if request.collision.flip {
266 let flipped = request.preferred.flipped();
267 if !candidates.contains(&flipped) {
268 candidates.push(flipped);
269 }
270 }
271
272 let mut best = None::<(usize, f32, Rect, OverlayPlacement)>;
273 for (index, placement) in candidates.into_iter().enumerate() {
274 let raw = placement_rect(request.anchor, size, placement, request.gap);
275 let overflow = overflow_amount(raw, safe_viewport);
276 let score = overflow + index as f32 * 0.001;
277 if best
278 .as_ref()
279 .is_none_or(|(_, best_score, _, _)| score < *best_score)
280 {
281 best = Some((index, score, raw, placement));
282 }
283 }
284
285 let (_, _, raw, placement) = best.unwrap_or((0, 0.0, Rect::ZERO, request.preferred));
286 let overflow = overflow_amount(raw, safe_viewport);
287 let bounds = if request.collision.shift {
288 shift_inside(raw, safe_viewport)
289 } else {
290 raw
291 };
292 OverlayPlacementResult {
293 bounds,
294 placement,
295 shifted: bounds.origin != raw.origin,
296 resized,
297 overflow,
298 }
299}
300
301fn placement_rect(anchor: Rect, size: Size, placement: OverlayPlacement, gap: f32) -> Rect {
302 let (x, y) = match placement.side {
303 OverlaySide::Top | OverlaySide::Bottom => {
304 let x = match placement.alignment {
305 OverlayAlignment::Start => anchor.x(),
306 OverlayAlignment::Center => anchor.x() + (anchor.width() - size.width) * 0.5,
307 OverlayAlignment::End => anchor.max_x() - size.width,
308 };
309 let y = if placement.side == OverlaySide::Top {
310 anchor.y() - gap - size.height
311 } else {
312 anchor.max_y() + gap
313 };
314 (x, y)
315 }
316 OverlaySide::Left | OverlaySide::Right => {
317 let y = match placement.alignment {
318 OverlayAlignment::Start => anchor.y(),
319 OverlayAlignment::Center => anchor.y() + (anchor.height() - size.height) * 0.5,
320 OverlayAlignment::End => anchor.max_y() - size.height,
321 };
322 let x = if placement.side == OverlaySide::Left {
323 anchor.x() - gap - size.width
324 } else {
325 anchor.max_x() + gap
326 };
327 (x, y)
328 }
329 };
330 Rect::new(x, y, size.width, size.height)
331}
332
333fn inset_rect(rect: Rect, margin: f32) -> Rect {
334 let horizontal = margin.min(rect.width() * 0.5);
335 let vertical = margin.min(rect.height() * 0.5);
336 Rect::new(
337 rect.x() + horizontal,
338 rect.y() + vertical,
339 (rect.width() - horizontal * 2.0).max(0.0),
340 (rect.height() - vertical * 2.0).max(0.0),
341 )
342}
343
344fn overflow_amount(rect: Rect, viewport: Rect) -> f32 {
345 (viewport.x() - rect.x()).max(0.0)
346 + (rect.max_x() - viewport.max_x()).max(0.0)
347 + (viewport.y() - rect.y()).max(0.0)
348 + (rect.max_y() - viewport.max_y()).max(0.0)
349}
350
351fn shift_inside(rect: Rect, viewport: Rect) -> Rect {
352 let max_x = (viewport.max_x() - rect.width()).max(viewport.x());
353 let max_y = (viewport.max_y() - rect.height()).max(viewport.y());
354 Rect::from_origin_size(
355 Point::new(
356 rect.x().clamp(viewport.x(), max_x),
357 rect.y().clamp(viewport.y(), max_y),
358 ),
359 rect.size,
360 )
361}
362
363static NEXT_NOTIFICATION_ID: AtomicU64 = AtomicU64::new(1);
364
365#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
366pub struct NotificationId(u64);
367
368impl NotificationId {
369 pub const fn get(self) -> u64 {
370 self.0
371 }
372}
373
374#[derive(Debug, Clone, Copy, PartialEq, Eq)]
375pub enum NotificationUrgency {
376 Polite,
377 Assertive,
378}
379
380#[derive(Debug, Clone, PartialEq)]
381pub struct TransientNotification {
382 pub id: NotificationId,
383 pub title: String,
384 pub message: String,
385 pub duration: Option<f64>,
386 pub urgency: NotificationUrgency,
387}
388
389impl TransientNotification {
390 pub fn new(title: impl Into<String>, message: impl Into<String>) -> Self {
391 Self {
392 id: NotificationId(NEXT_NOTIFICATION_ID.fetch_add(1, Ordering::Relaxed)),
393 title: title.into(),
394 message: message.into(),
395 duration: Some(5.0),
396 urgency: NotificationUrgency::Polite,
397 }
398 }
399
400 pub fn duration(mut self, seconds: f64) -> Self {
401 self.duration = Some(seconds.max(0.0));
402 self
403 }
404
405 pub fn persistent(mut self) -> Self {
406 self.duration = None;
407 self
408 }
409
410 pub fn urgency(mut self, urgency: NotificationUrgency) -> Self {
411 self.urgency = urgency;
412 self
413 }
414}
415
416#[derive(Default)]
417struct NotificationCenterInner {
418 revision: u64,
419 notifications: Vec<TransientNotification>,
420}
421
422#[derive(Clone)]
424pub struct NotificationCenter {
425 inner: Arc<Mutex<NotificationCenterInner>>,
426 revision: Signal<u64>,
427}
428
429impl NotificationCenter {
430 pub fn new() -> Self {
431 Self {
432 inner: Arc::new(Mutex::new(NotificationCenterInner::default())),
433 revision: Signal::named("NotificationCenter", 0),
434 }
435 }
436
437 pub fn push(&self, notification: TransientNotification) -> NotificationId {
438 let id = notification.id;
439 let revision = {
440 let mut inner = self
441 .inner
442 .lock()
443 .unwrap_or_else(std::sync::PoisonError::into_inner);
444 inner.notifications.push(notification);
445 inner.revision = inner.revision.wrapping_add(1);
446 inner.revision
447 };
448 self.revision.set(revision);
449 id
450 }
451
452 pub fn notify(&self, title: impl Into<String>, message: impl Into<String>) -> NotificationId {
453 self.push(TransientNotification::new(title, message))
454 }
455
456 pub fn dismiss(&self, id: NotificationId) -> bool {
457 let (changed, revision) = {
458 let mut inner = self
459 .inner
460 .lock()
461 .unwrap_or_else(std::sync::PoisonError::into_inner);
462 let before = inner.notifications.len();
463 inner
464 .notifications
465 .retain(|notification| notification.id != id);
466 let changed = before != inner.notifications.len();
467 if changed {
468 inner.revision = inner.revision.wrapping_add(1);
469 }
470 (changed, inner.revision)
471 };
472 if changed {
473 self.revision.set(revision);
474 }
475 changed
476 }
477
478 pub fn clear(&self) -> bool {
479 let (changed, revision) = {
480 let mut inner = self
481 .inner
482 .lock()
483 .unwrap_or_else(std::sync::PoisonError::into_inner);
484 let changed = !inner.notifications.is_empty();
485 inner.notifications.clear();
486 if changed {
487 inner.revision = inner.revision.wrapping_add(1);
488 }
489 (changed, inner.revision)
490 };
491 if changed {
492 self.revision.set(revision);
493 }
494 changed
495 }
496
497 pub fn snapshot(&self) -> Vec<TransientNotification> {
498 self.inner
499 .lock()
500 .unwrap_or_else(std::sync::PoisonError::into_inner)
501 .notifications
502 .clone()
503 }
504}
505
506impl Default for NotificationCenter {
507 fn default() -> Self {
508 Self::new()
509 }
510}
511
512pub struct NotificationHost {
514 center: NotificationCenter,
515 notifications: Vec<TransientNotification>,
516 timers: HashMap<TimerToken, NotificationId>,
517 scheduled: HashMap<NotificationId, TimerToken>,
518 frames: Vec<(NotificationId, Rect)>,
519 theme: DefaultTheme,
520 width: f32,
521 margin: f32,
522 gap: f32,
523}
524
525impl NotificationHost {
526 pub fn new(center: NotificationCenter) -> Self {
527 Self {
528 center,
529 notifications: Vec::new(),
530 timers: HashMap::new(),
531 scheduled: HashMap::new(),
532 frames: Vec::new(),
533 theme: DefaultTheme::default(),
534 width: 340.0,
535 margin: 16.0,
536 gap: 8.0,
537 }
538 }
539
540 pub fn theme(mut self, theme: DefaultTheme) -> Self {
541 self.theme = theme;
542 self
543 }
544
545 pub fn width(mut self, width: f32) -> Self {
546 self.width = width.max(120.0);
547 self
548 }
549
550 fn sync(&mut self, ctx: &mut EventCtx) {
551 self.notifications = self.center.snapshot();
552 let active = self
553 .notifications
554 .iter()
555 .map(|notification| notification.id)
556 .collect::<Vec<_>>();
557 let obsolete = self
558 .scheduled
559 .keys()
560 .copied()
561 .filter(|id| !active.contains(id))
562 .collect::<Vec<_>>();
563 for id in obsolete {
564 if let Some(token) = self.scheduled.remove(&id) {
565 self.timers.remove(&token);
566 ctx.cancel_timer(token);
567 }
568 }
569 for notification in &self.notifications {
570 let Some(duration) = notification.duration else {
571 continue;
572 };
573 if self.scheduled.contains_key(¬ification.id) {
574 continue;
575 }
576 let token = ctx.schedule_timer_after(duration);
577 self.scheduled.insert(notification.id, token);
578 self.timers.insert(token, notification.id);
579 }
580 ctx.request_measure();
581 ctx.request_paint();
582 ctx.request_semantics();
583 }
584
585 fn notification_height(&self, notification: &TransientNotification) -> f32 {
586 if notification.message.is_empty() {
587 48.0
588 } else {
589 68.0
590 }
591 }
592}
593
594impl Widget for NotificationHost {
595 fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
596 if command.is(REACTIVE_CHANGED) {
597 self.sync(ctx);
598 ctx.set_handled();
599 }
600 }
601
602 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
603 match event {
604 Event::Wake(WakeEvent::AnimationFrame { .. }) => {
605 self.sync(ctx);
606 ctx.set_handled();
607 }
608 Event::Wake(WakeEvent::Timer { token, .. }) => {
609 if let Some(id) = self.timers.remove(token) {
610 self.scheduled.remove(&id);
611 self.center.dismiss(id);
612 self.sync(ctx);
613 ctx.set_handled();
614 }
615 }
616 _ => {}
617 }
618 }
619
620 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
621 let _ = ctx.observe(&self.center.revision);
622 self.notifications = self.center.snapshot();
623 if self.notifications.iter().any(|notification| {
624 notification.duration.is_some() && !self.scheduled.contains_key(¬ification.id)
625 }) {
626 ctx.request_animation_frame();
627 }
628 constraints.clamp(Size::new(
629 if constraints.max.width.is_finite() {
630 constraints.max.width
631 } else {
632 self.width + self.margin * 2.0
633 },
634 if constraints.max.height.is_finite() {
635 constraints.max.height
636 } else {
637 480.0
638 },
639 ))
640 }
641
642 fn arrange(&mut self, _ctx: &mut ArrangeCtx, bounds: Rect) {
643 self.frames.clear();
644 let width = self
645 .width
646 .min((bounds.width() - self.margin * 2.0).max(0.0));
647 let mut y = bounds.y() + self.margin;
648 for notification in &self.notifications {
649 let height = self.notification_height(notification);
650 self.frames.push((
651 notification.id,
652 Rect::new(bounds.max_x() - self.margin - width, y, width, height),
653 ));
654 y += height + self.gap;
655 }
656 }
657
658 fn paint(&self, ctx: &mut PaintCtx) {
659 let metrics = self.theme.metrics;
660 let title_style = self.theme.body_text_style();
661 let message_style = self.theme.placeholder_text_style();
662 for notification in &self.notifications {
663 let Some((_, frame)) = self.frames.iter().find(|(id, _)| *id == notification.id) else {
664 continue;
665 };
666 ctx.fill_rrect_bordered(
667 *frame,
668 [metrics.corner_radius; 4],
669 self.theme.palette.surface_raised,
670 Border {
671 width: metrics.border_width,
672 color: self.theme.palette.border,
673 },
674 );
675 let padding = 12.0;
676 let title_rect = Rect::new(
677 frame.x() + padding,
678 frame.y() + 8.0,
679 (frame.width() - padding * 2.0).max(0.0),
680 title_style.line_height,
681 );
682 ctx.draw_text(title_rect, notification.title.clone(), title_style.clone());
683 if !notification.message.is_empty() {
684 let message_rect = Rect::new(
685 title_rect.x(),
686 title_rect.max_y() + 4.0,
687 title_rect.width(),
688 message_style.line_height,
689 );
690 ctx.draw_text(
691 message_rect,
692 notification.message.clone(),
693 message_style.clone(),
694 );
695 }
696 }
697 }
698
699 fn layer_options(&self) -> LayerOptions {
700 LayerOptions {
701 paint_boundary: PaintBoundaryMode::Explicit,
702 composition_mode: if self.notifications.is_empty() {
703 LayerCompositionMode::Normal
704 } else {
705 LayerCompositionMode::Overlay
706 },
707 }
708 }
709
710 fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
711 (!self.notifications.is_empty()).then_some(StackSurfaceOptions {
712 transient: true,
713 hit_test: false,
714 ..StackSurfaceOptions::default()
715 })
716 }
717
718 fn overlay_options(&self) -> Option<OverlayOptions> {
719 (!self.notifications.is_empty()).then_some(
720 OverlayOptions::new(OverlayKind::Notification)
721 .dismiss(OverlayDismissPolicy::NONE)
722 .focus(OverlayFocusBehavior::NONE),
723 )
724 }
725
726 fn semantics(&self, ctx: &mut SemanticsCtx) {
727 for notification in &self.notifications {
728 let Some((_, frame)) = self.frames.iter().find(|(id, _)| *id == notification.id) else {
729 continue;
730 };
731 let mut node = SemanticsNode::new(
732 WidgetId::new((1_u64 << 62) | notification.id.get()),
733 SemanticsRole::Status,
734 *frame,
735 );
736 node.parent = Some(ctx.widget_id());
737 node.name = Some(notification.title.clone());
738 node.description =
739 (!notification.message.is_empty()).then(|| notification.message.clone());
740 node.live_region = Some(match notification.urgency {
741 NotificationUrgency::Polite => SemanticsLiveRegion::Polite,
742 NotificationUrgency::Assertive => SemanticsLiveRegion::Assertive,
743 });
744 ctx.push(node);
745 }
746 }
747}
748
749#[cfg(test)]
750mod tests {
751 use super::*;
752 use sui_runtime::{Application, WindowBuilder};
753
754 #[test]
755 fn placement_flips_before_shifting_when_the_other_side_fits() {
756 let result = place_overlay(
757 &OverlayPlacementRequest::new(
758 Rect::new(80.0, 170.0, 40.0, 20.0),
759 Size::new(100.0, 70.0),
760 Rect::new(0.0, 0.0, 240.0, 200.0),
761 OverlayPlacement::BOTTOM_START,
762 )
763 .gap(4.0),
764 );
765 assert_eq!(result.placement, OverlayPlacement::TOP_START);
766 assert_eq!(result.bounds, Rect::new(80.0, 96.0, 100.0, 70.0));
767 assert!(!result.shifted);
768 }
769
770 #[test]
771 fn placement_shifts_and_resizes_inside_safe_viewport() {
772 let result = place_overlay(
773 &OverlayPlacementRequest::new(
774 Rect::new(190.0, 90.0, 10.0, 10.0),
775 Size::new(260.0, 140.0),
776 Rect::new(0.0, 0.0, 200.0, 120.0),
777 OverlayPlacement::RIGHT_START,
778 )
779 .margin(8.0),
780 );
781 assert_eq!(result.bounds, Rect::new(8.0, 8.0, 184.0, 104.0));
782 assert!(result.resized);
783 assert!(result.shifted);
784 }
785
786 #[test]
787 fn notification_host_exposes_live_status_and_expires_it() {
788 let center = NotificationCenter::new();
789 let mut runtime = Application::new()
790 .window(
791 WindowBuilder::new()
792 .title("Notifications")
793 .root(NotificationHost::new(center.clone())),
794 )
795 .build()
796 .unwrap();
797 let window_id = runtime.window_ids()[0];
798 let initial = runtime.render(window_id).unwrap();
799 assert!(
800 initial
801 .semantics
802 .iter()
803 .all(|node| node.role != SemanticsRole::Status)
804 );
805
806 center.push(
807 TransientNotification::new("Upload complete", "artifact.zip is ready")
808 .duration(0.05)
809 .urgency(NotificationUrgency::Assertive),
810 );
811 let _ = runtime.render(window_id).unwrap();
812 for (ready_window, event) in runtime.drain_ready_events() {
813 runtime.handle_event(ready_window, event).unwrap();
814 }
815 let shown = runtime.render(window_id).unwrap();
816 let status = shown
817 .semantics
818 .iter()
819 .find(|node| node.role == SemanticsRole::Status)
820 .expect("notification status semantics");
821 assert_eq!(status.name.as_deref(), Some("Upload complete"));
822 assert_eq!(status.live_region, Some(SemanticsLiveRegion::Assertive));
823 assert_eq!(
824 runtime.overlay_snapshot(window_id).unwrap().overlays.len(),
825 1
826 );
827
828 runtime.tick(0.06);
829 for (ready_window, event) in runtime.drain_ready_events() {
830 runtime.handle_event(ready_window, event).unwrap();
831 }
832 let expired = runtime.render(window_id).unwrap();
833 assert!(
834 expired
835 .semantics
836 .iter()
837 .all(|node| node.role != SemanticsRole::Status)
838 );
839 assert!(
840 runtime
841 .overlay_snapshot(window_id)
842 .unwrap()
843 .overlays
844 .is_empty()
845 );
846 }
847
848 #[test]
849 fn notification_center_accepts_threaded_producers() {
850 let center = NotificationCenter::new();
851 let producer = center.clone();
852 std::thread::spawn(move || {
853 producer.notify("Background task", "Indexed 42 files");
854 })
855 .join()
856 .unwrap();
857
858 let notifications = center.snapshot();
859 assert_eq!(notifications.len(), 1);
860 assert_eq!(notifications[0].title, "Background task");
861 }
862}