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 );
142
143 (size, line)
144 }
145
146 fn paint(
147 &mut self,
148 bounds: RectF,
149 visible_bounds: RectF,
150 line: &mut Self::LayoutState,
151 cx: &mut PaintContext,
152 ) -> Self::PaintState {
153 line.paint(bounds.origin(), visible_bounds, bounds.size().y(), cx)
154 }
155
156 fn dispatch_event(
157 &mut self,
158 _: &Event,
159 _: RectF,
160 _: &mut Self::LayoutState,
161 _: &mut Self::PaintState,
162 _: &mut EventContext,
163 ) -> bool {
164 false
165 }
166
167 fn debug(
168 &self,
169 bounds: RectF,
170 _: &Self::LayoutState,
171 _: &Self::PaintState,
172 _: &DebugContext,
173 ) -> Value {
174 json!({
175 "type": "Label",
176 "bounds": bounds.to_json(),
177 "text": &self.text,
178 "highlight_indices": self.highlight_indices,
179 "style": self.style.to_json(),
180 })
181 }
182}
183
184impl ToJson for LabelStyle {
185 fn to_json(&self) -> Value {
186 json!({
187 "text": self.text.to_json(),
188 "highlight_text": self.highlight_text
189 .as_ref()
190 .map_or(serde_json::Value::Null, |style| style.to_json())
191 })
192 }
193}
194
195#[cfg(test)]
196mod tests {
197 use super::*;
198 use crate::color::Color;
199 use crate::fonts::{Properties as FontProperties, Weight};
200
201 #[crate::test(self)]
202 fn test_layout_label_with_highlights(cx: &mut crate::MutableAppContext) {
203 let default_style = TextStyle::new(
204 "Menlo",
205 12.,
206 Default::default(),
207 false,
208 Color::black(),
209 cx.font_cache(),
210 )
211 .unwrap();
212 let highlight_style = TextStyle::new(
213 "Menlo",
214 12.,
215 *FontProperties::new().weight(Weight::BOLD),
216 false,
217 Color::new(255, 0, 0, 255),
218 cx.font_cache(),
219 )
220 .unwrap();
221 let label = Label::new(
222 ".αβγδε.ⓐⓑⓒⓓⓔ.abcde.".to_string(),
223 LabelStyle {
224 text: default_style.clone(),
225 highlight_text: Some(highlight_style.clone()),
226 },
227 )
228 .with_highlights(vec![
229 ".α".len(),
230 ".αβ".len(),
231 ".αβγδ".len(),
232 ".αβγδε.ⓐ".len(),
233 ".αβγδε.ⓐⓑ".len(),
234 ]);
235
236 let default_run_style = RunStyle {
237 font_id: default_style.font_id,
238 color: default_style.color,
239 underline: default_style.underline,
240 };
241 let highlight_run_style = RunStyle {
242 font_id: highlight_style.font_id,
243 color: highlight_style.color,
244 underline: highlight_style.underline,
245 };
246 let runs = label.compute_runs();
247 assert_eq!(
248 runs.as_slice(),
249 &[
250 (".α".len(), default_run_style),
251 ("βγ".len(), highlight_run_style),
252 ("δ".len(), default_run_style),
253 ("ε".len(), highlight_run_style),
254 (".ⓐ".len(), default_run_style),
255 ("ⓑⓒ".len(), highlight_run_style),
256 ("ⓓⓔ.abcde.".len(), default_run_style),
257 ]
258 );
259 }
260}