BlueGit

ict rusty-teams

Files

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

elements.rs

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