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 system_colors = &cx.theme().styles.system;
 26
 27        let fill = match (self.window_has_focus, self.color) {
 28            (true, TrafficLightColor::Red) => system_colors.mac_os_traffic_light_red,
 29            (true, TrafficLightColor::Yellow) => system_colors.mac_os_traffic_light_yellow,
 30            (true, TrafficLightColor::Green) => system_colors.mac_os_traffic_light_green,
 31            (false, _) => cx.theme().colors().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 gpui2::{Div, Render};
 81
 82    use crate::Story;
 83
 84    use super::*;
 85
 86    pub struct TrafficLightsStory;
 87
 88    impl Render for TrafficLightsStory {
 89        type Element = Div<Self>;
 90
 91        fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
 92            Story::container(cx)
 93                .child(Story::title_for::<_, TrafficLights>(cx))
 94                .child(Story::label(cx, "Default"))
 95                .child(TrafficLights::new())
 96                .child(Story::label(cx, "Unfocused"))
 97                .child(TrafficLights::new().window_has_focus(false))
 98        }
 99    }
100}