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 div()
1298 .flex()
1299 .flex_col()
1300 .children(reset)
1301 .child(code_body(0, underlay, lines, &typography, true))
1302 .into_any_element()
1303}
1304
1305fn code_lines(
1308 language: Option<&str>,
1309 code: &str,
1310 overlay: Overlay,
1311 typography: &Typography,
1312 theme: &Theme,
1313 cx: &App,
1314) -> (AnyElement, Vec<AnyElement>) {
1315 let ix = overlay.block;
1316 let spans = crate::highlight::spans(cx, language, code).or_else(|| {
1321 language
1322 .filter(|language| crate::source::is_markdown(language))
1323 .map(|_| crate::source::spans(code))
1324 });
1325 let mono = font(theme.font_mono.clone());
1326 let run = |len: usize, color: Hsla| TextRun {
1327 len,
1328 font: mono.clone(),
1329 color,
1330 background_color: None,
1331 underline: None,
1332 strikethrough: None,
1333 };
1334 let mut rows: Vec<(Range<usize>, TextLayout)> = Vec::new();
1339 let mut offset = 0usize;
1340 let lines: Vec<AnyElement> = code
1341 .split('\n')
1342 .map(|line| {
1343 let start = offset;
1344 offset += line.len() + 1;
1345 let mut runs = Vec::new();
1346 let mut pos = 0usize;
1349 if let Some(spans) = &spans {
1350 let end = start + line.len();
1351 for (range, kind) in spans.iter().filter(|(r, _)| r.end > start && r.start < end) {
1352 let s = range.start.clamp(start, end) - start;
1353 let e = range.end.min(end) - start;
1354 if s > pos {
1355 runs.push(run(s - pos, theme.text));
1356 }
1357 runs.push(run(e - s, theme.syntax.color(*kind)));
1358 pos = e;
1359 }
1360 }
1361 if pos < line.len() {
1362 runs.push(run(line.len() - pos, theme.text));
1363 }
1364 if runs.is_empty() {
1365 runs.push(run(0, theme.text));
1366 }
1367 let styled = StyledText::new(SharedString::from(line.to_string())).with_runs(runs);
1368 rows.push((start..start + line.len(), styled.layout().clone()));
1369 styled.into_any_element()
1370 })
1371 .collect();
1372
1373 let caret = overlay.caret_painted();
1374 let selected = overlay.selected(code.len());
1375 let sink = overlay.layouts.cloned();
1376 let code_size = typography.code.size();
1377 let annotated = overlay.annotated(code.len(), theme);
1378 let (caret_color, selection_color) = (theme.caret, theme.selection);
1379 let underlay = canvas(
1380 |_, _, _| (),
1381 move |_, _, window, _| {
1382 for (span, layout) in &rows {
1383 if let Some(sink) = &sink {
1384 sink.record(ix, Part::Code, span.clone(), layout.clone());
1385 }
1386 for (range, wash) in &annotated {
1387 let (from, to) = (range.start.max(span.start), range.end.min(span.end));
1388 if from < to {
1389 for rect in
1390 range_rects(layout, &(from - span.start..to - span.start), 0.0, 0.0)
1391 {
1392 window.paint_quad(quad(
1393 rect,
1394 px(2.0),
1395 *wash,
1396 px(0.0),
1397 gpui::transparent_black(),
1398 BorderStyle::default(),
1399 ));
1400 }
1401 }
1402 }
1403 if let Some(range) = &selected {
1404 let (from, to) = (range.start.max(span.start), range.end.min(span.end));
1405 if from < to {
1406 for rect in
1407 range_rects(layout, &(from - span.start..to - span.start), 0.0, 0.0)
1408 {
1409 window.paint_quad(quad(
1410 rect,
1411 px(2.0),
1412 selection_color,
1413 px(0.0),
1414 gpui::transparent_black(),
1415 BorderStyle::default(),
1416 ));
1417 }
1418 }
1419 }
1420 if let Some(offset) = caret.filter(|at| span.contains(at) || *at == span.end)
1421 && let Some(head) = layout.position_for_index(offset - span.start)
1422 {
1423 window.paint_quad(quad(
1424 caret_quad(head, code_size, layout.line_height()),
1425 px(0.0),
1426 caret_color,
1427 px(0.0),
1428 gpui::transparent_black(),
1429 BorderStyle::default(),
1430 ));
1431 }
1432 }
1433 },
1434 )
1435 .absolute()
1436 .size_full();
1437
1438 (underlay.into_any_element(), lines)
1439}
1440
1441fn code_block(
1442 language: Option<&str>,
1443 code: &str,
1444 overlay: Overlay,
1445 typography: &Typography,
1446 theme: &Theme,
1447 window: &mut Window,
1448 cx: &mut App,
1449) -> AnyElement {
1450 let ix = overlay.block;
1451 let (underlay, lines) = code_lines(language, code, overlay, typography, theme, cx);
1452 let body = code_body(ix, underlay, lines, typography, Layout::of(cx).wrap_code);
1453
1454 div()
1455 .rounded(px(Theme::panel_radius()))
1456 .bg(theme.ink(0.035))
1457 .border_1()
1458 .border_color(theme.border)
1459 .overflow_hidden()
1460 .relative()
1461 .child(
1465 div()
1466 .relative()
1467 .flex()
1468 .flex_row()
1469 .items_center()
1470 .px(px(CODE_PADDING_X))
1471 .py(px(5.0))
1472 .border_b_1()
1473 .border_color(theme.border)
1474 .bg(theme.ink(0.02))
1475 .text_style(TextStyle::Subheadline)
1476 .text_color(match language {
1477 Some(_) => theme.text_muted,
1478 None => theme.text_faint,
1479 })
1480 .child(
1484 div()
1485 .relative()
1486 .children(overlay.layouts.map(|layouts| {
1487 let layouts = layouts.clone();
1488 canvas(
1489 move |bounds, _, _| layouts.record_language(ix, bounds),
1490 |_, _, _, _| (),
1491 )
1492 .absolute()
1493 .size_full()
1494 }))
1495 .child(SharedString::from(
1496 language.unwrap_or(PLAIN_LANGUAGE).to_string(),
1497 )),
1498 ),
1499 )
1500 .child(body)
1501 .child(copy_button(code, ix, theme, window, cx))
1502 .into_any_element()
1503}
1504
1505fn code_body(
1507 ix: usize,
1508 underlay: AnyElement,
1509 lines: Vec<AnyElement>,
1510 typography: &Typography,
1511 wrap: bool,
1512) -> gpui::Stateful<gpui::Div> {
1513 let column = div()
1514 .flex()
1515 .flex_col()
1516 .px(px(CODE_PADDING_X))
1517 .children(lines);
1518 let body = div()
1519 .id(ElementId::named_usize("md-code", ix))
1520 .relative()
1521 .py(px(CODE_PADDING_Y))
1522 .text_size(px(typography.code.size()))
1523 .line_height(px(typography.code.line_height()))
1524 .child(underlay);
1525 if wrap {
1526 body.child(column.w_full())
1529 } else {
1530 contain_sideways(body)
1531 .overflow_x_scroll()
1532 .restrict_scroll_to_axis()
1536 .flex()
1537 .flex_row()
1538 .whitespace_nowrap()
1539 .child(column.items_start())
1546 }
1547}
1548
1549fn copy_button(
1556 code: &str,
1557 ix: usize,
1558 theme: &Theme,
1559 window: &mut Window,
1560 cx: &mut App,
1561) -> AnyElement {
1562 let copied = window.use_keyed_state(ElementId::named_usize("md-copied", ix), cx, |_, _| false);
1563 let showing = *copied.read(cx);
1564 let text: SharedString = code.to_string().into();
1565
1566 div()
1567 .id(ElementId::named_usize("md-copy", ix))
1568 .absolute()
1569 .top(px(3.0))
1570 .right(px(5.0))
1571 .h(px(20.0))
1572 .px(px(6.0))
1573 .rounded(px(5.0))
1574 .flex()
1575 .items_center()
1576 .cursor_pointer()
1577 .text_style(TextStyle::Caption)
1578 .text_color(theme.text_muted)
1579 .hover(|el| el.bg(theme.element_hover))
1580 .child(if showing { "Copied" } else { "Copy" })
1581 .on_click({
1582 let copied = copied.clone();
1583 move |_, _, cx| {
1584 cx.write_to_clipboard(gpui::ClipboardItem::new_string(text.to_string()));
1585 copied.update(cx, |state, cx| {
1586 *state = true;
1587 cx.notify();
1588 });
1589 }
1590 })
1591 .on_hover(move |hovering, _, cx| {
1592 if !*hovering && *copied.read(cx) {
1593 copied.update(cx, |state, cx| {
1594 *state = false;
1595 cx.notify();
1596 });
1597 }
1598 })
1599 .into_any_element()
1600}
1601
1602fn image(
1609 url: &str,
1610 alt: &Text,
1611 width: Option<u32>,
1612 overlay: Overlay,
1613 typography: &Typography,
1614 theme: &Theme,
1615 cx: &App,
1616) -> AnyElement {
1617 let hint = SharedString::new_static(CAPTION_HINT);
1618 let overlay = Overlay {
1619 placeholder: Some(&hint),
1620 ..overlay.at(Part::Caption)
1621 };
1622 let picture = if url.is_empty() {
1623 div()
1624 .h(px(IMAGE_EMPTY_HEIGHT))
1625 .flex()
1626 .items_center()
1627 .px(px(CARD_PADDING))
1628 .rounded(px(Theme::button_radius()))
1629 .border_1()
1630 .border_dashed()
1631 .border_color(theme.border)
1632 .text_size(px(typography.body.size()))
1633 .text_color(theme.text_muted)
1634 .child(IMAGE_EMPTY)
1635 } else {
1636 let picture = match url.contains("://") {
1640 true => img(SharedString::from(url.to_string())),
1641 false => img(std::path::PathBuf::from(url)),
1642 };
1643 let box_ = div()
1644 .relative()
1645 .rounded(px(Theme::button_radius()))
1646 .overflow_hidden()
1647 .border_1()
1648 .border_color(theme.border)
1649 .children(overlay.layouts.map(|layouts| {
1650 let layouts = layouts.clone();
1651 let ix = overlay.block;
1652 canvas(
1653 move |bounds, _, _| layouts.record_picture(ix, bounds),
1654 |_, _, _, _| (),
1655 )
1656 .absolute()
1657 .size_full()
1658 }));
1659 match width {
1660 Some(width) => box_
1665 .self_start()
1666 .max_w_full()
1667 .w(px(width as f32))
1668 .child(picture.w(px(width as f32)).max_w_full()),
1669 None => box_.child(picture.max_w_full()),
1672 }
1673 };
1674 div()
1675 .flex()
1676 .flex_col()
1677 .gap(px(CAPTION_GAP))
1678 .child(picture)
1679 .when(
1682 overlay.caption == Caption::Shown && (!alt.is_empty() || overlay.caret().is_some()),
1683 |el| {
1684 el.child(text_element(
1685 alt,
1686 typography.caption.size(),
1687 typography.caption.line_height(),
1688 FontWeight::NORMAL,
1689 overlay,
1690 theme,
1691 cx,
1692 ))
1693 },
1694 )
1695 .into_any_element()
1696}
1697
1698fn bookmark(
1710 ix: usize,
1711 url: &str,
1712 form: Form,
1713 typography: &Typography,
1714 theme: &Theme,
1715 cx: &App,
1716) -> AnyElement {
1717 let preview = preview::of(cx, url).unwrap_or_default();
1718 let host = SharedString::from(preview::host(url).to_string());
1719 let label = preview.label.clone().unwrap_or_else(|| host.clone());
1720 let title = preview
1721 .title
1722 .clone()
1723 .unwrap_or_else(|| SharedString::from(url.to_string()));
1724
1725 let (icon, muted, wash) = (preview.icon.clone(), theme.text_muted, theme.element_hover);
1728 let site = host.clone();
1729 let mark = move |size: f32| {
1730 let host = site.clone();
1731 match icon.clone() {
1732 Some(icon) => img(icon)
1733 .size(px(size))
1734 .rounded(px(size / 4.0))
1735 .with_fallback(move || initial(&host, size, muted, wash))
1736 .into_any_element(),
1737 None => initial(&host, size, muted, wash),
1738 }
1739 };
1740
1741 if form == Form::Chip {
1742 let open = url.to_string();
1743 let pill = div()
1744 .id(ElementId::named_usize("md-chip", ix))
1745 .flex()
1746 .flex_row()
1747 .items_center()
1748 .gap(px(6.0))
1749 .px(px(CHIP_BLOCK_PAD_X))
1750 .py(px(CHIP_BLOCK_PAD_Y))
1751 .rounded(px(Theme::control_radius()))
1752 .border_1()
1753 .border_color(theme.border)
1754 .bg(theme.element_hover)
1755 .text_size(px(typography.body.size()))
1756 .line_height(px(typography.body.line_height()))
1757 .text_color(theme.text)
1758 .cursor(CursorStyle::PointingHand)
1759 .hover(|el| el.bg(theme.element_active))
1760 .on_click(move |_, _, cx| cx.open_url(&open))
1761 .child(mark(CHIP_ICON))
1762 .child(
1765 div()
1766 .min_w_0()
1767 .truncate()
1768 .child(preview.title.unwrap_or(label)),
1769 );
1770 return div().flex().flex_row().child(pill).into_any_element();
1773 }
1774
1775 let words = div()
1776 .flex()
1777 .flex_col()
1778 .min_w_0()
1779 .px(px(CARD_PADDING))
1780 .py(px(CARD_PADDING - 2.0))
1781 .child(
1782 div()
1783 .truncate()
1784 .text_size(px(typography.body.size()))
1785 .line_height(px(typography.body.line_height()))
1786 .text_color(theme.text)
1787 .child(title),
1788 )
1789 .children(preview.description.map(|blurb| {
1790 div()
1791 .line_clamp(2)
1792 .text_size(px(typography.card.size()))
1793 .line_height(px(typography.card.line_height()))
1794 .text_color(theme.text_muted)
1795 .child(blurb)
1796 }))
1797 .child(
1798 div()
1799 .mt_auto()
1800 .pt(px(6.0))
1801 .flex()
1802 .items_center()
1803 .gap(px(6.0))
1804 .text_size(px(typography.card.size()))
1805 .text_color(theme.text_muted)
1806 .child(mark(CARD_ICON))
1807 .child(div().truncate().child(label)),
1808 );
1809
1810 let picture = corners(div(), form)
1811 .bg(theme.surface)
1812 .flex()
1813 .items_center()
1814 .justify_center()
1815 .overflow_hidden()
1816 .child(match preview.image {
1817 Some(image) => corners(img(image).size_full().object_fit(ObjectFit::Cover), form)
1818 .with_fallback(move || mark(CARD_COVER))
1819 .into_any_element(),
1820 None => mark(CARD_COVER),
1821 });
1822
1823 let open = url.to_string();
1824 let card = div()
1825 .id(ElementId::named_usize("md-bookmark", ix))
1826 .flex()
1827 .w_full()
1828 .overflow_hidden()
1829 .rounded(px(Theme::button_radius()))
1830 .border(px(CARD_BORDER))
1831 .border_color(theme.border)
1832 .bg(theme.surface_card)
1833 .cursor(CursorStyle::PointingHand)
1834 .hover(|el| el.bg(theme.element_hover))
1835 .on_click(move |_, _, cx| cx.open_url(&open));
1836
1837 if form == Form::Embed {
1838 card.flex_col()
1839 .child(picture.w_full().h(px(CARD_COVER_HEIGHT)))
1840 .child(words.w_full())
1841 } else {
1842 card.h(px(CARD_HEIGHT))
1843 .child(words.flex_1())
1844 .child(picture.flex_none().w(px(CARD_IMAGE_WIDTH)).h_full())
1845 }
1846 .into_any_element()
1847}
1848
1849fn corners<T: Styled>(element: T, form: Form) -> T {
1853 let corner = px(Theme::inset_radius(Theme::button_radius(), CARD_BORDER));
1854 match form {
1855 Form::Embed => element.rounded_t(corner),
1856 _ => element.rounded_r(corner),
1857 }
1858}
1859
1860fn initial(host: &str, size: f32, color: Hsla, wash: Hsla) -> AnyElement {
1863 div()
1864 .flex_none()
1865 .size(px(size))
1866 .rounded(px(size / 4.0))
1867 .bg(wash)
1868 .flex()
1869 .items_center()
1870 .justify_center()
1871 .text_size(px(size * 0.55))
1872 .text_color(color)
1873 .child(SharedString::from(
1874 host.chars()
1875 .next()
1876 .unwrap_or('?')
1877 .to_uppercase()
1878 .to_string(),
1879 ))
1880 .into_any_element()
1881}
1882
1883#[expect(
1890 clippy::too_many_arguments,
1891 reason = "a table, its overlay, and what paints them"
1892)]
1893fn table(
1894 align: &[Align],
1895 header: &[Text],
1896 rows: &[Vec<Text>],
1897 overlay: Overlay,
1898 typography: &Typography,
1899 theme: &Theme,
1900 window: &mut Window,
1901 cx: &App,
1902) -> AnyElement {
1903 let ix = overlay.block;
1904 let all: Vec<&[Text]> = std::iter::once(header)
1905 .filter(|row| !row.is_empty())
1906 .chain(rows.iter().map(|row| row.as_slice()))
1907 .collect();
1908 let columns = all.iter().map(|row| row.len()).max().unwrap_or(0);
1909 if columns == 0 {
1910 return gpui::Empty.into_any_element();
1911 }
1912 let has_header = !header.is_empty();
1913
1914 let text_system = window.text_system();
1915 let mut flats: Vec<Vec<Option<Flat>>> = Vec::with_capacity(all.len());
1916 let mut content = vec![0.0f32; columns];
1917 for (r, row) in all.iter().enumerate() {
1918 let weight = if has_header && r == 0 {
1919 FontWeight::BOLD
1920 } else {
1921 FontWeight::NORMAL
1922 };
1923 let mut out = Vec::with_capacity(columns);
1924 for (c, natural) in content.iter_mut().enumerate() {
1925 let Some(cell) = row.get(c) else {
1926 out.push(None);
1927 continue;
1928 };
1929 let flat = flatten_with(cell, weight, theme, |name| {
1930 crate::marks::paint_of(cx, name, theme)
1931 });
1932 if !flat.text.is_empty() {
1933 let width = f32::from(
1934 text_system
1935 .shape_line(
1936 flat.text.clone(),
1937 px(typography.body.size()),
1938 &flat.runs,
1939 None,
1940 )
1941 .width(),
1942 );
1943 *natural = natural.max(width);
1944 }
1945 out.push(Some(flat));
1946 }
1947 flats.push(out);
1948 }
1949
1950 let naturals: Vec<f32> = content
1951 .iter()
1952 .map(|width| width.max(TABLE_MIN_COLUMN_CONTENT) + 2.0 * TABLE_CELL_PADDING)
1953 .collect();
1954 let minimums: Vec<f32> = naturals
1955 .iter()
1956 .map(|natural| natural.min(TABLE_MIN_COLUMN_WIDTH))
1957 .collect();
1958 let hairline = theme.hairline(0.10);
1959
1960 let mut inner = div()
1961 .flex()
1962 .flex_col()
1963 .w_full()
1964 .min_w(px(minimums.iter().sum::<f32>()));
1965 for (r, row) in flats.into_iter().enumerate() {
1966 if r > 0 {
1967 inner = inner.child(div().flex_none().h(px(TABLE_DIVIDER)).w_full().bg(hairline));
1968 }
1969 let mut row_el = div().flex().flex_row();
1970 for (c, cell) in row.into_iter().enumerate() {
1971 let mut cell_el = div()
1972 .flex_grow(naturals[c])
1973 .flex_shrink(naturals[c])
1974 .flex_basis(px(0.0))
1975 .min_w(px(minimums[c]))
1976 .p(px(TABLE_CELL_PADDING))
1977 .text_size(px(typography.body.size()))
1978 .line_height(px(typography.body.line_height()));
1979 cell_el = match align.get(c).copied().unwrap_or_default() {
1980 Align::Left => cell_el,
1981 Align::Center => cell_el.text_center(),
1982 Align::Right => cell_el.text_right(),
1983 };
1984 if let Some(flat) = cell {
1985 let row = if has_header { r } else { r + 1 };
1989 let len = flat.text.len();
1990 cell_el = cell_el.child(painted_text(
1991 flat,
1992 len,
1993 typography.body.size(),
1994 typography.body.line_height(),
1995 overlay.at(Part::Cell { row, column: c }),
1996 theme,
1997 ));
1998 }
1999 row_el = row_el.child(cell_el);
2000 }
2001 inner = inner.child(row_el);
2002 }
2003
2004 contain_sideways(div().id(ElementId::named_usize("md-table", ix)))
2005 .w_full()
2006 .overflow_x_scroll()
2007 .restrict_scroll_to_axis()
2008 .child(inner)
2009 .into_any_element()
2010}
2011
2012fn contain_sideways<E: gpui::InteractiveElement>(el: E) -> E {
2030 el.on_scroll_wheel(|event, window, cx| {
2031 let delta = event.delta.pixel_delta(window.line_height());
2032 if delta.x.abs() > delta.y.abs() {
2036 cx.stop_propagation();
2037 }
2038 })
2039}