label.rs

  1use crate::{
  2    fonts::TextStyle,
  3    geometry::{
  4        rect::RectF,
  5        vector::{vec2f, Vector2F},
  6    },
  7    json::{ToJson, Value},
  8    text_layout::{Line, RunStyle},
  9    DebugContext, Element, Event, EventContext, LayoutContext, PaintContext, SizeConstraint,
 10};
 11use serde::Deserialize;
 12use serde_json::json;
 13use smallvec::{smallvec, SmallVec};
 14
 15pub struct Label {
 16    text: String,
 17    style: LabelStyle,
 18    highlight_indices: Vec<usize>,
 19}
 20
 21#[derive(Clone, Debug, Deserialize)]
 22pub struct LabelStyle {
 23    pub text: TextStyle,
 24    pub highlight_text: Option<TextStyle>,
 25}
 26
 27impl From<TextStyle> for LabelStyle {
 28    fn from(text: TextStyle) -> Self {
 29        LabelStyle {
 30            text,
 31            highlight_text: None,
 32        }
 33    }
 34}
 35
 36impl Label {
 37    pub fn new(text: String, style: impl Into<LabelStyle>) -> Self {
 38        Self {
 39            text,
 40            highlight_indices: Default::default(),
 41            style: style.into(),
 42        }
 43    }
 44
 45    pub fn with_highlights(mut self, indices: Vec<usize>) -> Self {
 46        self.highlight_indices = indices;
 47        self
 48    }
 49
 50    fn compute_runs(&self) -> SmallVec<[(usize, RunStyle); 8]> {
 51        let font_id = self.style.text.font_id;
 52        if self.highlight_indices.is_empty() {
 53            return smallvec![(
 54                self.text.len(),
 55                RunStyle {
 56                    font_id,
 57                    color: self.style.text.color,
 58                    underline: self.style.text.underline,
 59                }
 60            )];
 61        }
 62
 63        let highlight_font_id = self
 64            .style
 65            .highlight_text
 66            .as_ref()
 67            .map_or(font_id, |style| style.font_id);
 68
 69        let mut highlight_indices = self.highlight_indices.iter().copied().peekable();
 70        let mut runs = SmallVec::new();
 71        let highlight_style = self
 72            .style
 73            .highlight_text
 74            .as_ref()
 75            .unwrap_or(&self.style.text);
 76
 77        for (char_ix, c) in self.text.char_indices() {
 78            let mut font_id = font_id;
 79            let mut color = self.style.text.color;
 80            let mut underline = self.style.text.underline;
 81            if let Some(highlight_ix) = highlight_indices.peek() {
 82                if char_ix == *highlight_ix {
 83                    font_id = highlight_font_id;
 84                    color = highlight_style.color;
 85                    underline = highlight_style.underline;
 86                    highlight_indices.next();
 87                }
 88            }
 89
 90            let last_run: Option<&mut (usize, RunStyle)> = runs.last_mut();
 91            let push_new_run = if let Some((last_len, last_style)) = last_run {
 92                if font_id == last_style.font_id
 93                    && color == last_style.color
 94                    && underline == last_style.underline
 95                {
 96                    *last_len += c.len_utf8();
 97                    false
 98                } else {
 99                    true
100                }
101            } else {
102                true
103            };
104
105            if push_new_run {
106                runs.push((
107                    c.len_utf8(),
108                    RunStyle {
109                        font_id,
110                        color,
111                        underline,
112                    },
113                ));
114            }
115        }
116
117        runs
118    }
119}
120
121impl Element for Label {
122    type LayoutState = Line;
123    type PaintState = ();
124
125    fn layout(
126        &mut self,
127        constraint: SizeConstraint,
128        cx: &mut LayoutContext,
129    ) -> (Vector2F, Self::LayoutState) {
130        let runs = self.compute_runs();
131        let line = cx.text_layout_cache.layout_str(
132            self.text.as_str(),
133            self.style.text.font_size,
134            runs.as_slice(),
135        );
136
137        let size = vec2f(
138            line.width().max(constraint.min.x()).min(constraint.max.x()),
139            cx.font_cache
140                .line_height(self.style.text.font_id, self.style.text.font_size)
141                .ceil(),
142        );
143
144        (size, line)
145    }
146
147    fn paint(
148        &mut self,
149        bounds: RectF,
150        visible_bounds: RectF,
151        line: &mut Self::LayoutState,
152        cx: &mut PaintContext,
153    ) -> Self::PaintState {
154        line.paint(bounds.origin(), visible_bounds, bounds.size().y(), cx)
155    }
156
157    fn dispatch_event(
158        &mut self,
159        _: &Event,
160        _: RectF,
161        _: &mut Self::LayoutState,
162        _: &mut Self::PaintState,
163        _: &mut EventContext,
164    ) -> bool {
165        false
166    }
167
168    fn debug(
169        &self,
170        bounds: RectF,
171        _: &Self::LayoutState,
172        _: &Self::PaintState,
173        _: &DebugContext,
174    ) -> Value {
175        json!({
176            "type": "Label",
177            "bounds": bounds.to_json(),
178            "text": &self.text,
179            "highlight_indices": self.highlight_indices,
180            "style": self.style.to_json(),
181        })
182    }
183}
184
185impl ToJson for LabelStyle {
186    fn to_json(&self) -> Value {
187        json!({
188            "text": self.text.to_json(),
189            "highlight_text": self.highlight_text
190                .as_ref()
191                .map_or(serde_json::Value::Null, |style| style.to_json())
192        })
193    }
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199    use crate::color::Color;
200    use crate::fonts::{Properties as FontProperties, Weight};
201
202    #[crate::test(self)]
203    fn test_layout_label_with_highlights(cx: &mut crate::MutableAppContext) {
204        let default_style = TextStyle::new(
205            "Menlo",
206            12.,
207            Default::default(),
208            false,
209            Color::black(),
210            cx.font_cache(),
211        )
212        .unwrap();
213        let highlight_style = TextStyle::new(
214            "Menlo",
215            12.,
216            *FontProperties::new().weight(Weight::BOLD),
217            false,
218            Color::new(255, 0, 0, 255),
219            cx.font_cache(),
220        )
221        .unwrap();
222        let label = Label::new(
223            ".αβγδε.ⓐⓑⓒⓓⓔ.abcde.".to_string(),
224            LabelStyle {
225                text: default_style.clone(),
226                highlight_text: Some(highlight_style.clone()),
227            },
228        )
229        .with_highlights(vec![
230            "".len(),
231            ".αβ".len(),
232            ".αβγδ".len(),
233            ".αβγδε.ⓐ".len(),
234            ".αβγδε.ⓐⓑ".len(),
235        ]);
236
237        let default_run_style = RunStyle {
238            font_id: default_style.font_id,
239            color: default_style.color,
240            underline: default_style.underline,
241        };
242        let highlight_run_style = RunStyle {
243            font_id: highlight_style.font_id,
244            color: highlight_style.color,
245            underline: highlight_style.underline,
246        };
247        let runs = label.compute_runs();
248        assert_eq!(
249            runs.as_slice(),
250            &[
251                ("".len(), default_run_style),
252                ("βγ".len(), highlight_run_style),
253                ("δ".len(), default_run_style),
254                ("ε".len(), highlight_run_style),
255                (".ⓐ".len(), default_run_style),
256                ("ⓑⓒ".len(), highlight_run_style),
257                ("ⓓⓔ.abcde.".len(), default_run_style),
258            ]
259        );
260    }
261}