traffic_lights.rs

 1use crate::prelude::*;
 2
 3#[derive(Clone, Copy)]
 4enum TrafficLightColor {
 5    Red,
 6    Yellow,
 7    Green,
 8}
 9
10#[derive(Component)]
11struct TrafficLight {
12    color: TrafficLightColor,
13    window_has_focus: bool,
14}
15
16impl TrafficLight {
17    fn new(color: TrafficLightColor, window_has_focus: bool) -> Self {
18        Self {
19            color,
20            window_has_focus,
21        }
22    }
23
24    fn render<V: 'static>(self, _view: &mut V, cx: &mut ViewContext<V>) -> impl Component<V> {
25        let theme = theme(cx);
26
27        let fill = match (self.window_has_focus, self.color) {
28            (true, TrafficLightColor::Red) => theme.mac_os_traffic_light_red,
29            (true, TrafficLightColor::Yellow) => theme.mac_os_traffic_light_yellow,
30            (true, TrafficLightColor::Green) => theme.mac_os_traffic_light_green,
31            (false, _) => theme.filled_element,
32        };
33
34        div().w_3().h_3().rounded_full().bg(fill)
35    }
36}
37
38#[derive(Component)]
39pub struct TrafficLights {
40    window_has_focus: bool,
41}
42
43impl TrafficLights {
44    pub fn new() -> Self {
45        Self {
46            window_has_focus: true,
47        }
48    }
49
50    pub fn window_has_focus(mut self, window_has_focus: bool) -> Self {
51        self.window_has_focus = window_has_focus;
52        self
53    }
54
55    fn render<V: 'static>(self, _view: &mut V, cx: &mut ViewContext<V>) -> impl Component<V> {
56        div()
57            .flex()
58            .items_center()
59            .gap_2()
60            .child(TrafficLight::new(
61                TrafficLightColor::Red,
62                self.window_has_focus,
63            ))
64            .child(TrafficLight::new(
65                TrafficLightColor::Yellow,
66                self.window_has_focus,
67            ))
68            .child(TrafficLight::new(
69                TrafficLightColor::Green,
70                self.window_has_focus,
71            ))
72    }
73}
74
75#[cfg(feature = "stories")]
76pub use stories::*;
77
78#[cfg(feature = "stories")]
79mod stories {
80    use crate::Story;
81
82    use super::*;
83
84    #[derive(Component)]
85    pub struct TrafficLightsStory;
86
87    impl TrafficLightsStory {
88        fn render<V: 'static>(self, _view: &mut V, cx: &mut ViewContext<V>) -> impl Component<V> {
89            Story::container(cx)
90                .child(Story::title_for::<_, TrafficLights>(cx))
91                .child(Story::label(cx, "Default"))
92                .child(TrafficLights::new())
93                .child(Story::label(cx, "Unfocused"))
94                .child(TrafficLights::new().window_has_focus(false))
95        }
96    }
97}