BlueGit

ict rusty-teams

Files

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

elements.rs

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