BlueGit

ict rusty-teams

Files

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

elements.rs

elements.rs 22.6 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, TableCell};
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 INDENT_STEP: f32 = teams_core::INDENT_PIXELS as f32;
15const MARKER_WIDTH: f32 = 18.;
16const WIDE_MARKER_WIDTH: f32 = 26.;
17const BULLETS: [&str; 3] = ["\u{2022}", "\u{25e6}", "\u{25aa}"];
18const CODE_HEADER_MIN_LINES: usize = 3;
19const PLAIN_LANGUAGE: &str = "text";
20const MIN_CONTRAST: f32 = 4.5;
21const HIGHLIGHT_ALPHA: f32 = 0.3;
22const CODE_LINE_PADDING_X: f32 = 6.;
23const CODE_LINE_PADDING_Y: f32 = 4.;
24const CODE_LINE_RADIUS: f32 = 4.;
25pub const CODE_LINE_TAG: &str = "message/code-line";
26pub const CODE_BLOCK_TAG: &str = "message/code-block";
27
28pub fn render_blocks(blocks: &[Block], id: &str, own: bool, cx: &App) -> AnyElement {
29 render_block_list(blocks, id, own, 0, cx)
30}
31
32fn render_block_list(blocks: &[Block], id: &str, own: bool, depth: usize, cx: &App) -> AnyElement {
33 v_flex()
34 .w_full()
35 .gap(px(6.))
36 .children(
37 blocks
38 .iter()
39 .enumerate()
40 .map(|(index, block)| render_block(block, format!("{id}-{index}"), own, depth, cx)),
41 )
42 .into_any_element()
43}
44
45fn render_block(block: &Block, id: String, own: bool, depth: usize, cx: &App) -> AnyElement {
46 match block {
47 Block::Paragraph(inline) => render_inline(inline, id, own, cx),
48 Block::Heading { level, inline } => div()
49 .w_full()
50 .text_size(px(heading_size(*level)))
51 .line_height(relative(1.3))
52 .font_weight(FontWeight::BOLD)
53 .child(render_inline(inline, id, own, cx))
54 .into_any_element(),
55 Block::Code { language, code } => render_code(language.as_deref(), code, id, own, cx),
56 Block::CodeLine { code } => render_code_line(code, id, own, cx),
57 Block::Reply {
58 message_id,
59 children,
60 } => div()
61 .id(SharedString::from(format!("{id}-reply")))
62 .w_full()
63 .when_some(message_id.clone(), |quote, message_id| {
64 quote
65 .cursor_pointer()
66 .hover(|quote| quote.bg(theme::row_hover()))
67 .on_click(move |_, _, cx| {
68 cx.stop_propagation();
69 jump_to_quoted(message_id.clone(), cx);
70 })
71 })
72 .px(px(8.))
73 .py(px(3.))
74 .border_l(px(3.))
75 .border_color(theme::accent())
76 .rounded_r(px(4.))
77 .bg(theme::quote_fill())
78 .text_size(px(12.5))
79 .text_color(theme::text_muted())
80 .child(render_block_list(children, &id, own, depth, cx))
81 .into_any_element(),
82 Block::Quote(children) => div()
83 .w_full()
84 .px(px(8.))
85 .py(px(2.))
86 .border_l(px(3.))
87 .border_color(theme::border_strong())
88 .rounded_r(px(4.))
89 .bg(theme::quote_fill())
90 .text_color(theme::text_soft())
91 .child(render_block_list(children, &id, own, depth, cx))
92 .into_any_element(),
93 Block::Indent { level, children } => div()
94 .w_full()
95 .pl(px(f32::from(*level) * INDENT_STEP))
96 .child(render_block_list(children, &id, own, depth, cx))
97 .into_any_element(),
98 Block::List {
99 ordered,
100 start,
101 items,
102 } => render_list(*ordered, *start, items, &id, own, depth, cx),
103 Block::Image { .. } => div().into_any_element(),
104 Block::Table { header, rows } => render_table(*header, rows, &id, own, cx, &|_| None),
105 Block::Rule => div()
106 .w_full()
107 .h(px(1.))
108 .my(px(2.))
109 .bg(theme::rule(own))
110 .into_any_element(),
111 }
112}
113
114fn heading_size(level: u8) -> f32 {
115 match level {
116 1 => 18.,
117 2 => 16.,
118 _ => 14.,
119 }
120}
121
122fn render_code(language: Option<&str>, code: &str, id: String, own: bool, cx: &App) -> AnyElement {
123 let highlights = language
124 .and_then(|language| syntax::highlight(code, language))
125 .unwrap_or_default()
126 .into_iter()
127 .map(|(range, token)| (range, token_style(token)))
128 .collect();
129 let body = div()
130 .w_full()
131 .px(px(10.))
132 .py(px(8.))
133 .child(SelectableRichText::new(
134 ElementId::Name(id.clone().into()),
135 code.to_owned(),
136 highlights,
137 ));
138 let show_header = language.is_some() || code.lines().count() >= CODE_HEADER_MIN_LINES;
139 v_flex()
140 .debug_selector(|| CODE_BLOCK_TAG.into())
141 .w_full()
142 .rounded(px(8.))
143 .overflow_hidden()
144 .border_1()
145 .border_color(theme::code_frame())
146 .bg(theme::code_surface())
147 .text_color(theme::text_strong())
148 .font_family(code_font(cx))
149 .text_size(px(12.5))
150 .line_height(relative(1.5))
151 .when(show_header, |container| {
152 container.child(code_header(
153 language.unwrap_or(PLAIN_LANGUAGE),
154 code,
155 &id,
156 own,
157 ))
158 })
159 .child(body)
160 .into_any_element()
161}
162
163fn render_code_line(code: &str, id: String, own: bool, cx: &App) -> AnyElement {
164 h_flex()
165 .w_full()
166 .child(
167 div()
168 .debug_selector(|| CODE_LINE_TAG.into())
169 .min_w_0()
170 .flex_shrink(1.)
171 .px(px(CODE_LINE_PADDING_X))
172 .py(px(CODE_LINE_PADDING_Y))
173 .rounded(px(CODE_LINE_RADIUS))
174 .border_1()
175 .border_color(theme::code_frame())
176 .font_family(code_font(cx))
177 .text_size(px(12.5))
178 .line_height(relative(1.5))
179 .text_color(code_text(own))
180 .child(SelectableRichText::new(
181 ElementId::Name(id.into()),
182 code.to_owned(),
183 Vec::new(),
184 )),
185 )
186 .into_any_element()
187}
188
189fn code_text(own: bool) -> Hsla {
190 if own {
191 theme::accent_soft()
192 } else {
193 theme::red_soft()
194 }
195}
196
197fn code_header(language: &str, code: &str, id: &str, own: bool) -> Div {
198 let muted = if own {
199 theme::own_meta()
200 } else {
201 theme::text_muted()
202 };
203 let code = code.to_owned();
204 h_flex()
205 .w_full()
206 .h(px(26.))
207 .pl(px(10.))
208 .pr(px(6.))
209 .justify_between()
210 .items_center()
211 .font_family(theme::font_family())
212 .text_size(px(11.))
213 .text_color(muted)
214 .child(language.to_owned())
215 .child(
216 h_flex()
217 .id(ElementId::Name(format!("{id}-copy").into()))
218 .h(px(20.))
219 .px(px(6.))
220 .gap(px(4.))
221 .items_center()
222 .rounded(px(4.))
223 .cursor_pointer()
224 .hover(|button| button.bg(theme::inline_code_fill(false)))
225 .on_click(move |_, _, cx| {
226 cx.write_to_clipboard(ClipboardItem::new_string(code.clone()))
227 })
228 .child(symbol("content_copy", 13., muted))
229 .child("Copy"),
230 )
231}
232
233fn token_style(token: Token) -> HighlightStyle {
234 match token {
235 Token::Keyword => HighlightStyle {
236 color: Some(theme::accent_text()),
237 ..Default::default()
238 },
239 Token::String | Token::Number => HighlightStyle {
240 color: Some(theme::accent_soft()),
241 ..Default::default()
242 },
243 Token::Comment => HighlightStyle {
244 color: Some(theme::text_faint()),
245 font_style: Some(FontStyle::Italic),
246 ..Default::default()
247 },
248 }
249}
250
251fn render_list(
252 ordered: bool,
253 start: u32,
254 items: &[Vec<Block>],
255 id: &str,
256 own: bool,
257 depth: usize,
258 cx: &App,
259) -> AnyElement {
260 let last_number = start as usize + items.len().saturating_sub(1);
261 let marker_width = if ordered && last_number >= 10 {
262 WIDE_MARKER_WIDTH
263 } else {
264 MARKER_WIDTH
265 };
266 let marker_color = if own {
267 theme::own_meta()
268 } else {
269 theme::text_muted()
270 };
271 v_flex()
272 .w_full()
273 .gap(px(LIST_GAP))
274 .children(items.iter().enumerate().map(|(index, item)| {
275 let marker = if ordered {
276 format!("{}.", start as usize + index)
277 } else {
278 BULLETS[depth.min(BULLETS.len() - 1)].to_owned()
279 };
280 h_flex()
281 .w_full()
282 .items_start()
283 .child(
284 div()
285 .flex_none()
286 .w(px(marker_width))
287 .when(ordered, |marker| marker.pr(px(4.)).text_right())
288 .text_color(marker_color)
289 .child(marker),
290 )
291 .child(div().flex_1().min_w_0().child(render_list_item(
292 item,
293 &format!("{id}-{index}"),
294 own,
295 depth + 1,
296 cx,
297 )))
298 }))
299 .into_any_element()
300}
301
302fn render_list_item(blocks: &[Block], id: &str, own: bool, depth: usize, cx: &App) -> AnyElement {
303 v_flex()
304 .w_full()
305 .gap(px(LIST_GAP))
306 .children(
307 blocks
308 .iter()
309 .enumerate()
310 .map(|(index, block)| render_block(block, format!("{id}-{index}"), own, depth, cx)),
311 )
312 .into_any_element()
313}
314
315/// `image` draws an image of a cell; cells without a drawn image show only their text.
316pub fn render_table(
317 header: bool,
318 rows: &[Vec<TableCell>],
319 id: &str,
320 own: bool,
321 cx: &App,
322 image: &dyn Fn(&str) -> Option<AnyElement>,
323) -> AnyElement {
324 let columns = rows.iter().map(Vec::len).max().unwrap_or(0);
325 v_flex()
326 .w_full()
327 .border_t_1()
328 .border_l_1()
329 .border_color(theme::border_strong())
330 .text_size(px(13.))
331 .children(rows.iter().enumerate().map(|(row_index, row)| {
332 let is_header = header && row_index == 0;
333 h_flex()
334 .w_full()
335 .items_stretch()
336 .when(is_header, |line| {
337 line.bg(theme::table_header())
338 .font_weight(FontWeight::SEMIBOLD)
339 .text_color(theme::text_strong())
340 })
341 .children((0..columns).map(|column| {
342 let cell = div()
343 .flex_1()
344 .min_w_0()
345 .px(px(8.))
346 .py(px(4.))
347 .border_r_1()
348 .border_b_1()
349 .border_color(theme::border_strong());
350 match row.get(column) {
351 Some(content) => cell
352 .flex()
353 .flex_col()
354 .gap(px(6.))
355 .children(content.images.iter().filter_map(|url| image(url)))
356 .when(!content.inline.is_blank(), |cell| {
357 cell.child(render_inline(
358 &content.inline,
359 format!("{id}-{row_index}-{column}"),
360 own,
361 cx,
362 ))
363 }),
364 None => cell,
365 }
366 }))
367 }))
368 .into_any_element()
369}
370
371fn code_font(cx: &App) -> SharedString {
372 use gpui_kit::component::ActiveTheme as _;
373 cx.theme().mono_font_family.clone()
374}
375
376const KEYCAP: char = '\u{20e3}';
377const VARIATION_SELECTOR: char = '\u{fe0f}';
378
379/// Font fallback maps the keycap base digit to the text font and leaves the combining keycap as a box.
380pub fn keycap_ranges(text: &str) -> Vec<std::ops::Range<usize>> {
381 let mut ranges = Vec::new();
382 for (keycap_at, _) in text.match_indices(KEYCAP) {
383 let before = &text[..keycap_at];
384 let before = before.strip_suffix(VARIATION_SELECTOR).unwrap_or(before);
385 let Some(base) = before.chars().next_back() else {
386 continue;
387 };
388 if base.is_ascii_digit() || base == '#' || base == '*' {
389 ranges.push(before.len() - base.len_utf8()..keycap_at + KEYCAP.len_utf8());
390 }
391 }
392 ranges
393}
394
395/// gpui applies a font override only to a run that lies inside it, so every cut range gets runs of its own.
396pub fn split_highlights(
397 highlights: Vec<(std::ops::Range<usize>, HighlightStyle)>,
398 cuts: &[std::ops::Range<usize>],
399 text_len: usize,
400) -> Vec<(std::ops::Range<usize>, HighlightStyle)> {
401 if cuts.is_empty() {
402 return highlights;
403 }
404 let mut covered = Vec::new();
405 let mut cursor = 0;
406 for (range, style) in highlights {
407 if cursor < range.start {
408 covered.push((cursor..range.start, HighlightStyle::default()));
409 }
410 cursor = cursor.max(range.end);
411 covered.push((range, style));
412 }
413 if cursor < text_len {
414 covered.push((cursor..text_len, HighlightStyle::default()));
415 }
416 let mut points: Vec<usize> = cuts.iter().flat_map(|cut| [cut.start, cut.end]).collect();
417 points.sort_unstable();
418 covered
419 .into_iter()
420 .flat_map(|(range, style)| {
421 let mut start = range.start;
422 let mut pieces = Vec::new();
423 for &point in points
424 .iter()
425 .filter(|&&point| range.start < point && point < range.end)
426 {
427 pieces.push((start..point, style));
428 start = point;
429 }
430 pieces.push((start..range.end, style));
431 pieces
432 })
433 .collect()
434}
435
436fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement {
437 let highlights = inline
438 .segments
439 .iter()
440 .filter(|segment| !segment.style.is_plain())
441 .map(|segment| (segment.range.clone(), highlight_for(segment.style, own)))
442 .collect::<Vec<_>>();
443 let mono = code_font(cx);
444 let emoji_family = SharedString::from(theme::EMOJI_FONT_FAMILY);
445 let mut font_overrides: Vec<_> = inline
446 .segments
447 .iter()
448 .filter(|segment| segment.style.code)
449 .map(|segment| (segment.range.clone(), mono.clone()))
450 .chain(
451 keycap_ranges(&inline.text)
452 .into_iter()
453 .map(|range| (range, emoji_family.clone())),
454 )
455 .chain(
456 inline
457 .segments
458 .iter()
459 .filter(|segment| segment.emoji.is_some())
460 .map(|segment| (segment.range.clone(), emoji_family.clone())),
461 )
462 .collect();
463 font_overrides.sort_by_key(|(range, _)| range.start);
464 let keycaps = keycap_ranges(&inline.text);
465 let emoji = inline.emoji();
466 let highlights = highlights
467 .into_iter()
468 .chain(emoji.iter().map(|(range, _)| {
469 (
470 range.clone(),
471 HighlightStyle {
472 color: Some(transparent_black()),
473 ..Default::default()
474 },
475 )
476 }))
477 .collect::<Vec<_>>();
478 let inline_images = emoji
479 .into_iter()
480 .filter_map(|(range, url)| Some((range, super::hooks::inline_image(&url, cx)?)))
481 .collect();
482 let pills = inline
483 .segments
484 .iter()
485 .filter_map(|segment| pill_for(segment.range.clone(), segment.style, own))
486 .collect();
487 if inline
488 .segments
489 .iter()
490 .any(|segment| segment.style.is_flowed())
491 {
492 let segments = inline
493 .segments
494 .iter()
495 .map(|segment| FlowSegment {
496 range: segment.range.clone(),
497 highlight: match segment.emoji {
498 Some(_) => HighlightStyle {
499 color: Some(transparent_black()),
500 ..Default::default()
501 },
502 None => highlight_for(segment.style, own),
503 },
504 family: if segment.emoji.is_some() {
505 Some(SharedString::from(theme::EMOJI_FONT_FAMILY))
506 } else {
507 segment.style.code.then(|| mono.clone())
508 },
509 scale: segment.style.font_scale(),
510 raise: segment.style.baseline_raise(),
511 })
512 .collect();
513 return div()
514 .w_full()
515 .text_color(theme::text())
516 .child(
517 FlowText::new(ElementId::Name(id.into()), inline.text.clone(), segments)
518 .links(inline.links())
519 .pills(pills),
520 )
521 .into_any_element();
522 }
523 div()
524 .w_full()
525 .text_color(theme::text())
526 .child(
527 SelectableRichText::new(
528 ElementId::Name(id.into()),
529 inline.text.clone(),
530 split_highlights(highlights, &keycaps, inline.text.len()),
531 )
532 .links(inline.links())
533 .font_overrides(font_overrides)
534 .pills(pills)
535 .inline_images(inline_images),
536 )
537 .into_any_element()
538}
539
540fn pill_for(range: std::ops::Range<usize>, style: StyleFlags, own: bool) -> Option<Pill> {
541 if style.code {
542 return Some(Pill {
543 range,
544 fill: theme::inline_code_fill(own),
545 border: Some(theme::code_frame()),
546 radius: px(4.),
547 });
548 }
549 Some(Pill {
550 range,
551 fill: highlight_fill(style.background?),
552 border: None,
553 radius: px(3.),
554 })
555}
556
557fn highlight_for(style: StyleFlags, own: bool) -> HighlightStyle {
558 let mut highlight = HighlightStyle::default();
559 if style.bold {
560 highlight.font_weight = Some(FontWeight::BOLD);
561 }
562 if style.italic {
563 highlight.font_style = Some(FontStyle::Italic);
564 }
565 if let Some(color) = style.color {
566 highlight.color = Some(readable(color, own));
567 }
568 if style.code {
569 highlight.color = Some(code_text(own));
570 }
571 if style.underline {
572 highlight.underline = Some(UnderlineStyle {
573 thickness: px(1.),
574 color: None,
575 wavy: false,
576 });
577 }
578 if style.strike {
579 highlight.color = Some(if own {
580 theme::own_meta()
581 } else {
582 theme::text_muted()
583 });
584 highlight.strikethrough = Some(StrikethroughStyle {
585 thickness: px(1.),
586 color: None,
587 });
588 }
589 let accent = if own {
590 theme::accent_soft()
591 } else {
592 theme::accent_text()
593 };
594 if style.mention {
595 highlight.font_weight = Some(FontWeight::BOLD);
596 highlight.color = Some(accent);
597 }
598 if style.link {
599 highlight.color = Some(accent);
600 highlight.underline = Some(UnderlineStyle {
601 thickness: px(1.),
602 color: Some(accent),
603 wavy: false,
604 });
605 }
606 highlight
607}
608
609pub fn highlight_fill(color: u32) -> Hsla {
610 let mut fill: Hsla = rgb(color).into();
611 fill.a = HIGHLIGHT_ALPHA;
612 fill
613}
614
615fn readable(color: u32, own: bool) -> Hsla {
616 readable_on(
617 color,
618 if own {
619 theme::bubble_own()
620 } else {
621 theme::bubble_other()
622 },
623 )
624}
625
626/// `color` moved towards black or white until it reads on `background`.
627pub fn readable_on(color: u32, background: Hsla) -> Hsla {
628 let background = Rgba::from(background);
629 let mut foreground = rgb(color);
630 let target = if luminance(background) > 0.5 { 0. } else { 1. };
631 for _ in 0..10 {
632 if contrast(foreground, background) >= MIN_CONTRAST {
633 break;
634 }
635 foreground = Rgba {
636 r: foreground.r + (target - foreground.r) * 0.2,
637 g: foreground.g + (target - foreground.g) * 0.2,
638 b: foreground.b + (target - foreground.b) * 0.2,
639 a: 1.,
640 };
641 }
642 foreground.into()
643}
644
645fn contrast(first: Rgba, second: Rgba) -> f32 {
646 let (lighter, darker) = {
647 let (a, b) = (luminance(first), luminance(second));
648 if a > b { (a, b) } else { (b, a) }
649 };
650 (lighter + 0.05) / (darker + 0.05)
651}
652
653fn luminance(color: Rgba) -> f32 {
654 let channel = |value: f32| {
655 if value <= 0.03928 {
656 value / 12.92
657 } else {
658 ((value + 0.055) / 1.055).powf(2.4)
659 }
660 };
661 0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b)
662}
663
664#[cfg(test)]
665mod tests {
666 use gpui_kit::{Rgba, rgb};
667
668 use super::{MIN_CONTRAST, contrast, keycap_ranges, readable, split_highlights};
669 use app_base::theme;
670 use gpui_kit::{FontWeight, HighlightStyle};
671
672 #[test]
673 fn a_keycap_inside_bold_text_gets_runs_of_its_own() {
674 let bold = HighlightStyle {
675 font_weight: Some(FontWeight::BOLD),
676 ..Default::default()
677 };
678 let split = split_highlights(vec![(0..10, bold)], &[2..9, 12..15], 20);
679 let ranges: Vec<_> = split.iter().map(|(range, _)| range.clone()).collect();
680 assert_eq!(ranges, [0..2, 2..9, 9..10, 10..12, 12..15, 15..20]);
681 assert_eq!(split[1].1, bold);
682 assert_eq!(split[4].1, HighlightStyle::default());
683 }
684
685 #[test]
686 fn keycap_sequences_cover_the_base_the_selector_and_the_keycap() {
687 let text = "\u{1f522} 4\u{fe0f}\u{20e3} After #\u{20e3} x\u{20e3}";
688 let found: Vec<&str> = keycap_ranges(text)
689 .into_iter()
690 .map(|range| &text[range])
691 .collect();
692 assert_eq!(found, ["4\u{fe0f}\u{20e3}", "#\u{20e3}"]);
693 }
694
695 #[test]
696 fn dark_text_color_is_lifted_to_readable_contrast() {
697 let lifted = Rgba::from(readable(0x000080, false));
698 assert!(contrast(lifted, Rgba::from(theme::bubble_other())) >= MIN_CONTRAST);
699 }
700
701 #[test]
702 fn light_text_color_stays_as_sent() {
703 assert_eq!(Rgba::from(readable(0xffd700, false)), rgb(0xffd700));
704 }
705
706 #[test]
707 fn light_text_color_is_darkened_on_a_light_bubble() {
708 theme::set_thread_shade(Some(theme::Shade::Light));
709 let darkened = Rgba::from(readable(0xffd700, false));
710 let bubble = Rgba::from(theme::bubble_other());
711 theme::set_thread_shade(None);
712 assert!(contrast(darkened, bubble) >= MIN_CONTRAST);
713 assert!(darkened.r < 1.);
714 }
715}