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