1use std::{cell::RefCell, ops::Range, rc::Rc};
11
12use gpui::{
13 AnyElement, App, BorderStyle, Bounds, CursorStyle, ElementId, FontStyle, FontWeight, Hsla,
14 InteractiveText, ObjectFit, Pixels, Point, SharedString, StrikethroughStyle, StyledImage as _,
15 StyledText, TextLayout, TextRun, UnderlineStyle, Window, canvas, div, font, img, point,
16 prelude::*, px, quad, size,
17};
18use theme::{TextStyle, Theme, Typeset};
19
20use crate::{
21 block,
22 doc::{Align, Block, BlockKind, Doc, Form, Mark, Part, Text},
23 layout::Layout,
24 preview,
25 select::{Cursor, Selection},
26 typography::Typography,
27};
28
29const BLOCK_GAP: f32 = 12.0;
31const LIST_GAP: f32 = 4.0;
32const INDENT_WIDTH: f32 = 22.0;
34const MARKER_WIDTH: f32 = 18.0;
36const MARKER_GAP: f32 = 8.0;
37const CODE_PADDING_X: f32 = 12.0;
39const CODE_PADDING_Y: f32 = 10.0;
40pub const PLAIN_LANGUAGE: &str = "Plain";
43const CARET_WIDTH: f32 = 1.5;
46const INLINE_CODE_RADIUS: f32 = 4.5;
49const INLINE_CODE_PAD_X: f32 = 2.0;
50const INLINE_CODE_INSET_Y: f32 = 2.0;
51const CHIP_PAD_X: f32 = 4.0;
54const CHIP_INSET_Y: f32 = 1.0;
55const CHIP_BLOCK_PAD_X: f32 = 8.0;
58const CHIP_BLOCK_PAD_Y: f32 = 3.0;
59const CHIP_ICON: f32 = 15.0;
60const CARD_HEIGHT: f32 = 116.0;
64const CARD_IMAGE_WIDTH: f32 = 180.0;
65const CARD_COVER_HEIGHT: f32 = 200.0;
66const CARD_PADDING: f32 = 14.0;
67const CARD_BORDER: f32 = 1.0;
68const CARD_ICON: f32 = 16.0;
69const CARD_COVER: f32 = 44.0;
70const IMAGE_EMPTY_HEIGHT: f32 = 52.0;
72const CAPTION_GAP: f32 = 4.0;
73const IMAGE_EMPTY: &str = "Add an image";
75const CAPTION_HINT: &str = "Write a caption";
76const TABLE_CELL_PADDING: f32 = 12.0;
79const TABLE_DIVIDER: f32 = 1.0;
80const TABLE_MIN_COLUMN_CONTENT: f32 = 48.0;
83const TABLE_MIN_COLUMN_WIDTH: f32 = 96.0;
85
86#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
97pub enum Caption {
98 #[default]
100 Shown,
101 Hidden,
103}
104
105#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
112pub enum Annotation {
113 #[default]
115 Open,
116 Resolved,
118 Active,
120}
121
122impl Annotation {
123 fn wash(self, theme: &Theme) -> Hsla {
124 match self {
125 Self::Open => theme.warning.opacity(0.20),
126 Self::Resolved => theme.warning.opacity(0.08),
127 Self::Active => theme.warning.opacity(0.38),
128 }
129 }
130}
131
132#[derive(Clone)]
138pub struct Editing<'a> {
139 pub selection: Option<Selection>,
142 pub caret_on: bool,
145 pub layouts: Option<&'a BlockLayouts>,
147 pub annotations: &'a [(Selection, Annotation)],
149 pub placeholder: Option<SharedString>,
151 pub caption: Caption,
152 pub typography: Option<Typography>,
156}
157
158impl Default for Editing<'_> {
159 fn default() -> Self {
160 Self {
161 selection: None,
162 caret_on: true,
165 layouts: None,
166 annotations: &[],
167 placeholder: None,
168 caption: Caption::default(),
169 typography: None,
170 }
171 }
172}
173
174#[derive(Clone, Default)]
181pub struct BlockLayouts(Rc<RefCell<Frames>>);
182
183#[derive(Default)]
184struct Frames {
185 texts: Vec<Painted>,
186 blocks: Vec<(usize, Bounds<Pixels>)>,
189 languages: Vec<(usize, Bounds<Pixels>)>,
192 pictures: Vec<(usize, Bounds<Pixels>)>,
196}
197
198struct Painted {
205 block: usize,
206 part: Part,
207 range: Range<usize>,
208 layout: TextLayout,
209}
210
211impl BlockLayouts {
212 pub fn hit(&self, point: Point<Pixels>) -> Option<Cursor> {
218 let entries = &self.0.borrow().texts;
219 let cursor = |painted: &Painted| {
220 let (Ok(offset) | Err(offset)) = painted.layout.index_for_position(point);
221 Cursor::new(
222 painted.block,
223 painted.part,
224 painted.range.start + offset.min(painted.range.len()),
225 )
226 };
227 if let Some(painted) = entries
228 .iter()
229 .find(|painted| painted.layout.bounds().contains(&point))
230 {
231 return Some(cursor(painted));
232 }
233 entries
234 .iter()
235 .min_by_key(|painted| {
236 let bounds = painted.layout.bounds();
237 let above = (bounds.origin.y - point.y).abs();
238 let below = (bounds.origin.y + bounds.size.height - point.y).abs();
239 f32::from(above.min(below)) as i64
240 })
241 .map(cursor)
242 }
243
244 pub fn position(&self, at: Cursor) -> Option<(Point<Pixels>, Pixels)> {
250 let entries = &self.0.borrow().texts;
251 let painted = entries.iter().find(|painted| {
252 painted.block == at.block
253 && painted.part == at.part
254 && painted.range.start <= at.offset
255 && at.offset <= painted.range.end
256 })?;
257 let point = painted
258 .layout
259 .position_for_index(at.offset - painted.range.start)?;
260 Some((point, painted.layout.line_height()))
261 }
262
263 pub fn rects(&self, selection: Selection) -> Vec<Bounds<Pixels>> {
271 let (start, end) = selection.ordered();
272 self.0
273 .borrow()
274 .texts
275 .iter()
276 .filter_map(|painted| {
277 let here = Cursor::new(painted.block, painted.part, 0);
278 let (from, to) = (
279 Cursor::new(start.block, start.part, 0),
280 Cursor::new(end.block, end.part, 0),
281 );
282 if here < from || here > to {
283 return None;
284 }
285 let len = painted.range.len();
288 let first = if here == from { start.offset } else { 0 };
289 let last = if here == to { end.offset } else { usize::MAX };
290 let range = first.saturating_sub(painted.range.start).min(len)
291 ..last.saturating_sub(painted.range.start).min(len);
292 (range.start < range.end).then(|| range_rects(&painted.layout, &range, 0.0, 0.0))
293 })
294 .flatten()
295 .collect()
296 }
297
298 pub fn step_row(
309 &self,
310 at: Cursor,
311 from: Point<Pixels>,
312 down: bool,
313 ) -> Option<(Cursor, Pixels)> {
314 let entries = &self.0.borrow().texts;
315 let ix = entries.iter().position(|painted| {
316 painted.block == at.block
317 && painted.part == at.part
318 && painted.range.start <= at.offset
319 && at.offset <= painted.range.end
320 })?;
321 let here = &entries[ix];
322 let line = here.layout.line_height();
323 let index_at = |painted: &Painted, y: Pixels| {
324 let (Ok(offset) | Err(offset)) = painted.layout.index_for_position(point(from.x, y));
325 (
326 Cursor::new(
327 painted.block,
328 painted.part,
329 painted.range.start + offset.min(painted.range.len()),
330 ),
331 y,
332 )
333 };
334
335 let bounds = here.layout.bounds();
338 let target = if down { from.y + line } else { from.y - line };
339 if target >= bounds.origin.y && target < bounds.origin.y + bounds.size.height {
340 return Some(index_at(here, target));
341 }
342
343 let next = match down {
344 true => entries.get(ix + 1)?,
345 false => entries.get(ix.checked_sub(1)?)?,
346 };
347 let bounds = next.layout.bounds();
349 let row = match down {
350 true => bounds.origin.y,
351 false => bounds.origin.y + bounds.size.height - next.layout.line_height(),
352 };
353 Some(index_at(next, row))
354 }
355
356 pub fn over_text(&self, point: Point<Pixels>) -> bool {
363 self.0
364 .borrow()
365 .texts
366 .iter()
367 .any(|painted| painted.layout.bounds().contains(&point))
368 }
369
370 pub fn block_at(&self, point: Point<Pixels>) -> Option<usize> {
372 let blocks = &self.0.borrow().blocks;
373 blocks
374 .iter()
375 .find(|(_, bounds)| bounds.contains(&point))
376 .or_else(|| {
377 blocks.iter().min_by_key(|(_, bounds)| {
378 let above = (bounds.origin.y - point.y).abs();
379 let below = (bounds.origin.y + bounds.size.height - point.y).abs();
380 f32::from(above.min(below)) as i64
381 })
382 })
383 .map(|(ix, _)| *ix)
384 }
385
386 pub fn first_row(&self, ix: usize) -> Option<(Pixels, Pixels)> {
395 let texts = &self.0.borrow().texts;
396 let painted = texts.iter().find(|painted| painted.block == ix)?;
397 Some((
398 painted.layout.bounds().origin.y,
399 painted.layout.line_height(),
400 ))
401 }
402
403 pub fn block_bounds(&self, ix: usize) -> Option<Bounds<Pixels>> {
405 self.0
406 .borrow()
407 .blocks
408 .iter()
409 .find(|(block, _)| *block == ix)
410 .map(|(_, bounds)| *bounds)
411 }
412
413 pub fn language_bounds(&self, ix: usize) -> Option<Bounds<Pixels>> {
418 self.0
419 .borrow()
420 .languages
421 .iter()
422 .find(|(block, _)| *block == ix)
423 .map(|(_, bounds)| *bounds)
424 }
425
426 pub fn picture_bounds(&self, ix: usize) -> Option<Bounds<Pixels>> {
431 self.0
432 .borrow()
433 .pictures
434 .iter()
435 .find(|(block, _)| *block == ix)
436 .map(|(_, bounds)| *bounds)
437 }
438
439 fn record(&self, block: usize, part: Part, range: Range<usize>, layout: TextLayout) {
440 self.0.borrow_mut().texts.push(Painted {
441 block,
442 part,
443 range,
444 layout,
445 });
446 }
447
448 fn record_block(&self, ix: usize, bounds: Bounds<Pixels>) {
449 self.0.borrow_mut().blocks.push((ix, bounds));
450 }
451
452 fn record_language(&self, ix: usize, bounds: Bounds<Pixels>) {
453 self.0.borrow_mut().languages.push((ix, bounds));
454 }
455
456 fn record_picture(&self, ix: usize, bounds: Bounds<Pixels>) {
457 self.0.borrow_mut().pictures.push((ix, bounds));
458 }
459
460 fn clear(&self) {
461 let mut frames = self.0.borrow_mut();
462 frames.texts.clear();
463 frames.blocks.clear();
464 frames.languages.clear();
465 frames.pictures.clear();
466 }
467}
468
469#[derive(Clone, Copy)]
475struct Overlay<'a> {
476 block: usize,
477 part: Part,
478 selection: Option<Selection>,
479 caret_on: bool,
480 layouts: Option<&'a BlockLayouts>,
481 annotations: &'a [(Selection, Annotation)],
483 placeholder: Option<&'a SharedString>,
486 caption: Caption,
487}
488
489impl<'a> Overlay<'a> {
490 fn at(self, part: Part) -> Self {
491 Self { part, ..self }
492 }
493
494 fn here(&self) -> Cursor {
495 Cursor::new(self.block, self.part, 0)
496 }
497
498 fn caret_painted(&self) -> Option<usize> {
504 self.caret_on.then(|| self.caret()).flatten()
505 }
506
507 fn caret(&self) -> Option<usize> {
509 self.selection
510 .map(|selection| selection.head)
511 .filter(|head| head.block == self.block && head.part == self.part)
512 .map(|head| head.offset)
513 }
514
515 fn selected(&self, len: usize) -> Option<Range<usize>> {
517 self.clip(self.selection?, len)
518 }
519
520 fn annotated(&self, len: usize, theme: &Theme) -> Vec<(Range<usize>, Hsla)> {
523 self.annotations
524 .iter()
525 .filter_map(|(range, kind)| Some((self.clip(*range, len)?, kind.wash(theme))))
526 .collect()
527 }
528
529 fn clip(&self, selection: Selection, len: usize) -> Option<Range<usize>> {
535 if selection.is_collapsed() {
536 return None;
537 }
538 let (start, end) = selection.ordered();
539 let here = self.here();
540 let (first, last) = (
541 Cursor::new(start.block, start.part, 0),
542 Cursor::new(end.block, end.part, 0),
543 );
544 if here < first || here > last {
545 return None;
546 }
547 let from = if here == first { start.offset } else { 0 };
548 let to = if here == last { end.offset } else { len };
549 (from < to).then_some(from..to.min(len))
550 }
551
552 fn covers_block(&self) -> bool {
556 let Some(selection) = self.selection.filter(|s| !s.is_collapsed()) else {
557 return false;
558 };
559 let (start, end) = selection.ordered();
560 start.block < self.block && self.block < end.block
561 }
562}
563
564pub fn markdown(source: &str, window: &mut Window, cx: &mut App) -> AnyElement {
566 let doc = crate::parse_with(source, &crate::Marks::of(cx));
567 render(&doc, Caption::default(), window, cx)
568}
569
570pub fn render(doc: &Doc, caption: Caption, window: &mut Window, cx: &mut App) -> AnyElement {
572 render_with(
573 doc,
574 Editing {
575 caption,
576 ..Editing::default()
577 },
578 window,
579 cx,
580 )
581}
582
583pub fn render_with(doc: &Doc, editing: Editing, window: &mut Window, cx: &mut App) -> AnyElement {
591 let Editing {
592 selection,
593 caret_on,
594 layouts,
595 annotations,
596 placeholder,
597 caption,
598 typography,
599 } = editing;
600 let reset = layouts.map(|layouts| {
606 let layouts = layouts.clone();
607 canvas(move |_, _, _| layouts.clear(), |_, _, _, _| ())
608 .absolute()
609 .size(px(0.0))
610 });
611 let theme = Theme::of(cx).clone();
614 let typography = typography.unwrap_or_else(|| Typography::of(cx));
615 let mut column = div().flex().flex_col().children(reset);
616
617 for (ix, block) in doc.blocks.iter().enumerate() {
618 let gap = match doc.blocks.get(ix.wrapping_sub(1)) {
619 None => 0.0,
620 Some(previous) if tight(previous, block) => LIST_GAP,
621 Some(_) => BLOCK_GAP,
622 };
623 let overlay = Overlay {
624 block: ix,
625 part: Part::Body,
626 selection,
627 caret_on,
628 layouts,
629 annotations,
630 placeholder: placeholder.as_ref(),
631 caption,
632 };
633 let frame = layouts.map(|layouts| {
636 let layouts = layouts.clone();
637 canvas(
638 move |bounds, _, _| layouts.record_block(ix, bounds),
639 |_, _, _, _| (),
640 )
641 .absolute()
642 .size_full()
643 });
644 column = column.child(
645 div()
651 .mt(px(gap))
652 .pl(px(block.indent as f32 * INDENT_WIDTH))
653 .child(
654 div()
655 .w_full()
656 .relative()
657 .children(frame)
658 .when(overlay.covers_block() && block.opaque(), |el| {
663 el.rounded(px(4.0)).bg(theme.selection)
664 })
665 .child(block_element(
666 block,
667 overlay,
668 &typography,
669 &theme,
670 window,
671 cx,
672 )),
673 ),
674 );
675 }
676
677 column.into_any_element()
678}
679
680fn tight(previous: &Block, next: &Block) -> bool {
682 let marker = |block: &Block| {
683 matches!(
684 block.kind,
685 BlockKind::Bullet(_) | BlockKind::Ordered { .. } | BlockKind::Task { .. }
686 )
687 };
688 marker(previous) && (marker(next) || next.indent > previous.indent)
689}
690
691fn block_element(
692 block: &Block,
693 overlay: Overlay,
694 typography: &Typography,
695 theme: &Theme,
696 window: &mut Window,
697 cx: &mut App,
698) -> AnyElement {
699 let body = overlay.at(Part::Body);
700 match &block.kind {
701 BlockKind::Paragraph(text) => text_element(
702 text,
703 typography.body.size(),
704 typography.body.line_height(),
705 FontWeight::NORMAL,
706 body,
707 theme,
708 cx,
709 ),
710 BlockKind::Heading { level, text } => {
711 let heading = typography.heading(*level);
712 text_element(
713 text,
714 heading.size(),
715 heading.line_height(),
716 heading.weight,
717 body,
718 theme,
719 cx,
720 )
721 }
722 BlockKind::Bullet(text) => {
723 marker_row(disc(typography, theme), text, body, typography, theme, cx)
724 }
725 BlockKind::Ordered { number, text } => marker_row(
726 div()
727 .flex_none()
728 .w(px(MARKER_WIDTH))
729 .text_size(px(typography.body.size()))
730 .line_height(px(typography.body.line_height()))
731 .text_color(theme.text_muted)
732 .child(SharedString::from(format!("{number}.")))
733 .into_any_element(),
734 text,
735 body,
736 typography,
737 theme,
738 cx,
739 ),
740 BlockKind::Task { checked, text } => marker_row(
741 checkbox(*checked, typography, theme),
742 text,
743 body,
744 typography,
745 theme,
746 cx,
747 ),
748 BlockKind::Quote(text) => div()
749 .border_l_2()
750 .border_color(theme.border_strong)
751 .pl(px(12.0))
752 .pr(px(10.0))
753 .py(px(2.0))
754 .text_color(theme.text_muted)
755 .child(text_element(
756 text,
757 typography.body.size(),
758 typography.body.line_height(),
759 FontWeight::NORMAL,
760 body,
761 theme,
762 cx,
763 ))
764 .into_any_element(),
765 BlockKind::Code { language, code } => {
766 let overlay = overlay.at(Part::Code);
767 let painted = overlay
771 .caret()
772 .is_none()
773 .then(|| block::render(language.as_deref(), &code.text, window, cx))
774 .flatten();
775 match painted {
776 Some(element) => div()
779 .when(overlay.covers_block(), |el| {
780 el.rounded(px(4.0)).bg(theme.selection)
781 })
782 .child(element)
783 .into_any_element(),
784 None => code_block(
785 language.as_deref(),
786 &code.text,
787 overlay,
788 typography,
789 theme,
790 window,
791 cx,
792 ),
793 }
794 }
795 BlockKind::Image { url, alt, width } => {
796 image(url, alt, *width, overlay, typography, theme, cx)
797 }
798 BlockKind::Bookmark { url, form } => {
799 bookmark(overlay.block, url, *form, typography, theme, cx)
800 }
801 BlockKind::Table {
802 align,
803 header,
804 rows,
805 } => table(align, header, rows, overlay, typography, theme, window, cx),
806 BlockKind::Rule => div()
807 .h(px(1.0))
808 .w_full()
809 .bg(theme.border)
810 .into_any_element(),
811 }
812}
813
814fn disc(typography: &Typography, theme: &Theme) -> AnyElement {
816 div()
817 .flex_none()
818 .w(px(MARKER_WIDTH))
819 .h(px(typography.body.line_height()))
820 .flex()
821 .items_center()
822 .child(
823 div()
824 .ml(px(1.0))
825 .w(px(5.0))
826 .h(px(5.0))
827 .rounded_full()
828 .bg(theme.text_faint),
829 )
830 .into_any_element()
831}
832
833fn checkbox(checked: bool, typography: &Typography, theme: &Theme) -> AnyElement {
834 let mut box_ = div()
835 .w(px(13.0))
836 .h(px(13.0))
837 .rounded(px(3.5))
838 .border_1()
839 .flex()
840 .items_center()
841 .justify_center();
842 box_ = if checked {
843 box_.bg(theme.solid)
844 .border_color(theme.solid)
845 .text_style(TextStyle::Caption)
846 .text_color(theme.on_solid)
847 .child("✓")
848 } else {
849 box_.border_color(theme.border_strong)
850 };
851
852 div()
853 .flex_none()
854 .w(px(MARKER_WIDTH))
855 .h(px(typography.body.line_height()))
856 .flex()
857 .items_center()
858 .child(box_)
859 .into_any_element()
860}
861
862fn marker_row(
863 marker: AnyElement,
864 text: &Text,
865 overlay: Overlay,
866 typography: &Typography,
867 theme: &Theme,
868 cx: &App,
869) -> AnyElement {
870 div()
871 .flex()
872 .flex_row()
873 .gap(px(MARKER_GAP))
874 .child(marker)
875 .child(div().flex_1().min_w_0().child(text_element(
876 text,
877 typography.body.size(),
878 typography.body.line_height(),
879 FontWeight::NORMAL,
880 overlay,
881 theme,
882 cx,
883 )))
884 .into_any_element()
885}
886
887pub struct Flat {
890 pub text: SharedString,
891 pub runs: Vec<TextRun>,
892 pub links: Vec<(Range<usize>, String)>,
893 pub code: Vec<Range<usize>>,
894 pub chips: Vec<Range<usize>>,
895}
896
897pub fn flatten(text: &Text, base_weight: FontWeight, theme: &Theme) -> Flat {
900 flatten_with(text, base_weight, theme, |_| None)
901}
902
903pub fn flatten_with(
906 text: &Text,
907 base_weight: FontWeight,
908 theme: &Theme,
909 paint: impl Fn(&str) -> Option<crate::MarkPaint>,
910) -> Flat {
911 let mut cuts: Vec<usize> = text
912 .marks
913 .iter()
914 .flat_map(|span| [span.range.start, span.range.end])
915 .chain([0, text.text.len()])
916 .filter(|cut| *cut <= text.text.len())
917 .collect();
918 cuts.sort_unstable();
919 cuts.dedup();
920
921 let mut runs = Vec::new();
922 let mut links: Vec<(Range<usize>, String)> = Vec::new();
923 let mut code: Vec<Range<usize>> = Vec::new();
924 let mut chips: Vec<Range<usize>> = Vec::new();
925
926 for pair in cuts.windows(2) {
927 let (start, end) = (pair[0], pair[1]);
928 let covering = text
929 .marks
930 .iter()
931 .filter(|span| span.range.start <= start && span.range.end >= end);
932
933 let (mut bold, mut italic, mut mono, mut strike) = (false, false, false, false);
934 let mut chip = false;
935 let mut link = None;
936 let mut custom = crate::MarkPaint::default();
939 for span in covering {
940 match &span.mark {
941 Mark::Bold => bold = true,
942 Mark::Italic => italic = true,
943 Mark::Strike => strike = true,
944 Mark::Code => mono = true,
945 Mark::Mention { url, .. } => {
946 chip = true;
947 link = Some(url.clone());
948 }
949 Mark::Link(url) | Mark::Image(url) => link = Some(url.clone()),
950 Mark::Custom(name) => {
951 let Some(painted) = paint(name) else { continue };
952 custom.color = painted.color.or(custom.color);
953 custom.background = painted.background.or(custom.background);
954 custom.weight = painted.weight.or(custom.weight);
955 custom.italic |= painted.italic;
956 custom.underline |= painted.underline;
957 custom.strikethrough |= painted.strikethrough;
958 }
959 }
960 }
961 let (italic, strike) = (italic || custom.italic, strike || custom.strikethrough);
962
963 if mono {
964 match code.last_mut() {
965 Some(range) if range.end == start => range.end = end,
966 _ => code.push(start..end),
967 }
968 }
969 if chip {
970 match chips.last_mut() {
971 Some(range) if range.end == start => range.end = end,
972 _ => chips.push(start..end),
973 }
974 }
975 if let Some(url) = &link {
976 match links.last_mut() {
977 Some((range, last)) if range.end == start && last == url => range.end = end,
978 _ => links.push((start..end, url.clone())),
979 }
980 }
981
982 let mut face = font(if mono {
983 theme.font_mono.clone()
984 } else {
985 theme.font_sans.clone()
986 });
987 face.weight = if bold && base_weight.0 < FontWeight::SEMIBOLD.0 {
988 FontWeight::SEMIBOLD
989 } else {
990 custom.weight.unwrap_or(base_weight)
991 };
992 face.style = if italic {
993 FontStyle::Italic
994 } else {
995 FontStyle::Normal
996 };
997
998 runs.push(TextRun {
999 len: end - start,
1000 font: face,
1001 color: match (mono, custom.color) {
1005 (_, Some(color)) => color,
1006 (true, None) => theme.code_text,
1007 (false, None) => theme.text,
1008 },
1009 background_color: custom.background,
1010 underline: ((link.is_some() && !chip) || custom.underline).then_some(UnderlineStyle {
1011 color: Some(theme.text_muted),
1012 thickness: px(1.0),
1013 wavy: false,
1014 }),
1015 strikethrough: strike.then_some(StrikethroughStyle {
1016 thickness: px(1.0),
1017 color: Some(theme.text_muted),
1018 }),
1019 });
1020 }
1021
1022 Flat {
1023 text: text.text.clone().into(),
1024 runs,
1025 links,
1026 code,
1027 chips,
1028 }
1029}
1030
1031fn text_element(
1032 text: &Text,
1033 size: f32,
1034 line_height: f32,
1035 weight: FontWeight,
1036 overlay: Overlay,
1037 theme: &Theme,
1038 cx: &App,
1039) -> AnyElement {
1040 let flat = flatten_with(text, weight, theme, |name| {
1041 crate::marks::paint_of(cx, name, theme)
1042 });
1043 painted_text(flat, text.text.len(), size, line_height, overlay, theme)
1044}
1045
1046fn painted_text(
1052 flat: Flat,
1053 len: usize,
1054 size: f32,
1055 line_height: f32,
1056 overlay: Overlay,
1057 theme: &Theme,
1058) -> AnyElement {
1059 let (ix, part) = (overlay.block, overlay.part);
1060 let (caret, selected) = (overlay.caret_painted(), overlay.selected(len));
1061 let span = 0..len;
1062 let hint = overlay
1065 .placeholder
1066 .filter(|_| len == 0 && overlay.caret().is_some())
1069 .map(|hint| {
1070 div()
1071 .absolute()
1072 .text_color(theme.text_faint)
1073 .child(hint.clone())
1074 });
1075 let styled = StyledText::new(flat.text).with_runs(flat.runs);
1076 let layout = styled.layout().clone();
1077
1078 let painted: AnyElement = if flat.links.is_empty() {
1079 styled.into_any_element()
1080 } else {
1081 let (ranges, urls): (Vec<_>, Vec<_>) = flat.links.into_iter().unzip();
1082 InteractiveText::new(ElementId::named_usize("md-text", ix), styled)
1083 .on_click(ranges, move |clicked, _window, cx| {
1084 if let Some(url) = urls.get(clicked) {
1085 cx.open_url(url);
1086 }
1087 })
1088 .into_any_element()
1089 };
1090
1091 let wash = theme.code_wash;
1095 let code_ranges = flat.code;
1096 let chip_wash = theme.element_hover;
1097 let chip_edge = theme.border;
1098 let chip_ranges = flat.chips;
1099 let caret_color = theme.caret;
1100 let selection_color = theme.selection;
1101 let annotated = overlay.annotated(len, theme);
1102 let layouts = overlay.layouts.cloned();
1103 let underlay = canvas(
1104 |_, _, _| (),
1105 move |_, _, window, _| {
1106 if let Some(layouts) = &layouts {
1107 layouts.record(ix, part, span.clone(), layout.clone());
1108 }
1109 for (range, wash) in &annotated {
1112 for rect in range_rects(&layout, range, 0.0, 0.0) {
1113 window.paint_quad(quad(
1114 rect,
1115 px(2.0),
1116 *wash,
1117 px(0.0),
1118 gpui::transparent_black(),
1119 BorderStyle::default(),
1120 ));
1121 }
1122 }
1123 if let Some(range) = &selected {
1127 for rect in range_rects(&layout, range, 0.0, 0.0) {
1128 window.paint_quad(quad(
1129 rect,
1130 px(2.0),
1131 selection_color,
1132 px(0.0),
1133 gpui::transparent_black(),
1134 BorderStyle::default(),
1135 ));
1136 }
1137 }
1138 if let Some(offset) = caret
1139 && let Some(head) = layout.position_for_index(offset)
1140 {
1141 window.paint_quad(quad(
1142 caret_quad(head, size, layout.line_height()),
1143 px(0.0),
1144 caret_color,
1145 px(0.0),
1146 gpui::transparent_black(),
1147 BorderStyle::default(),
1148 ));
1149 }
1150 for range in &code_ranges {
1151 for rect in range_rects(&layout, range, INLINE_CODE_PAD_X, INLINE_CODE_INSET_Y) {
1152 window.paint_quad(quad(
1153 rect,
1154 px(INLINE_CODE_RADIUS),
1155 wash,
1156 px(0.0),
1157 gpui::transparent_black(),
1158 BorderStyle::default(),
1159 ));
1160 }
1161 }
1162 for range in &chip_ranges {
1165 for rect in range_rects(&layout, range, CHIP_PAD_X, CHIP_INSET_Y) {
1166 window.paint_quad(quad(
1167 rect,
1168 px(Theme::control_radius()),
1169 chip_wash,
1170 px(1.0),
1171 chip_edge,
1172 BorderStyle::Solid,
1173 ));
1174 }
1175 }
1176 },
1177 )
1178 .absolute()
1179 .size_full();
1180
1181 div()
1182 .text_size(px(size))
1183 .line_height(px(line_height))
1184 .relative()
1185 .child(underlay)
1186 .children(hint)
1187 .child(painted)
1188 .into_any_element()
1189}
1190
1191fn caret_quad(head: Point<Pixels>, size: f32, line_height: Pixels) -> Bounds<Pixels> {
1197 let inset = (line_height - px(size)) / 2.0;
1198 Bounds::new(
1199 head + point(px(0.0), inset),
1200 gpui::size(px(CARET_WIDTH), px(size)),
1201 )
1202}
1203
1204fn range_rects(
1206 layout: &gpui::TextLayout,
1207 range: &Range<usize>,
1208 pad_x: f32,
1209 inset_y: f32,
1210) -> Vec<Bounds<Pixels>> {
1211 let mut rects = Vec::new();
1212 let line_height = layout.line_height();
1213 let mut cursor = range.start;
1214 let mut guard = 0;
1217 while cursor < range.end && guard < 256 {
1218 guard += 1;
1219 let Some(head) = layout.position_for_index(cursor) else {
1220 break;
1221 };
1222 let (row_end, next) = match layout.position_for_index(range.end) {
1223 Some(tail) if tail.y == head.y => (range.end, range.end),
1224 _ => {
1225 let (mut low, mut high) = (cursor, range.end);
1226 while high - low > 1 {
1227 let mid = low + (high - low) / 2;
1228 match layout.position_for_index(mid) {
1229 Some(probe) if probe.y == head.y => low = mid,
1230 _ => high = mid,
1231 }
1232 }
1233 (low, high)
1234 }
1235 };
1236 if let Some(tail) = layout.position_for_index(row_end)
1237 && tail.x > head.x
1238 {
1239 rects.push(Bounds::new(
1240 point(head.x - px(pad_x), head.y + px(inset_y)),
1241 size(
1242 tail.x - head.x + px(2.0 * pad_x),
1243 line_height - px(2.0 * inset_y),
1244 ),
1245 ));
1246 }
1247 cursor = next.max(cursor + 1);
1248 }
1249 rects
1250}
1251
1252pub fn render_source(code: &str, editing: Editing, cx: &mut App) -> AnyElement {
1260 let Editing {
1261 selection,
1262 caret_on,
1263 layouts,
1264 annotations,
1265 typography,
1266 ..
1267 } = editing;
1268 let reset = layouts.map(|layouts| {
1272 let layouts = layouts.clone();
1273 canvas(move |_, _, _| layouts.clear(), |_, _, _, _| ())
1274 .absolute()
1275 .size(px(0.0))
1276 });
1277 let theme = Theme::of(cx).clone();
1278 let typography = typography.unwrap_or_else(|| Typography::of(cx));
1279 let overlay = Overlay {
1280 block: 0,
1281 part: Part::Code,
1282 selection,
1283 caret_on,
1284 layouts,
1285 annotations,
1286 placeholder: None,
1287 caption: Caption::default(),
1288 };
1289 let (underlay, lines) = code_lines(
1290 Some(crate::source::LANGUAGES[0]),
1291 code,
1292 overlay,
1293 &typography,
1294 &theme,
1295 cx,
1296 );
1297 let style = crate::SourceStyle::of(cx);
1299 let digits = lines.len().to_string().len().max(style.gutter_min_digits);
1300 let gap = style.gutter_gap.max(0.0) * typography.code.size();
1301 let gutter_width = digits as f32 * typography.code.size() + gap;
1302 let lines = lines
1303 .into_iter()
1304 .enumerate()
1305 .map(|(index, line)| {
1306 if !style.line_numbers {
1307 return line;
1308 }
1309 div()
1310 .flex()
1311 .items_start()
1312 .child(
1313 div()
1314 .w(px(gutter_width))
1315 .flex_shrink_0()
1316 .pr(px(gap))
1317 .font_family(theme.font_mono.clone())
1318 .text_color(style.gutter_color.unwrap_or(theme.text_faint))
1319 .text_right()
1320 .child((index + 1).to_string()),
1321 )
1322 .child(div().flex_1().min_w_0().child(line))
1323 .into_any_element()
1324 })
1325 .collect();
1326 div()
1327 .flex()
1328 .flex_col()
1329 .children(reset)
1330 .child(code_body(0, underlay, lines, &typography, true))
1331 .into_any_element()
1332}
1333
1334fn code_lines(
1337 language: Option<&str>,
1338 code: &str,
1339 overlay: Overlay,
1340 typography: &Typography,
1341 theme: &Theme,
1342 cx: &App,
1343) -> (AnyElement, Vec<AnyElement>) {
1344 let ix = overlay.block;
1345 let spans = crate::highlight::spans(cx, language, code).or_else(|| {
1350 language
1351 .filter(|language| crate::source::is_markdown(language))
1352 .map(|_| crate::source::spans(code))
1353 });
1354 let mono = font(theme.font_mono.clone());
1355 let run = |len: usize, color: Hsla| TextRun {
1356 len,
1357 font: mono.clone(),
1358 color,
1359 background_color: None,
1360 underline: None,
1361 strikethrough: None,
1362 };
1363 let mut rows: Vec<(Range<usize>, TextLayout)> = Vec::new();
1368 let mut offset = 0usize;
1369 let lines: Vec<AnyElement> = code
1370 .split('\n')
1371 .map(|line| {
1372 let start = offset;
1373 offset += line.len() + 1;
1374 let mut runs = Vec::new();
1375 let mut pos = 0usize;
1378 if let Some(spans) = &spans {
1379 let end = start + line.len();
1380 for (range, kind) in spans.iter().filter(|(r, _)| r.end > start && r.start < end) {
1381 let s = range.start.clamp(start, end) - start;
1382 let e = range.end.min(end) - start;
1383 if s > pos {
1384 runs.push(run(s - pos, theme.text));
1385 }
1386 runs.push(run(e - s, theme.syntax.color(*kind)));
1387 pos = e;
1388 }
1389 }
1390 if pos < line.len() {
1391 runs.push(run(line.len() - pos, theme.text));
1392 }
1393 if runs.is_empty() {
1394 runs.push(run(0, theme.text));
1395 }
1396 let styled = StyledText::new(SharedString::from(line.to_string())).with_runs(runs);
1397 rows.push((start..start + line.len(), styled.layout().clone()));
1398 styled.into_any_element()
1399 })
1400 .collect();
1401
1402 let caret = overlay.caret_painted();
1403 let selected = overlay.selected(code.len());
1404 let sink = overlay.layouts.cloned();
1405 let code_size = typography.code.size();
1406 let annotated = overlay.annotated(code.len(), theme);
1407 let (caret_color, selection_color) = (theme.caret, theme.selection);
1408 let underlay = canvas(
1409 |_, _, _| (),
1410 move |_, _, window, _| {
1411 for (span, layout) in &rows {
1412 if let Some(sink) = &sink {
1413 sink.record(ix, Part::Code, span.clone(), layout.clone());
1414 }
1415 for (range, wash) in &annotated {
1416 let (from, to) = (range.start.max(span.start), range.end.min(span.end));
1417 if from < to {
1418 for rect in
1419 range_rects(layout, &(from - span.start..to - span.start), 0.0, 0.0)
1420 {
1421 window.paint_quad(quad(
1422 rect,
1423 px(2.0),
1424 *wash,
1425 px(0.0),
1426 gpui::transparent_black(),
1427 BorderStyle::default(),
1428 ));
1429 }
1430 }
1431 }
1432 if let Some(range) = &selected {
1433 let (from, to) = (range.start.max(span.start), range.end.min(span.end));
1434 if from < to {
1435 for rect in
1436 range_rects(layout, &(from - span.start..to - span.start), 0.0, 0.0)
1437 {
1438 window.paint_quad(quad(
1439 rect,
1440 px(2.0),
1441 selection_color,
1442 px(0.0),
1443 gpui::transparent_black(),
1444 BorderStyle::default(),
1445 ));
1446 }
1447 }
1448 }
1449 if let Some(offset) = caret.filter(|at| span.contains(at) || *at == span.end)
1450 && let Some(head) = layout.position_for_index(offset - span.start)
1451 {
1452 window.paint_quad(quad(
1453 caret_quad(head, code_size, layout.line_height()),
1454 px(0.0),
1455 caret_color,
1456 px(0.0),
1457 gpui::transparent_black(),
1458 BorderStyle::default(),
1459 ));
1460 }
1461 }
1462 },
1463 )
1464 .absolute()
1465 .size_full();
1466
1467 (underlay.into_any_element(), lines)
1468}
1469
1470fn code_block(
1471 language: Option<&str>,
1472 code: &str,
1473 overlay: Overlay,
1474 typography: &Typography,
1475 theme: &Theme,
1476 window: &mut Window,
1477 cx: &mut App,
1478) -> AnyElement {
1479 let ix = overlay.block;
1480 let (underlay, lines) = code_lines(language, code, overlay, typography, theme, cx);
1481 let body = code_body(ix, underlay, lines, typography, Layout::of(cx).wrap_code);
1482
1483 div()
1484 .rounded(px(Theme::panel_radius()))
1485 .bg(theme.ink(0.035))
1486 .border_1()
1487 .border_color(theme.border)
1488 .overflow_hidden()
1489 .relative()
1490 .child(
1494 div()
1495 .relative()
1496 .flex()
1497 .flex_row()
1498 .items_center()
1499 .px(px(CODE_PADDING_X))
1500 .py(px(5.0))
1501 .border_b_1()
1502 .border_color(theme.border)
1503 .bg(theme.ink(0.02))
1504 .text_style(TextStyle::Subheadline)
1505 .text_color(match language {
1506 Some(_) => theme.text_muted,
1507 None => theme.text_faint,
1508 })
1509 .child(
1513 div()
1514 .relative()
1515 .children(overlay.layouts.map(|layouts| {
1516 let layouts = layouts.clone();
1517 canvas(
1518 move |bounds, _, _| layouts.record_language(ix, bounds),
1519 |_, _, _, _| (),
1520 )
1521 .absolute()
1522 .size_full()
1523 }))
1524 .child(SharedString::from(
1525 language.unwrap_or(PLAIN_LANGUAGE).to_string(),
1526 )),
1527 ),
1528 )
1529 .child(body)
1530 .child(copy_button(code, ix, theme, window, cx))
1531 .into_any_element()
1532}
1533
1534fn code_body(
1536 ix: usize,
1537 underlay: AnyElement,
1538 lines: Vec<AnyElement>,
1539 typography: &Typography,
1540 wrap: bool,
1541) -> AnyElement {
1542 let column = div()
1543 .flex()
1544 .flex_col()
1545 .px(px(CODE_PADDING_X))
1546 .children(lines);
1547 let body = div()
1548 .id(ElementId::named_usize("md-code", ix))
1549 .relative()
1550 .py(px(CODE_PADDING_Y))
1551 .text_size(px(typography.code.size()))
1552 .line_height(px(typography.code.line_height()))
1553 .child(underlay);
1554 if wrap {
1555 body.child(column.w_full()).into_any_element()
1558 } else {
1559 ui::scroll::Viewport::new(
1560 format!("md-code-scroll-{ix}"),
1561 body.flex()
1562 .flex_row()
1563 .whitespace_nowrap()
1564 .child(column.items_start()),
1571 gpui::Axis::Horizontal,
1572 )
1573 .into_any_element()
1574 }
1575}
1576
1577fn copy_button(
1584 code: &str,
1585 ix: usize,
1586 theme: &Theme,
1587 window: &mut Window,
1588 cx: &mut App,
1589) -> AnyElement {
1590 let copied = window.use_keyed_state(ElementId::named_usize("md-copied", ix), cx, |_, _| false);
1591 let showing = *copied.read(cx);
1592 let text: SharedString = code.to_string().into();
1593
1594 div()
1595 .id(ElementId::named_usize("md-copy", ix))
1596 .absolute()
1597 .top(px(3.0))
1598 .right(px(5.0))
1599 .h(px(20.0))
1600 .px(px(6.0))
1601 .rounded(px(5.0))
1602 .flex()
1603 .items_center()
1604 .cursor_pointer()
1605 .text_style(TextStyle::Caption)
1606 .text_color(theme.text_muted)
1607 .hover(|el| el.bg(theme.element_hover))
1608 .child(if showing { "Copied" } else { "Copy" })
1609 .on_click({
1610 let copied = copied.clone();
1611 move |_, _, cx| {
1612 cx.write_to_clipboard(gpui::ClipboardItem::new_string(text.to_string()));
1613 copied.update(cx, |state, cx| {
1614 *state = true;
1615 cx.notify();
1616 });
1617 }
1618 })
1619 .on_hover(move |hovering, _, cx| {
1620 if !*hovering && *copied.read(cx) {
1621 copied.update(cx, |state, cx| {
1622 *state = false;
1623 cx.notify();
1624 });
1625 }
1626 })
1627 .into_any_element()
1628}
1629
1630fn image(
1637 url: &str,
1638 alt: &Text,
1639 width: Option<u32>,
1640 overlay: Overlay,
1641 typography: &Typography,
1642 theme: &Theme,
1643 cx: &App,
1644) -> AnyElement {
1645 let hint = SharedString::new_static(CAPTION_HINT);
1646 let overlay = Overlay {
1647 placeholder: Some(&hint),
1648 ..overlay.at(Part::Caption)
1649 };
1650 let picture = if url.is_empty() {
1651 div()
1652 .h(px(IMAGE_EMPTY_HEIGHT))
1653 .flex()
1654 .items_center()
1655 .px(px(CARD_PADDING))
1656 .rounded(px(Theme::button_radius()))
1657 .border_1()
1658 .border_dashed()
1659 .border_color(theme.border)
1660 .text_size(px(typography.body.size()))
1661 .text_color(theme.text_muted)
1662 .child(IMAGE_EMPTY)
1663 } else {
1664 let picture = match url.contains("://") {
1668 true => img(SharedString::from(url.to_string())),
1669 false => img(std::path::PathBuf::from(url)),
1670 };
1671 let box_ = div()
1672 .relative()
1673 .rounded(px(Theme::button_radius()))
1674 .overflow_hidden()
1675 .border_1()
1676 .border_color(theme.border)
1677 .children(overlay.layouts.map(|layouts| {
1678 let layouts = layouts.clone();
1679 let ix = overlay.block;
1680 canvas(
1681 move |bounds, _, _| layouts.record_picture(ix, bounds),
1682 |_, _, _, _| (),
1683 )
1684 .absolute()
1685 .size_full()
1686 }));
1687 match width {
1688 Some(width) => box_
1693 .self_start()
1694 .max_w_full()
1695 .w(px(width as f32))
1696 .child(picture.w(px(width as f32)).max_w_full()),
1697 None => box_.child(picture.max_w_full()),
1700 }
1701 };
1702 div()
1703 .flex()
1704 .flex_col()
1705 .gap(px(CAPTION_GAP))
1706 .child(picture)
1707 .when(
1710 overlay.caption == Caption::Shown && (!alt.is_empty() || overlay.caret().is_some()),
1711 |el| {
1712 el.child(text_element(
1713 alt,
1714 typography.caption.size(),
1715 typography.caption.line_height(),
1716 FontWeight::NORMAL,
1717 overlay,
1718 theme,
1719 cx,
1720 ))
1721 },
1722 )
1723 .into_any_element()
1724}
1725
1726fn bookmark(
1738 ix: usize,
1739 url: &str,
1740 form: Form,
1741 typography: &Typography,
1742 theme: &Theme,
1743 cx: &App,
1744) -> AnyElement {
1745 let preview = preview::of(cx, url).unwrap_or_default();
1746 let host = SharedString::from(preview::host(url).to_string());
1747 let label = preview.label.clone().unwrap_or_else(|| host.clone());
1748 let title = preview
1749 .title
1750 .clone()
1751 .unwrap_or_else(|| SharedString::from(url.to_string()));
1752
1753 let (icon, muted, wash) = (preview.icon.clone(), theme.text_muted, theme.element_hover);
1756 let site = host.clone();
1757 let mark = move |size: f32| {
1758 let host = site.clone();
1759 match icon.clone() {
1760 Some(icon) => img(icon)
1761 .size(px(size))
1762 .rounded(px(size / 4.0))
1763 .with_fallback(move || initial(&host, size, muted, wash))
1764 .into_any_element(),
1765 None => initial(&host, size, muted, wash),
1766 }
1767 };
1768
1769 if form == Form::Chip {
1770 let open = url.to_string();
1771 let pill = div()
1772 .id(ElementId::named_usize("md-chip", ix))
1773 .flex()
1774 .flex_row()
1775 .items_center()
1776 .gap(px(6.0))
1777 .px(px(CHIP_BLOCK_PAD_X))
1778 .py(px(CHIP_BLOCK_PAD_Y))
1779 .rounded(px(Theme::control_radius()))
1780 .border_1()
1781 .border_color(theme.border)
1782 .bg(theme.element_hover)
1783 .text_size(px(typography.body.size()))
1784 .line_height(px(typography.body.line_height()))
1785 .text_color(theme.text)
1786 .cursor(CursorStyle::PointingHand)
1787 .hover(|el| el.bg(theme.element_active))
1788 .on_click(move |_, _, cx| cx.open_url(&open))
1789 .child(mark(CHIP_ICON))
1790 .child(
1793 div()
1794 .min_w_0()
1795 .truncate()
1796 .child(preview.title.unwrap_or(label)),
1797 );
1798 return div().flex().flex_row().child(pill).into_any_element();
1801 }
1802
1803 let words = div()
1804 .flex()
1805 .flex_col()
1806 .min_w_0()
1807 .px(px(CARD_PADDING))
1808 .py(px(CARD_PADDING - 2.0))
1809 .child(
1810 div()
1811 .truncate()
1812 .text_size(px(typography.body.size()))
1813 .line_height(px(typography.body.line_height()))
1814 .text_color(theme.text)
1815 .child(title),
1816 )
1817 .children(preview.description.map(|blurb| {
1818 div()
1819 .line_clamp(2)
1820 .text_size(px(typography.card.size()))
1821 .line_height(px(typography.card.line_height()))
1822 .text_color(theme.text_muted)
1823 .child(blurb)
1824 }))
1825 .child(
1826 div()
1827 .mt_auto()
1828 .pt(px(6.0))
1829 .flex()
1830 .items_center()
1831 .gap(px(6.0))
1832 .text_size(px(typography.card.size()))
1833 .text_color(theme.text_muted)
1834 .child(mark(CARD_ICON))
1835 .child(div().truncate().child(label)),
1836 );
1837
1838 let picture = corners(div(), form)
1839 .bg(theme.surface)
1840 .flex()
1841 .items_center()
1842 .justify_center()
1843 .overflow_hidden()
1844 .child(match preview.image {
1845 Some(image) => corners(img(image).size_full().object_fit(ObjectFit::Cover), form)
1846 .with_fallback(move || mark(CARD_COVER))
1847 .into_any_element(),
1848 None => mark(CARD_COVER),
1849 });
1850
1851 let open = url.to_string();
1852 let card = div()
1853 .id(ElementId::named_usize("md-bookmark", ix))
1854 .flex()
1855 .w_full()
1856 .overflow_hidden()
1857 .rounded(px(Theme::button_radius()))
1858 .border(px(CARD_BORDER))
1859 .border_color(theme.border)
1860 .bg(theme.surface_card)
1861 .cursor(CursorStyle::PointingHand)
1862 .hover(|el| el.bg(theme.element_hover))
1863 .on_click(move |_, _, cx| cx.open_url(&open));
1864
1865 if form == Form::Embed {
1866 card.flex_col()
1867 .child(picture.w_full().h(px(CARD_COVER_HEIGHT)))
1868 .child(words.w_full())
1869 } else {
1870 card.h(px(CARD_HEIGHT))
1871 .child(words.flex_1())
1872 .child(picture.flex_none().w(px(CARD_IMAGE_WIDTH)).h_full())
1873 }
1874 .into_any_element()
1875}
1876
1877fn corners<T: Styled>(element: T, form: Form) -> T {
1881 let corner = px(Theme::inset_radius(Theme::button_radius(), CARD_BORDER));
1882 match form {
1883 Form::Embed => element.rounded_t(corner),
1884 _ => element.rounded_r(corner),
1885 }
1886}
1887
1888fn initial(host: &str, size: f32, color: Hsla, wash: Hsla) -> AnyElement {
1891 div()
1892 .flex_none()
1893 .size(px(size))
1894 .rounded(px(size / 4.0))
1895 .bg(wash)
1896 .flex()
1897 .items_center()
1898 .justify_center()
1899 .text_size(px(size * 0.55))
1900 .text_color(color)
1901 .child(SharedString::from(
1902 host.chars()
1903 .next()
1904 .unwrap_or('?')
1905 .to_uppercase()
1906 .to_string(),
1907 ))
1908 .into_any_element()
1909}
1910
1911#[expect(
1918 clippy::too_many_arguments,
1919 reason = "a table, its overlay, and what paints them"
1920)]
1921fn table(
1922 align: &[Align],
1923 header: &[Text],
1924 rows: &[Vec<Text>],
1925 overlay: Overlay,
1926 typography: &Typography,
1927 theme: &Theme,
1928 window: &mut Window,
1929 cx: &App,
1930) -> AnyElement {
1931 let ix = overlay.block;
1932 let all: Vec<&[Text]> = std::iter::once(header)
1933 .filter(|row| !row.is_empty())
1934 .chain(rows.iter().map(|row| row.as_slice()))
1935 .collect();
1936 let columns = all.iter().map(|row| row.len()).max().unwrap_or(0);
1937 if columns == 0 {
1938 return gpui::Empty.into_any_element();
1939 }
1940 let has_header = !header.is_empty();
1941
1942 let text_system = window.text_system();
1943 let mut flats: Vec<Vec<Option<Flat>>> = Vec::with_capacity(all.len());
1944 let mut content = vec![0.0f32; columns];
1945 for (r, row) in all.iter().enumerate() {
1946 let weight = if has_header && r == 0 {
1947 FontWeight::BOLD
1948 } else {
1949 FontWeight::NORMAL
1950 };
1951 let mut out = Vec::with_capacity(columns);
1952 for (c, natural) in content.iter_mut().enumerate() {
1953 let Some(cell) = row.get(c) else {
1954 out.push(None);
1955 continue;
1956 };
1957 let flat = flatten_with(cell, weight, theme, |name| {
1958 crate::marks::paint_of(cx, name, theme)
1959 });
1960 if !flat.text.is_empty() {
1961 let width = f32::from(
1962 text_system
1963 .shape_line(
1964 flat.text.clone(),
1965 px(typography.body.size()),
1966 &flat.runs,
1967 None,
1968 )
1969 .width(),
1970 );
1971 *natural = natural.max(width);
1972 }
1973 out.push(Some(flat));
1974 }
1975 flats.push(out);
1976 }
1977
1978 let naturals: Vec<f32> = content
1979 .iter()
1980 .map(|width| width.max(TABLE_MIN_COLUMN_CONTENT) + 2.0 * TABLE_CELL_PADDING)
1981 .collect();
1982 let minimums: Vec<f32> = naturals
1983 .iter()
1984 .map(|natural| natural.min(TABLE_MIN_COLUMN_WIDTH))
1985 .collect();
1986 let hairline = theme.hairline(0.10);
1987
1988 let mut inner = div()
1989 .flex()
1990 .flex_col()
1991 .w_full()
1992 .min_w(px(minimums.iter().sum::<f32>()));
1993 for (r, row) in flats.into_iter().enumerate() {
1994 if r > 0 {
1995 inner = inner.child(div().flex_none().h(px(TABLE_DIVIDER)).w_full().bg(hairline));
1996 }
1997 let mut row_el = div().flex().flex_row();
1998 for (c, cell) in row.into_iter().enumerate() {
1999 let mut cell_el = div()
2000 .flex_grow(naturals[c])
2001 .flex_shrink(naturals[c])
2002 .flex_basis(px(0.0))
2003 .min_w(px(minimums[c]))
2004 .p(px(TABLE_CELL_PADDING))
2005 .text_size(px(typography.body.size()))
2006 .line_height(px(typography.body.line_height()));
2007 cell_el = match align.get(c).copied().unwrap_or_default() {
2008 Align::Left => cell_el,
2009 Align::Center => cell_el.text_center(),
2010 Align::Right => cell_el.text_right(),
2011 };
2012 if let Some(flat) = cell {
2013 let row = if has_header { r } else { r + 1 };
2017 let len = flat.text.len();
2018 cell_el = cell_el.child(painted_text(
2019 flat,
2020 len,
2021 typography.body.size(),
2022 typography.body.line_height(),
2023 overlay.at(Part::Cell { row, column: c }),
2024 theme,
2025 ));
2026 }
2027 row_el = row_el.child(cell_el);
2028 }
2029 inner = inner.child(row_el);
2030 }
2031
2032 ui::scroll::Viewport::new(
2033 format!("md-table-scroll-{ix}"),
2034 div()
2035 .id(ElementId::named_usize("md-table", ix))
2036 .w_full()
2037 .child(inner),
2038 gpui::Axis::Horizontal,
2039 )
2040 .into_any_element()
2041}