1use crate::{
2 element::{AnyElement, Element, IntoElement, Layout, ParentElement},
3 interactive::{InteractionHandlers, Interactive},
4 layout_context::LayoutContext,
5 paint_context::PaintContext,
6 style::{Style, StyleHelpers, Styleable},
7};
8use anyhow::Result;
9use gpui::{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 LayoutContext<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 layout: &Layout,
60 paint_state: &mut Self::PaintState,
61 cx: &mut PaintContext<V>,
62 ) where
63 Self: Sized,
64 {
65 let slot = self.cascade_slot;
66 let style = self.pressed.get().then_some(self.pressed_style.clone());
67 self.style_cascade().set(slot, style);
68
69 let pressed = self.pressed.clone();
70 let bounds = layout.bounds;
71 cx.on_event(layout.order, move |_view, event: &MouseButtonEvent, cx| {
72 if event.is_down {
73 if bounds.contains_point(event.position) {
74 pressed.set(true);
75 cx.repaint();
76 }
77 } else if pressed.get() {
78 pressed.set(false);
79 cx.repaint();
80 }
81 });
82
83 self.child.paint(view, layout, paint_state, cx);
84 }
85}
86
87impl<E: Styleable<Style = Style>> StyleHelpers for Pressable<E> {}
88
89impl<V: 'static, E: Interactive<V> + Styleable> Interactive<V> for Pressable<E> {
90 fn interaction_handlers(&mut self) -> &mut InteractionHandlers<V> {
91 self.child.interaction_handlers()
92 }
93}
94
95impl<V: 'static, E: ParentElement<V> + Styleable> ParentElement<V> for Pressable<E> {
96 fn children_mut(&mut self) -> &mut SmallVec<[AnyElement<V>; 2]> {
97 self.child.children_mut()
98 }
99}
100
101impl<V: 'static, E: Element<V> + Styleable> IntoElement<V> for Pressable<E> {
102 type Element = Self;
103
104 fn into_element(self) -> Self::Element {
105 self
106 }
107}