BlueGit

ict rusty-teams

Files

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

elements.rs

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