keystroke_label.rs

  1use crate::{
  2    elements::*,
  3    fonts::TextStyle,
  4    geometry::{rect::RectF, vector::Vector2F},
  5    Action, ElementBox, LayoutContext, PaintContext, SizeConstraint,
  6};
  7use serde_json::json;
  8
  9use super::ContainerStyle;
 10
 11pub struct KeystrokeLabel {
 12    action: Box<dyn Action>,
 13    container_style: ContainerStyle,
 14    text_style: TextStyle,
 15    window_id: usize,
 16    view_id: usize,
 17}
 18
 19impl KeystrokeLabel {
 20    pub fn new(
 21        window_id: usize,
 22        view_id: usize,
 23        action: Box<dyn Action>,
 24        container_style: ContainerStyle,
 25        text_style: TextStyle,
 26    ) -> Self {
 27        Self {
 28            window_id,
 29            view_id,
 30            action,
 31            container_style,
 32            text_style,
 33        }
 34    }
 35}
 36
 37impl Element for KeystrokeLabel {
 38    type LayoutState = ElementBox;
 39    type PaintState = ();
 40
 41    fn layout(
 42        &mut self,
 43        constraint: SizeConstraint,
 44        cx: &mut LayoutContext,
 45    ) -> (Vector2F, ElementBox) {
 46        let mut element = if let Some(keystrokes) =
 47            cx.app
 48                .keystrokes_for_action(self.window_id, self.view_id, self.action.as_ref())
 49        {
 50            Flex::row()
 51                .with_children(keystrokes.iter().map(|keystroke| {
 52                    Label::new(keystroke.to_string(), self.text_style.clone())
 53                        .contained()
 54                        .with_style(self.container_style)
 55                        .boxed()
 56                }))
 57                .boxed()
 58        } else {
 59            Empty::new().collapsed().boxed()
 60        };
 61
 62        let size = element.layout(constraint, cx);
 63        (size, element)
 64    }
 65
 66    fn paint(
 67        &mut self,
 68        bounds: RectF,
 69        visible_bounds: RectF,
 70        element: &mut ElementBox,
 71        cx: &mut PaintContext,
 72    ) {
 73        element.paint(bounds.origin(), visible_bounds, cx);
 74    }
 75
 76    fn rect_for_text_range(
 77        &self,
 78        _: Range<usize>,
 79        _: RectF,
 80        _: RectF,
 81        _: &Self::LayoutState,
 82        _: &Self::PaintState,
 83        _: &MeasurementContext,
 84    ) -> Option<RectF> {
 85        None
 86    }
 87
 88    fn debug(
 89        &self,
 90        _: RectF,
 91        element: &ElementBox,
 92        _: &(),
 93        cx: &crate::DebugContext,
 94    ) -> serde_json::Value {
 95        json!({
 96            "type": "KeystrokeLabel",
 97            "action": self.action.name(),
 98            "child": element.debug(cx)
 99        })
100    }
101}