BlueGit

ict rusty-teams

Files

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

elements.rs

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