BlueGit

ict rusty-teams

Files

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

elements.rs

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