1use std::rc::Rc;
2use std::time::Duration;
3
4use taffy::{
5 AlignItems, Dimension, FlexDirection, JustifyContent, LengthPercentageAuto, Position, Style,
6};
7use web_time::Instant;
8
9use super::{
10 Container, Snapshot, Stateful, Styled, button, column, container, future_builder, row, scroll,
11 stateful, text,
12};
13use crate::anim::{Animated, ease};
14use crate::render::{Color, Shadow};
15use crate::runtime::task::{self, sleep};
16use crate::theme::Role;
17use crate::widget::{
18 Element, Event, EventCx, Handle, Key, Layer, PaintCx, Placement, Scope, State, Widget,
19};
20
21use super::button::Handler;
22type OnPick = Rc<dyn Fn(&mut EventCx, usize)>;
23type Build = Rc<dyn Fn(Shown) -> Overlay>;
24
25const MOTION: Duration = Duration::from_millis(250);
27
28const LONG_PRESS: Duration = Duration::from_millis(500);
31const LINGER: Duration = Duration::from_millis(1500);
32
33const MENU_MAX_HEIGHT: f32 = 320.0;
35
36const SCRIM: Color = Color::BLACK.alpha(0.4);
37const SHADOW: Shadow = Shadow {
38 color: Color::BLACK.alpha(0.25),
39 offset: (0.0, 4.0),
40 blur: 16.0,
41};
42
43#[derive(Clone, Copy)]
44enum Show {
45 Always,
46 Hover,
47 For(Duration),
48}
49
50#[derive(Default)]
51struct OverlayState {
52 hovered: bool,
53 pressed: Option<Instant>,
55 linger: Option<Instant>,
57 since: Option<Instant>,
58 shown: bool,
60 t: Animated<f32>,
62}
63
64pub struct Overlay {
66 layer: Layer,
67 style: Style,
68 child: [Element; 1],
69 scrim: Option<Color>,
70 on_dismiss: Option<Handler>,
71 show: Show,
72 slide: Option<(f32, f32)>,
75 closing: bool,
76}
77
78struct Sink {
81 child: [Element; 1],
82 style: Style,
83}
84
85fn layer(layer: Layer, style: Style, sink: Style, child: Element) -> Overlay {
86 Overlay {
87 layer,
88 style,
89 child: [Element::new(Sink {
90 child: [child],
91 style: sink,
92 })],
93 scrim: None,
94 on_dismiss: None,
95 show: Show::Always,
96 slide: None,
97 closing: false,
98 }
99}
100
101fn column_style() -> Style {
102 Style {
103 flex_direction: FlexDirection::Column,
104 ..Style::default()
105 }
106}
107
108pub fn overlay(child: impl Into<Element>) -> Overlay {
110 layer(Layer::Window, column_style(), column_style(), child.into())
111}
112
113pub fn screen(child: impl Into<Element>) -> Overlay {
117 layer(Layer::Screen, column_style(), column_style(), child.into())
118}
119
120pub fn backdrop(child: impl Into<Element>) -> Overlay {
123 let fill = Style {
124 flex_grow: 1.0,
125 ..column_style()
126 };
127 layer(Layer::Screen, column_style(), fill, child.into())
128}
129
130pub fn popup(child: impl Into<Element>) -> Overlay {
132 let mut sink = beside(false);
133 sink.min_size.width = LengthPercentageAuto::percent(1.0);
134 layer(Layer::Parent, Style::default(), sink, child.into())
135}
136
137fn beside(above: bool) -> Style {
139 let (near, far) = (
140 LengthPercentageAuto::percent(1.0),
141 LengthPercentageAuto::auto(),
142 );
143 let gap = LengthPercentageAuto::length(4.0);
144 let zero = LengthPercentageAuto::length(0.0);
145 Style {
146 position: Position::Absolute,
147 inset: taffy::Rect {
148 top: if above { far } else { near },
149 bottom: if above { near } else { far },
150 left: zero,
151 right: far,
152 },
153 margin: taffy::Rect {
154 top: if above { zero } else { gap },
155 bottom: if above { gap } else { zero },
156 left: zero,
157 right: zero,
158 },
159 size: taffy::Size {
160 width: Dimension::max_content(),
161 height: Dimension::auto(),
162 },
163 ..column_style()
164 }
165}
166
167impl Overlay {
168 pub fn modal(mut self, scrim: Color) -> Self {
170 self.scrim = Some(scrim);
171 self
172 }
173 pub fn on_dismiss(mut self, f: impl Fn(&mut EventCx) + 'static) -> Self {
176 self.on_dismiss = Some(Box::new(f));
177 self
178 }
179}
180
181impl From<Overlay> for Element {
182 fn from(w: Overlay) -> Self {
183 Element::new(w)
184 }
185}
186
187impl Styled for Overlay {
188 fn style_mut(&mut self) -> &mut Style {
189 &mut self.style
190 }
191}
192
193fn pointer(ev: &Event) -> Option<(f32, f32)> {
194 match *ev {
195 Event::PointerDown { x, y }
196 | Event::PointerMove { x, y }
197 | Event::PointerUp { x, y }
198 | Event::Wheel { x, y, .. } => Some((x, y)),
199 _ => None,
200 }
201}
202
203impl Widget for Overlay {
204 fn layer(&self) -> Option<Layer> {
205 Some(self.layer)
206 }
207 fn style(&self) -> Style {
208 self.style.clone()
209 }
210 fn children(&self) -> &[Element] {
211 &self.child
212 }
213 fn scroll(&self, state: &mut State, at: Placement, now: Instant) -> Option<(f32, f32)> {
214 let s = state.get::<OverlayState>();
215 let first = s.since.is_none();
216 let since = *s.since.get_or_insert(now);
217 if s.linger.is_some_and(|u| now >= u) {
218 s.linger = None;
219 }
220 s.shown = !self.closing
221 && match self.show {
222 Show::Always => true,
223 Show::Hover => {
224 let held = s.pressed.map(|t| now >= t + LONG_PRESS);
225 held.unwrap_or(s.hovered) || s.linger.is_some()
226 }
227 Show::For(d) => now < since + d,
228 };
229 let Some((dx, mut dy)) = self.slide else {
231 return (!s.shown).then_some((0.0, 1e6));
232 };
233 if self.layer == Layer::Parent && at.rest.y < at.anchor.y {
235 dy = -dy;
236 }
237 if first {
238 s.t.to(0.0, now, MOTION, ease::out_cubic);
239 }
240 let target = if s.shown { 1.0 } else { 0.0 };
241 s.t.to(target, now, MOTION, ease::out_cubic);
242 let k = 1.0 - s.t.get(now);
243 if k >= 1.0 {
245 return Some((-dx * 1e6, -dy * 1e6));
246 }
247 let (c, r) = (at.clip, at.rest);
249 let reach = |d: f32, lo: f32, hi: f32, start: f32, end: f32| match d {
250 d if d > 0.0 => hi - start,
251 d if d < 0.0 => end - lo,
252 _ => 0.0,
253 };
254 let w = reach(dx, c.x, c.x + c.w, r.x, r.x + r.w);
255 let h = reach(dy, c.y, c.y + c.h, r.y, r.y + r.h);
256 (k > 0.0).then_some((-dx * k * w, -dy * k * h))
257 }
258 fn paint(&self, cx: &mut PaintCx) {
259 let now = cx.now;
260 let s = cx.state.get::<OverlayState>();
261 let (shown, since, moving) = (s.shown, s.since, s.t.running(now));
262 let press = s.pressed.map(|t| t + LONG_PRESS).filter(|_| !shown);
263 let linger = s.linger.filter(|_| shown);
264 let t = match self.slide {
265 Some(_) => s.t.get(now),
266 None if shown => 1.0,
267 None => 0.0,
268 };
269 let timer = match (self.show, since) {
270 (Show::For(d), Some(since)) if shown => Some(since + d),
271 (Show::Hover, _) => press.or(linger),
272 _ => None,
273 };
274 if (self.slide.is_some() && moving) || timer.is_some_and(|at| now >= at) {
275 cx.request_placement();
276 } else if let Some(at) = timer {
277 cx.request_frame_at(at);
278 }
279 if let Some(c) = self.scrim
280 && t > 0.0
281 {
282 cx.fill(cx.clip, 0.0, c.alpha(c.a * t));
283 }
284 }
285 fn event(&self, ev: &Event, cx: &mut EventCx) {
286 if let Event::Back = ev {
287 if cx.state.get::<OverlayState>().shown {
288 if let Some(f) = &self.on_dismiss {
289 f(cx);
290 cx.stop();
291 }
292 if self.scrim.is_some() {
294 cx.stop();
295 }
296 }
297 return;
298 }
299 let at = pointer(ev);
300 if let Show::Hover = self.show {
301 let (now, hit) = (cx.now, at.map(|(x, y)| cx.hit(x, y)));
302 let s = cx.state.get::<OverlayState>();
303 let before = (s.hovered, s.pressed, s.linger);
304 match ev {
305 Event::PointerDown { .. } if hit == Some(true) => {
306 (s.hovered, s.pressed) = (true, Some(now));
307 }
308 Event::Cancel => {}
310 Event::PointerUp { .. } | Event::Leave => {
311 if s.pressed.is_some_and(|t| now >= t + LONG_PRESS) {
312 s.linger = Some(now + LINGER);
313 }
314 s.pressed = None;
315 s.hovered &= !matches!(ev, Event::Leave);
316 }
317 _ => {
318 if let Some(h) = hit {
319 s.hovered = h;
320 s.pressed = s.pressed.filter(|_| h);
321 }
322 }
323 }
324 if (s.hovered, s.pressed, s.linger) != before {
325 cx.request_redraw();
326 }
327 }
328 if at.is_none() || !cx.state.get::<OverlayState>().shown {
329 return;
330 }
331 if let (Event::PointerDown { .. }, Some(f)) = (ev, &self.on_dismiss) {
332 f(cx);
333 cx.stop();
334 }
335 if self.scrim.is_some() {
336 cx.stop();
337 }
338 }
339}
340
341impl Widget for Sink {
342 fn style(&self) -> Style {
343 self.style.clone()
344 }
345 fn children(&self) -> &[Element] {
346 &self.child
347 }
348 fn event(&self, ev: &Event, cx: &mut EventCx) {
349 if let Some((x, y)) = pointer(ev)
350 && cx.hit(x, y)
351 {
352 cx.stop();
353 }
354 }
355}
356
357fn card(child: impl Into<Element>) -> Container {
358 container(child)
359 .bg(Role::Surface)
360 .content(Role::Ink)
361 .radius(16.0)
362 .padding(24.0)
363 .shadow(SHADOW)
364}
365
366#[doc = example!("dialog")]
368pub fn dialog(child: impl Into<Element>) -> Overlay {
369 let mut o = overlay(card(child))
370 .modal(SCRIM)
371 .align(AlignItems::CENTER)
372 .justify(JustifyContent::CENTER)
373 .padding(24.0);
374 o.slide = Some((0.0, 1.0));
375 o
376}
377
378#[doc = example!("drawer")]
380pub fn drawer(child: impl Into<Element>) -> Overlay {
381 let panel = card(child).radius(0.0).width(280.0).grow(1.0);
382 let mut o = overlay(panel).modal(SCRIM);
383 o.style.flex_direction = FlexDirection::Row;
384 o.slide = Some((-1.0, 0.0));
385 o
386}
387
388#[doc = example!("bottom_sheet")]
390pub fn bottom_sheet(child: impl Into<Element>) -> Overlay {
391 let mut panel = card(child);
394 panel.style_mut().padding.bottom = taffy::LengthPercentage::length(24.0 + 16.0);
395 panel.style_mut().margin.bottom = LengthPercentageAuto::length(-16.0);
396 let mut o = overlay(panel)
397 .modal(SCRIM)
398 .justify(JustifyContent::FLEX_END);
399 o.slide = Some((0.0, 1.0));
400 o
401}
402
403#[doc = example!("snackbar")]
408pub fn snackbar(message: impl Into<String>) -> Overlay {
409 let bar = container(text(message).size(14.0).color(Role::OnInverse))
410 .bg(Role::Inverse)
411 .radius(8.0)
412 .padding_xy(16.0, 14.0);
413 let mut o = overlay(bar)
414 .align(AlignItems::CENTER)
415 .justify(JustifyContent::FLEX_END)
416 .padding(16.0);
417 o.show = Show::For(Duration::from_secs(4));
418 o.slide = Some((0.0, 1.0));
419 o
420}
421
422#[derive(Default)]
425pub struct Overlays {
426 entries: Vec<Entry>,
427 next: u64,
428}
429
430struct Entry {
431 key: u64,
432 build: Build,
433 closing: bool,
434 from: Option<Instant>,
436 until: Option<Instant>,
438}
439
440#[derive(Clone, Copy)]
442pub struct Shown {
443 h: Handle<Overlays>,
444 key: u64,
445}
446
447impl Shown {
448 pub fn close(self, cx: &mut EventCx) {
450 let key = self.key;
451 cx.update(self.h, move |o: &mut Overlays| {
452 let now = task::now();
453 let Some(e) = o.entries.iter_mut().find(|e| e.key == key && !e.closing) else {
454 return;
455 };
456 e.closing = true;
457 e.until = Some(now + MOTION);
458 if e.from.is_some_and(|f| f > now) {
459 (e.from, e.until) = (Some(now), Some(now));
460 }
461 requeue(&mut o.entries, now);
462 });
463 }
464}
465
466fn requeue(entries: &mut [Entry], now: Instant) {
468 let mut end = now;
469 for e in entries {
470 let (Some(from), Some(until)) = (e.from, e.until) else {
471 continue;
472 };
473 if from > now {
474 (e.from, e.until) = (Some(end), Some(end + (until - from)));
475 }
476 end = end.max(e.until.unwrap_or(end));
477 }
478}
479
480impl Handle<Overlays> {
481 pub fn show(self, cx: &mut EventCx, build: impl Fn(Shown) -> Overlay + 'static) {
484 let h = self;
485 cx.update(self, move |o: &mut Overlays| {
486 let now = task::now();
487 o.entries.retain(|e| e.until.is_none_or(|u| u > now));
489 let key = o.next;
490 o.next += 1;
491 let (from, until) = match build(Shown { h, key }).show {
492 Show::For(d) => {
493 let last = o.entries.iter().filter(|e| e.from.is_some());
494 let from = last.filter_map(|e| e.until).fold(now, Instant::max);
495 (Some(from), Some(from + d + MOTION))
496 }
497 _ => (None, None),
498 };
499 o.entries.push(Entry {
500 key,
501 build: Rc::new(build),
502 closing: false,
503 from,
504 until,
505 });
506 });
507 }
508}
509
510impl Handle<Overlays> {
511 pub fn confirm(
514 self,
515 cx: &mut EventCx,
516 title: impl Into<String>,
517 body: impl Into<String>,
518 ok: impl Into<String>,
519 on_ok: impl Fn(&mut EventCx) + 'static,
520 ) {
521 let (title, body, ok): (String, String, String) = (title.into(), body.into(), ok.into());
522 let on_ok = Rc::new(on_ok);
523 self.show(cx, move |me| {
524 let on_ok = on_ok.clone();
525 dialog(
526 column([
527 text(title.clone()).size(20.0).into(),
528 text(body.clone()).size(14.0).color(Role::Muted).into(),
529 row([
530 button(text("Cancel").color(Role::Ink))
531 .color(Role::Surface)
532 .flat()
533 .on_click(move |cx| me.close(cx))
534 .into(),
535 button(text(ok.clone()))
536 .flat()
537 .on_click(move |cx| {
538 me.close(cx);
539 on_ok(cx);
540 })
541 .into(),
542 ])
543 .gap(8.0)
544 .justify(JustifyContent::FLEX_END)
545 .into(),
546 ])
547 .gap(12.0),
548 )
549 });
550 }
551}
552
553#[doc = example!("overlays")]
555pub fn overlays<E: Into<Element>>(
556 content: impl Fn(Handle<Overlays>) -> E + 'static,
557) -> Stateful<Overlays> {
558 stateful(move |s: &Overlays, h| {
559 let shown = s.entries.iter().map(move |e| entry(e, h));
560 column(std::iter::once(content(h).into()).chain(shown)).fill()
561 })
562}
563
564fn entry(e: &Entry, h: Handle<Overlays>) -> Element {
568 let (build, closing, key, until) = (e.build.clone(), e.closing, e.key, e.until);
569 let timer = move |_: Scope| async move {
570 match until {
571 Some(u) => sleep(u.saturating_duration_since(task::now())).await,
572 None => std::future::pending().await,
573 }
574 };
575 let view = move |snap: &Snapshot<Option<()>>| -> Element {
576 if snap.done {
577 return column([]).into();
578 }
579 let shown = Shown { h, key };
580 let mut o = build(shown);
581 o.closing = closing;
582 if o.scrim.is_some() && o.on_dismiss.is_none() {
583 o.on_dismiss = Some(Box::new(move |cx| shown.close(cx)));
584 }
585 o.into()
586 };
587 let shown = move || Element::from(future_builder((key, closing), timer, view.clone()));
588 let Some(from) = e.from else {
589 return shown().key(key);
590 };
591 let queue = move |_: Scope| sleep(from.saturating_duration_since(task::now()));
592 let wait = move |snap: &Snapshot<Option<()>>| match snap.done {
593 true => shown(),
594 false => column([]).into(),
595 };
596 Element::from(future_builder((key, from), queue, wait)).key(key)
597}
598
599pub struct OnBack(Handler);
602
603#[doc = example!("on_back")]
605pub fn on_back(f: impl Fn(&mut EventCx) + 'static) -> OnBack {
606 OnBack(Box::new(f))
607}
608
609impl From<OnBack> for Element {
610 fn from(w: OnBack) -> Self {
611 Element::new(w)
612 }
613}
614
615fn listener() -> Style {
617 Style {
618 position: Position::Absolute,
619 ..Style::default()
620 }
621}
622
623impl Widget for OnBack {
624 fn style(&self) -> Style {
625 listener()
626 }
627 fn event(&self, ev: &Event, cx: &mut EventCx) {
628 if let Event::Back = ev {
629 (self.0)(cx);
630 cx.stop();
631 }
632 }
633}
634
635pub struct OnKey(KeyHandler);
639
640type KeyHandler = Box<dyn Fn(&mut EventCx, Key)>;
641
642#[doc = example!("on_key")]
644pub fn on_key(f: impl Fn(&mut EventCx, Key) + 'static) -> OnKey {
645 OnKey(Box::new(f))
646}
647
648impl From<OnKey> for Element {
649 fn from(w: OnKey) -> Self {
650 Element::new(w)
651 }
652}
653
654impl Widget for OnKey {
655 fn style(&self) -> Style {
656 listener()
657 }
658 fn event(&self, ev: &Event, cx: &mut EventCx) {
659 if let Event::Key(k) = ev {
660 (self.0)(cx, *k);
661 }
662 }
663}
664
665#[doc = example!("tooltip")]
667pub fn tooltip(child: impl Into<Element>, tip: impl Into<String>) -> Container {
668 let tip = container(text(tip).size(13.0).color(Role::OnInverse))
669 .bg(Role::Inverse)
670 .radius(6.0)
671 .padding_xy(8.0, 4.0);
672 let mut p = layer(Layer::Parent, Style::default(), beside(true), tip.into());
673 p.show = Show::Hover;
674 container(child).child(p)
675}
676
677pub struct Dropdown {
679 labels: Vec<String>,
680 selected: usize,
681 on_change: Option<OnPick>,
682}
683
684#[doc = example!("dropdown")]
686pub fn dropdown<S: Into<String>>(labels: impl IntoIterator<Item = S>, selected: usize) -> Dropdown {
687 Dropdown {
688 labels: labels.into_iter().map(Into::into).collect(),
689 selected,
690 on_change: None,
691 }
692}
693
694impl Dropdown {
695 pub fn on_change(mut self, f: impl Fn(&mut EventCx, usize) + 'static) -> Self {
697 self.on_change = Some(Rc::new(f));
698 self
699 }
700}
701
702impl From<Dropdown> for Element {
703 fn from(d: Dropdown) -> Self {
704 let Dropdown {
705 labels,
706 selected,
707 on_change,
708 } = d;
709 let on_change: OnPick = on_change.unwrap_or_else(|| Rc::new(|_, _| {}));
710 stateful(move |&open: &bool, h| {
711 let set =
712 move |v: bool| move |cx: &mut EventCx| cx.update(h, move |o: &mut bool| *o = v);
713 let field = button(
714 row([
715 text(&labels[selected]).color(Role::Ink).into(),
716 text("▾").color(Role::Ink).into(),
717 ])
718 .gap(8.0),
719 )
720 .color(Role::Track)
721 .on_click(set(!open));
722 let menu = {
723 let last = labels.len().saturating_sub(1);
724 let items = labels.iter().enumerate().map(|(i, l)| {
725 let f = on_change.clone();
726 let bg = if i == selected {
727 Role::Selected
728 } else {
729 Role::Surface
730 };
731 button(text(l).color(Role::Ink))
732 .color(bg)
733 .flat()
734 .radius(6.0)
735 .justify(JustifyContent::FLEX_START)
736 .on_click(move |cx| {
737 cx.update(h, |o: &mut bool| *o = false);
738 if i != selected {
739 f(cx, i);
740 }
741 })
742 .into()
743 });
744 let mut options = scroll(column(items)).max_height(MENU_MAX_HEIGHT);
745 if open {
746 options = options.start_at(selected as f32 / last.max(1) as f32);
748 }
749 let list = column([options.into()])
750 .bg(Role::Surface)
751 .radius(8.0)
752 .padding(4.0)
753 .shadow(SHADOW);
754 let mut menu = popup(list).on_dismiss(set(false));
756 menu.closing = !open;
757 menu.slide = Some((0.0, -1.0));
758 menu
759 };
760 column([field.into(), menu.into()]).align(AlignItems::FLEX_START)
761 })
762 .into()
763 }
764}
765
766#[cfg(test)]
767mod tests {
768 use super::*;
769
770 #[test]
771 fn closing_a_snackbar_pulls_the_queue_forward() {
772 let now = task::now();
773 let s = Duration::from_secs;
774 let timed = |key, from, until| Entry {
775 key,
776 build: Rc::new(|_| snackbar("")),
777 closing: false,
778 from: Some(now + s(from)),
779 until: Some(now + s(until)),
780 };
781 let mut entries = [timed(0, 0, 1), timed(1, 5, 10), timed(2, 10, 15)];
784 requeue(&mut entries, now);
785 let at = |e: &Entry| (e.from.unwrap() - now, e.until.unwrap() - now);
786 assert_eq!(at(&entries[1]), (s(1), s(6)));
787 assert_eq!(at(&entries[2]), (s(6), s(11)));
788 }
789}