BlueGit

ict rusty-teams

Files

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

elements.rs

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