BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / render / elements.rs

elements.rs

elements.rs 13.7 KiB Download Raw
1use gpui_kit::component::{h_flex, v_flex};
2use gpui_kit::prelude::FluentBuilder as _;
3use gpui_kit::*;
4
5use super::blocks::{Block, Inline, StyleFlags};
6use super::selectable::{Pill, SelectableRichText};
7use super::syntax::{self, Token};
8use crate::theme;
9use crate::views::widgets::symbol;
10
11const LIST_GAP: f32 = 2.;
12const MARKER_WIDTH: f32 = 18.;
13const WIDE_MARKER_WIDTH: f32 = 26.;
14const BULLETS: [&str; 3] = ["\u{2022}", "\u{25e6}", "\u{25aa}"];
15const CODE_HEADER_MIN_LINES: usize = 3;
16const PLAIN_LANGUAGE: &str = "text";
17const MIN_CONTRAST: f32 = 4.5;
18const HIGHLIGHT_ALPHA: f32 = 0.3;
19
20pub fn render_blocks(blocks: &[Block], id: &str, own: bool, cx: &App) -> AnyElement {
21 render_block_list(blocks, id, own, 0, cx)
22}
23
24fn render_block_list(blocks: &[Block], id: &str, own: bool, depth: usize, cx: &App) -> AnyElement {
25 v_flex()
26 .w_full()
27 .gap(px(6.))
28 .children(
29 blocks
30 .iter()
31 .enumerate()
32 .map(|(index, block)| render_block(block, format!("{id}-{index}"), own, depth, cx)),
33 )
34 .into_any_element()
35}
36
37fn render_block(block: &Block, id: String, own: bool, depth: usize, cx: &App) -> AnyElement {
38 match block {
39 Block::Paragraph(inline) => render_inline(inline, id, own, cx),
40 Block::Heading { level, inline } => div()
41 .w_full()
42 .text_size(px(heading_size(*level)))
43 .line_height(relative(1.3))
44 .font_weight(FontWeight::BOLD)
45 .child(render_inline(inline, id, own, cx))
46 .into_any_element(),
47 Block::Code { language, code } => render_code(language.as_deref(), code, id, own, cx),
48 Block::Reply(children) => div()
49 .w_full()
50 .px(px(8.))
51 .py(px(3.))
52 .border_l(px(3.))
53 .border_color(theme::accent())
54 .text_size(px(12.5))
55 .text_color(theme::text_muted())
56 .child(render_block_list(children, &id, own, depth, cx))
57 .into_any_element(),
58 Block::Quote(children) => div()
59 .w_full()
60 .px(px(8.))
61 .py(px(2.))
62 .border_l(px(3.))
63 .border_color(theme::border_strong())
64 .text_color(theme::text_soft())
65 .child(render_block_list(children, &id, own, depth, cx))
66 .into_any_element(),
67 Block::List {
68 ordered,
69 start,
70 items,
71 } => render_list(*ordered, *start, items, &id, own, depth, cx),
72 Block::Image { .. } => div().into_any_element(),
73 Block::Table { header, rows } => render_table(*header, rows, &id, own, cx),
74 Block::Rule => div()
75 .w_full()
76 .h(px(1.))
77 .my(px(2.))
78 .bg(theme::rule(own))
79 .into_any_element(),
80 }
81}
82
83fn heading_size(level: u8) -> f32 {
84 match level {
85 1 => 18.,
86 2 => 16.,
87 _ => 14.,
88 }
89}
90
91fn render_code(language: Option<&str>, code: &str, id: String, own: bool, cx: &App) -> AnyElement {
92 let highlights = language
93 .and_then(|language| syntax::highlight(code, language))
94 .unwrap_or_default()
95 .into_iter()
96 .map(|(range, token)| (range, token_style(token)))
97 .collect();
98 let body = div()
99 .w_full()
100 .px(px(10.))
101 .py(px(8.))
102 .child(SelectableRichText::new(
103 ElementId::Name(id.clone().into()),
104 code.to_owned(),
105 highlights,
106 ));
107 let show_header = language.is_some() || code.lines().count() >= CODE_HEADER_MIN_LINES;
108 v_flex()
109 .w_full()
110 .rounded(px(8.))
111 .overflow_hidden()
112 .bg(theme::code_surface())
113 .text_color(theme::text_strong())
114 .font_family(code_font(cx))
115 .text_size(px(12.5))
116 .line_height(relative(1.5))
117 .when(show_header, |container| {
118 container.child(code_header(
119 language.unwrap_or(PLAIN_LANGUAGE),
120 code,
121 &id,
122 own,
123 ))
124 })
125 .child(body)
126 .into_any_element()
127}
128
129fn code_header(language: &str, code: &str, id: &str, own: bool) -> Div {
130 let muted = if own {
131 theme::own_meta()
132 } else {
133 theme::text_muted()
134 };
135 let code = code.to_owned();
136 h_flex()
137 .w_full()
138 .h(px(26.))
139 .pl(px(10.))
140 .pr(px(6.))
141 .justify_between()
142 .items_center()
143 .border_b_1()
144 .border_color(theme::code_header_border())
145 .font_family(theme::font_family())
146 .text_size(px(11.))
147 .text_color(muted)
148 .child(language.to_owned())
149 .child(
150 h_flex()
151 .id(ElementId::Name(format!("{id}-copy").into()))
152 .h(px(20.))
153 .px(px(6.))
154 .gap(px(4.))
155 .items_center()
156 .rounded(px(4.))
157 .cursor_pointer()
158 .hover(|button| button.bg(theme::inline_code_fill(false)))
159 .on_click(move |_, _, cx| {
160 cx.write_to_clipboard(ClipboardItem::new_string(code.clone()))
161 })
162 .child(symbol("content_copy", 13., muted))
163 .child("Copy"),
164 )
165}
166
167fn token_style(token: Token) -> HighlightStyle {
168 match token {
169 Token::Keyword => HighlightStyle {
170 color: Some(theme::accent_text()),
171 ..Default::default()
172 },
173 Token::String | Token::Number => HighlightStyle {
174 color: Some(theme::accent_soft()),
175 ..Default::default()
176 },
177 Token::Comment => HighlightStyle {
178 color: Some(theme::text_faint()),
179 font_style: Some(FontStyle::Italic),
180 ..Default::default()
181 },
182 }
183}
184
185fn render_list(
186 ordered: bool,
187 start: u32,
188 items: &[Vec<Block>],
189 id: &str,
190 own: bool,
191 depth: usize,
192 cx: &App,
193) -> AnyElement {
194 let last_number = start as usize + items.len().saturating_sub(1);
195 let marker_width = if ordered && last_number >= 10 {
196 WIDE_MARKER_WIDTH
197 } else {
198 MARKER_WIDTH
199 };
200 let marker_color = if own {
201 theme::own_meta()
202 } else {
203 theme::text_muted()
204 };
205 v_flex()
206 .w_full()
207 .gap(px(LIST_GAP))
208 .children(items.iter().enumerate().map(|(index, item)| {
209 let marker = if ordered {
210 format!("{}.", start as usize + index)
211 } else {
212 BULLETS[depth.min(BULLETS.len() - 1)].to_owned()
213 };
214 h_flex()
215 .w_full()
216 .items_start()
217 .child(
218 div()
219 .flex_none()
220 .w(px(marker_width))
221 .when(ordered, |marker| marker.pr(px(4.)).text_right())
222 .text_color(marker_color)
223 .child(marker),
224 )
225 .child(div().flex_1().min_w_0().child(render_list_item(
226 item,
227 &format!("{id}-{index}"),
228 own,
229 depth + 1,
230 cx,
231 )))
232 }))
233 .into_any_element()
234}
235
236fn render_list_item(blocks: &[Block], id: &str, own: bool, depth: usize, cx: &App) -> AnyElement {
237 v_flex()
238 .w_full()
239 .gap(px(LIST_GAP))
240 .children(
241 blocks
242 .iter()
243 .enumerate()
244 .map(|(index, block)| render_block(block, format!("{id}-{index}"), own, depth, cx)),
245 )
246 .into_any_element()
247}
248
249fn render_table(header: bool, rows: &[Vec<Inline>], id: &str, own: bool, cx: &App) -> AnyElement {
250 let columns = rows.iter().map(Vec::len).max().unwrap_or(0);
251 v_flex()
252 .w_full()
253 .border_t_1()
254 .border_l_1()
255 .border_color(theme::border_strong())
256 .text_size(px(13.))
257 .children(rows.iter().enumerate().map(|(row_index, row)| {
258 let is_header = header && row_index == 0;
259 h_flex()
260 .w_full()
261 .items_stretch()
262 .when(is_header, |line| {
263 line.bg(theme::table_header())
264 .font_weight(FontWeight::SEMIBOLD)
265 .text_color(theme::text_strong())
266 })
267 .children((0..columns).map(|column| {
268 let cell = div()
269 .flex_1()
270 .min_w_0()
271 .px(px(8.))
272 .py(px(4.))
273 .border_r_1()
274 .border_b_1()
275 .border_color(theme::border_strong());
276 match row.get(column) {
277 Some(inline) => cell.child(render_inline(
278 inline,
279 format!("{id}-{row_index}-{column}"),
280 own,
281 cx,
282 )),
283 None => cell,
284 }
285 }))
286 }))
287 .into_any_element()
288}
289
290fn code_font(cx: &App) -> SharedString {
291 use gpui_kit::component::ActiveTheme as _;
292 cx.theme().mono_font_family.clone()
293}
294
295fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement {
296 let highlights = inline
297 .segments
298 .iter()
299 .filter(|segment| !segment.style.is_plain())
300 .map(|segment| (segment.range.clone(), highlight_for(segment.style, own)))
301 .collect::<Vec<_>>();
302 let mono = code_font(cx);
303 let font_overrides = inline
304 .segments
305 .iter()
306 .filter(|segment| segment.style.code)
307 .map(|segment| (segment.range.clone(), mono.clone()))
308 .collect();
309 let pills = inline
310 .segments
311 .iter()
312 .filter_map(|segment| pill_for(segment.range.clone(), segment.style, own))
313 .collect();
314 div()
315 .w_full()
316 .text_color(theme::text())
317 .child(
318 SelectableRichText::new(ElementId::Name(id.into()), inline.text.clone(), highlights)
319 .links(inline.links())
320 .font_overrides(font_overrides)
321 .pills(pills),
322 )
323 .into_any_element()
324}
325
326fn pill_for(range: std::ops::Range<usize>, style: StyleFlags, own: bool) -> Option<Pill> {
327 if style.code {
328 return Some(Pill {
329 range,
330 fill: theme::inline_code_fill(own),
331 border: Some(theme::inline_code_border()),
332 radius: px(4.),
333 });
334 }
335 let background = style.background?;
336 let mut fill: Hsla = rgb(background).into();
337 fill.a = HIGHLIGHT_ALPHA;
338 Some(Pill {
339 range,
340 fill,
341 border: None,
342 radius: px(3.),
343 })
344}
345
346fn highlight_for(style: StyleFlags, own: bool) -> HighlightStyle {
347 let mut highlight = HighlightStyle::default();
348 if style.bold {
349 highlight.font_weight = Some(FontWeight::BOLD);
350 }
351 if style.italic {
352 highlight.font_style = Some(FontStyle::Italic);
353 }
354 if let Some(color) = style.color {
355 highlight.color = Some(readable(color, own));
356 }
357 if style.code {
358 highlight.color = Some(if own {
359 theme::accent_soft()
360 } else {
361 theme::text_strong()
362 });
363 }
364 if style.underline {
365 highlight.underline = Some(UnderlineStyle {
366 thickness: px(1.),
367 color: None,
368 wavy: false,
369 });
370 }
371 if style.strike {
372 highlight.color = Some(if own {
373 theme::own_meta()
374 } else {
375 theme::text_muted()
376 });
377 highlight.strikethrough = Some(StrikethroughStyle {
378 thickness: px(1.),
379 color: None,
380 });
381 }
382 let accent = if own {
383 theme::accent_soft()
384 } else {
385 theme::accent_text()
386 };
387 if style.mention {
388 highlight.font_weight = Some(FontWeight::BOLD);
389 highlight.color = Some(accent);
390 }
391 if style.link {
392 highlight.color = Some(accent);
393 highlight.underline = Some(UnderlineStyle {
394 thickness: px(1.),
395 color: Some(accent),
396 wavy: false,
397 });
398 }
399 highlight
400}
401
402fn readable(color: u32, own: bool) -> Hsla {
403 let background = Rgba::from(if own {
404 theme::bubble_own()
405 } else {
406 theme::bubble_other()
407 });
408 let mut foreground = rgb(color);
409 for _ in 0..10 {
410 if contrast(foreground, background) >= MIN_CONTRAST {
411 break;
412 }
413 foreground = Rgba {
414 r: foreground.r + (1. - foreground.r) * 0.2,
415 g: foreground.g + (1. - foreground.g) * 0.2,
416 b: foreground.b + (1. - foreground.b) * 0.2,
417 a: 1.,
418 };
419 }
420 foreground.into()
421}
422
423fn contrast(first: Rgba, second: Rgba) -> f32 {
424 let (lighter, darker) = {
425 let (a, b) = (luminance(first), luminance(second));
426 if a > b { (a, b) } else { (b, a) }
427 };
428 (lighter + 0.05) / (darker + 0.05)
429}
430
431fn luminance(color: Rgba) -> f32 {
432 let channel = |value: f32| {
433 if value <= 0.03928 {
434 value / 12.92
435 } else {
436 ((value + 0.055) / 1.055).powf(2.4)
437 }
438 };
439 0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b)
440}
441
442#[cfg(test)]
443mod tests {
444 use gpui_kit::{Rgba, rgb};
445
446 use super::{MIN_CONTRAST, contrast, readable};
447 use crate::theme;
448
449 #[test]
450 fn dark_text_color_is_lifted_to_readable_contrast() {
451 let lifted = Rgba::from(readable(0x000080, false));
452 assert!(contrast(lifted, Rgba::from(theme::bubble_other())) >= MIN_CONTRAST);
453 }
454
455 #[test]
456 fn light_text_color_stays_as_sent() {
457 assert_eq!(Rgba::from(readable(0xffd700, false)), rgb(0xffd700));
458 }
459}