BlueGit

ict rusty-teams

Files

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

elements.rs

elements.rs 14.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::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 .border_b_1()
149 .border_color(theme::code_header_border())
150 .font_family(theme::font_family())
151 .text_size(px(11.))
152 .text_color(muted)
153 .child(language.to_owned())
154 .child(
155 h_flex()
156 .id(ElementId::Name(format!("{id}-copy").into()))
157 .h(px(20.))
158 .px(px(6.))
159 .gap(px(4.))
160 .items_center()
161 .rounded(px(4.))
162 .cursor_pointer()
163 .hover(|button| button.bg(theme::inline_code_fill(false)))
164 .on_click(move |_, _, cx| {
165 cx.write_to_clipboard(ClipboardItem::new_string(code.clone()))
166 })
167 .child(symbol("content_copy", 13., muted))
168 .child("Copy"),
169 )
170}
171
172fn token_style(token: Token) -> HighlightStyle {
173 match token {
174 Token::Keyword => HighlightStyle {
175 color: Some(theme::accent_text()),
176 ..Default::default()
177 },
178 Token::String | Token::Number => HighlightStyle {
179 color: Some(theme::accent_soft()),
180 ..Default::default()
181 },
182 Token::Comment => HighlightStyle {
183 color: Some(theme::text_faint()),
184 font_style: Some(FontStyle::Italic),
185 ..Default::default()
186 },
187 }
188}
189
190fn render_list(
191 ordered: bool,
192 start: u32,
193 items: &[Vec<Block>],
194 id: &str,
195 own: bool,
196 depth: usize,
197 cx: &App,
198) -> AnyElement {
199 let last_number = start as usize + items.len().saturating_sub(1);
200 let marker_width = if ordered && last_number >= 10 {
201 WIDE_MARKER_WIDTH
202 } else {
203 MARKER_WIDTH
204 };
205 let marker_color = if own {
206 theme::own_meta()
207 } else {
208 theme::text_muted()
209 };
210 v_flex()
211 .w_full()
212 .gap(px(LIST_GAP))
213 .children(items.iter().enumerate().map(|(index, item)| {
214 let marker = if ordered {
215 format!("{}.", start as usize + index)
216 } else {
217 BULLETS[depth.min(BULLETS.len() - 1)].to_owned()
218 };
219 h_flex()
220 .w_full()
221 .items_start()
222 .child(
223 div()
224 .flex_none()
225 .w(px(marker_width))
226 .when(ordered, |marker| marker.pr(px(4.)).text_right())
227 .text_color(marker_color)
228 .child(marker),
229 )
230 .child(div().flex_1().min_w_0().child(render_list_item(
231 item,
232 &format!("{id}-{index}"),
233 own,
234 depth + 1,
235 cx,
236 )))
237 }))
238 .into_any_element()
239}
240
241fn render_list_item(blocks: &[Block], id: &str, own: bool, depth: usize, cx: &App) -> AnyElement {
242 v_flex()
243 .w_full()
244 .gap(px(LIST_GAP))
245 .children(
246 blocks
247 .iter()
248 .enumerate()
249 .map(|(index, block)| render_block(block, format!("{id}-{index}"), own, depth, cx)),
250 )
251 .into_any_element()
252}
253
254fn render_table(header: bool, rows: &[Vec<Inline>], id: &str, own: bool, cx: &App) -> AnyElement {
255 let columns = rows.iter().map(Vec::len).max().unwrap_or(0);
256 v_flex()
257 .w_full()
258 .border_t_1()
259 .border_l_1()
260 .border_color(theme::border_strong())
261 .text_size(px(13.))
262 .children(rows.iter().enumerate().map(|(row_index, row)| {
263 let is_header = header && row_index == 0;
264 h_flex()
265 .w_full()
266 .items_stretch()
267 .when(is_header, |line| {
268 line.bg(theme::table_header())
269 .font_weight(FontWeight::SEMIBOLD)
270 .text_color(theme::text_strong())
271 })
272 .children((0..columns).map(|column| {
273 let cell = div()
274 .flex_1()
275 .min_w_0()
276 .px(px(8.))
277 .py(px(4.))
278 .border_r_1()
279 .border_b_1()
280 .border_color(theme::border_strong());
281 match row.get(column) {
282 Some(inline) => cell.child(render_inline(
283 inline,
284 format!("{id}-{row_index}-{column}"),
285 own,
286 cx,
287 )),
288 None => cell,
289 }
290 }))
291 }))
292 .into_any_element()
293}
294
295fn code_font(cx: &App) -> SharedString {
296 use gpui_kit::component::ActiveTheme as _;
297 cx.theme().mono_font_family.clone()
298}
299
300fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement {
301 let highlights = inline
302 .segments
303 .iter()
304 .filter(|segment| !segment.style.is_plain())
305 .map(|segment| (segment.range.clone(), highlight_for(segment.style, own)))
306 .collect::<Vec<_>>();
307 let mono = code_font(cx);
308 let font_overrides = inline
309 .segments
310 .iter()
311 .filter(|segment| segment.style.code)
312 .map(|segment| (segment.range.clone(), mono.clone()))
313 .collect();
314 let pills = inline
315 .segments
316 .iter()
317 .filter_map(|segment| pill_for(segment.range.clone(), segment.style, own))
318 .collect();
319 if inline
320 .segments
321 .iter()
322 .any(|segment| segment.style.is_flowed())
323 {
324 let segments = inline
325 .segments
326 .iter()
327 .map(|segment| FlowSegment {
328 range: segment.range.clone(),
329 highlight: highlight_for(segment.style, own),
330 family: segment.style.code.then(|| mono.clone()),
331 scale: segment.style.font_scale(),
332 raise: segment.style.baseline_raise(),
333 })
334 .collect();
335 return div()
336 .w_full()
337 .text_color(theme::text())
338 .child(
339 FlowText::new(ElementId::Name(id.into()), inline.text.clone(), segments)
340 .links(inline.links())
341 .pills(pills),
342 )
343 .into_any_element();
344 }
345 div()
346 .w_full()
347 .text_color(theme::text())
348 .child(
349 SelectableRichText::new(ElementId::Name(id.into()), inline.text.clone(), highlights)
350 .links(inline.links())
351 .font_overrides(font_overrides)
352 .pills(pills),
353 )
354 .into_any_element()
355}
356
357fn pill_for(range: std::ops::Range<usize>, style: StyleFlags, own: bool) -> Option<Pill> {
358 if style.code {
359 return Some(Pill {
360 range,
361 fill: theme::inline_code_fill(own),
362 border: Some(theme::inline_code_border()),
363 radius: px(4.),
364 });
365 }
366 let background = style.background?;
367 let mut fill: Hsla = rgb(background).into();
368 fill.a = HIGHLIGHT_ALPHA;
369 Some(Pill {
370 range,
371 fill,
372 border: None,
373 radius: px(3.),
374 })
375}
376
377fn highlight_for(style: StyleFlags, own: bool) -> HighlightStyle {
378 let mut highlight = HighlightStyle::default();
379 if style.bold {
380 highlight.font_weight = Some(FontWeight::BOLD);
381 }
382 if style.italic {
383 highlight.font_style = Some(FontStyle::Italic);
384 }
385 if let Some(color) = style.color {
386 highlight.color = Some(readable(color, own));
387 }
388 if style.code {
389 highlight.color = Some(if own {
390 theme::accent_soft()
391 } else {
392 theme::text_strong()
393 });
394 }
395 if style.underline {
396 highlight.underline = Some(UnderlineStyle {
397 thickness: px(1.),
398 color: None,
399 wavy: false,
400 });
401 }
402 if style.strike {
403 highlight.color = Some(if own {
404 theme::own_meta()
405 } else {
406 theme::text_muted()
407 });
408 highlight.strikethrough = Some(StrikethroughStyle {
409 thickness: px(1.),
410 color: None,
411 });
412 }
413 let accent = if own {
414 theme::accent_soft()
415 } else {
416 theme::accent_text()
417 };
418 if style.mention {
419 highlight.font_weight = Some(FontWeight::BOLD);
420 highlight.color = Some(accent);
421 }
422 if style.link {
423 highlight.color = Some(accent);
424 highlight.underline = Some(UnderlineStyle {
425 thickness: px(1.),
426 color: Some(accent),
427 wavy: false,
428 });
429 }
430 highlight
431}
432
433fn readable(color: u32, own: bool) -> Hsla {
434 let background = Rgba::from(if own {
435 theme::bubble_own()
436 } else {
437 theme::bubble_other()
438 });
439 let mut foreground = rgb(color);
440 for _ in 0..10 {
441 if contrast(foreground, background) >= MIN_CONTRAST {
442 break;
443 }
444 foreground = Rgba {
445 r: foreground.r + (1. - foreground.r) * 0.2,
446 g: foreground.g + (1. - foreground.g) * 0.2,
447 b: foreground.b + (1. - foreground.b) * 0.2,
448 a: 1.,
449 };
450 }
451 foreground.into()
452}
453
454fn contrast(first: Rgba, second: Rgba) -> f32 {
455 let (lighter, darker) = {
456 let (a, b) = (luminance(first), luminance(second));
457 if a > b { (a, b) } else { (b, a) }
458 };
459 (lighter + 0.05) / (darker + 0.05)
460}
461
462fn luminance(color: Rgba) -> f32 {
463 let channel = |value: f32| {
464 if value <= 0.03928 {
465 value / 12.92
466 } else {
467 ((value + 0.055) / 1.055).powf(2.4)
468 }
469 };
470 0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b)
471}
472
473#[cfg(test)]
474mod tests {
475 use gpui_kit::{Rgba, rgb};
476
477 use super::{MIN_CONTRAST, contrast, readable};
478 use crate::theme;
479
480 #[test]
481 fn dark_text_color_is_lifted_to_readable_contrast() {
482 let lifted = Rgba::from(readable(0x000080, false));
483 assert!(contrast(lifted, Rgba::from(theme::bubble_other())) >= MIN_CONTRAST);
484 }
485
486 #[test]
487 fn light_text_color_stays_as_sent() {
488 assert_eq!(Rgba::from(readable(0xffd700, false)), rgb(0xffd700));
489 }
490}