1use crate::{
2 element::{AnyElement, Element, IntoElement, Layout, ParentElement},
3 interactive::{InteractionHandlers, Interactive},
4 paint_context::PaintContext,
5 style::{Style, StyleHelpers, Styleable},
6 ViewContext,
7};
8use anyhow::Result;
9use gpui::{geometry::vector::Vector2F, platform::MouseButtonEvent, LayoutId};
10use refineable::{CascadeSlot, Refineable, RefinementCascade};
11use smallvec::SmallVec;
12use std::{cell::Cell, rc::Rc};
13
14pub struct Pressable<E: Styleable> {
15 pressed: Rc<Cell<bool>>,
16 pressed_style: <E::Style as Refineable>::Refinement,
17 cascade_slot: CascadeSlot,
18 child: E,
19}
20
21pub fn pressable<E: Styleable>(mut child: E) -> Pressable<E> {
22 Pressable {
23 pressed: Rc::new(Cell::new(false)),
24 pressed_style: Default::default(),
25 cascade_slot: child.style_cascade().reserve(),
26 child,
27 }
28}
29
30impl<E: Styleable> Styleable for Pressable<E> {
31 type Style = E::Style;
32
33 fn declared_style(&mut self) -> &mut <Self::Style as Refineable>::Refinement {
34 &mut self.pressed_style
35 }
36
37 fn style_cascade(&mut self) -> &mut RefinementCascade<E::Style> {
38 self.child.style_cascade()
39 }
40}
41
42impl<V: 'static, E: Element<V> + Styleable> Element<V> for Pressable<E> {
43 type PaintState = E::PaintState;
44
45 fn layout(
46 &mut self,
47 view: &mut V,
48 cx: &mut ViewContext<V>,
49 ) -> Result<(LayoutId, Self::PaintState)>
50 where
51 Self: Sized,
52 {
53 self.child.layout(view, cx)
54 }
55
56 fn paint(
57 &mut self,
58 view: &mut V,
59 parent_origin: Vector2F,
60 layout: &Layout,
61 paint_state: &mut Self::PaintState,
62 cx: &mut PaintContext<V>,
63 ) where
64 Self: Sized,
65 {
66 let slot = self.cascade_slot;
67 let style = self.pressed.get().then_some(self.pressed_style.clone());
68 self.style_cascade().set(slot, style);
69
70 let pressed = self.pressed.clone();
71 let bounds = layout.bounds + parent_origin;
72 cx.on_event(layout.order, move |_view, event: &MouseButtonEvent, cx| {
73 if event.is_down {
74 if bounds.contains_point(event.position) {
75 pressed.set(true);
76 cx.repaint();
77 }
78 } else if pressed.get() {
79 pressed.set(false);
80 cx.repaint();
81 }
82 });
83
84 self.child
85 .paint(view, parent_origin, layout, paint_state, cx);
86 }
87}
88
89impl<E: Styleable<Style = Style>> StyleHelpers for Pressable<E> {}
90
91impl<V: 'static, E: Interactive<V> + Styleable> Interactive<V> for Pressable<E> {
92 fn interaction_handlers(&mut self) -> &mut InteractionHandlers<V> {
93 self.child.interaction_handlers()
94 }
95}
96
97impl<V: 'static, E: ParentElement<V> + Styleable> ParentElement<V> for Pressable<E> {
98 fn children_mut(&mut self) -> &mut SmallVec<[AnyElement<V>; 2]> {
99 self.child.children_mut()
100 }
101}
102
103impl<V: 'static, E: Element<V> + Styleable> IntoElement<V> for Pressable<E> {
104 type Element = Self;
105
106 fn into_element(self) -> Self::Element {
107 self
108 }
109}