1use crate::AppExt as _;
11use std::{
12 cell::RefCell,
13 collections::HashMap,
14 hash::{DefaultHasher, Hash, Hasher},
15 ops::Range,
16 path::Path,
17 rc::Rc,
18};
19use ui::AppExt as _;
20use ui::widgets::Layout as _;
21
22use gpui::{
23 AnyElement, App, BorderStyle, Bounds, CursorStyle, ElementId, FontStyle, FontWeight, Hsla,
24 ImageSource, InteractiveText, MouseButton, ObjectFit, Pixels, Point, SharedString,
25 StrikethroughStyle, StyledImage as _, StyledText, TextLayout, TextRun, UnderlineStyle, Window,
26 canvas, div, font, img, point, prelude::*, px, quad, size,
27};
28use theme::{TextStyle, Theme, Typeset};
29
30use crate::{
31 block,
32 doc::{Align, Block, BlockKind, Doc, Form, Mark, Part, QuoteKind, Text},
33 preview,
34 select::{Affinity, Cursor, Selection},
35 typography::Typography,
36};
37
38mod code;
40mod column;
41mod layouts;
42mod media;
43mod table;
44mod text;
45
46pub use code::*;
47use column::*;
48pub use layouts::*;
49use media::*;
50use table::*;
51pub use text::*;
52
53const BLOCK_GAP: f32 = 12.0;
54const LIST_GAP: f32 = 4.0;
55const INDENT_WIDTH: f32 = 22.0;
57const MARKER_WIDTH: f32 = 18.0;
59const MARKER_GAP: f32 = 8.0;
60const CODE_PADDING_X: f32 = 12.0;
62const CODE_PADDING_Y: f32 = 10.0;
63pub const PLAIN_LANGUAGE: &str = "Plain";
66const CARET_WIDTH: f32 = 1.5;
69const INLINE_CODE_RADIUS: f32 = 4.5;
72const INLINE_CODE_PAD_X: f32 = 2.0;
73const INLINE_CODE_INSET_Y: f32 = 2.0;
74const MENTION_CARD_WIDTH: f32 = 320.0;
76const CARD_HEIGHT: f32 = 116.0;
80const CARD_IMAGE_WIDTH: f32 = 180.0;
81const CARD_COVER_HEIGHT: f32 = 200.0;
82const CARD_PADDING: f32 = 14.0;
83const CARD_BORDER: f32 = 1.0;
84const CARD_ICON: f32 = 16.0;
85const CARD_COVER: f32 = 44.0;
86const IMAGE_EMPTY_HEIGHT: f32 = 52.0;
88const CAPTION_GAP: f32 = 4.0;
89const IMAGE_EMPTY: &str = "Add an image";
91const CAPTION_HINT: &str = "Write a caption";
92const TABLE_CELL_PADDING: f32 = 12.0;
95pub const TABLE_CONTROL_SIZE: f32 = 16.0;
97const TABLE_DIVIDER: f32 = 1.0;
98const TABLE_MIN_COLUMN_CONTENT: f32 = 48.0;
101const TABLE_MIN_COLUMN_WIDTH: f32 = 96.0;
103
104#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
115pub enum Caption {
116 #[default]
118 Shown,
119 Hidden,
121}
122
123#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
127pub enum CopyButton {
128 #[default]
130 Shown,
131 Hidden,
134}
135
136#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
142#[non_exhaustive]
143pub enum Annotation {
144 #[default]
146 Open,
147 Resolved,
149 Active,
151 Highlight(crate::HighlightColor),
154 Match,
156 Current,
158}
159
160impl Annotation {
161 fn wash(self, theme: &Theme, highlight: crate::HighlightPaint, find: crate::FindPaint) -> Hsla {
162 match self {
163 Self::Open => theme.warning.opacity(0.20),
164 Self::Resolved => theme.warning.opacity(0.08),
165 Self::Active => theme.warning.opacity(0.38),
166 Self::Highlight(color) => highlight(color, theme),
167 Self::Match => find(theme).0,
168 Self::Current => find(theme).1,
169 }
170 }
171}
172
173pub type OnToggle = Rc<dyn Fn(usize, &mut Window, &mut App)>;
178
179pub type OnImage = Rc<dyn Fn(usize, &mut Window, &mut App)>;
181
182pub type OnJump = Rc<dyn Fn(usize, &mut Window, &mut App)>;
185
186pub type ImageOverlay = Rc<dyn Fn(usize, &str, &mut Window, &mut App) -> Option<AnyElement>>;
188
189pub type OnRewrite = Rc<dyn Fn(usize, String, &mut Window, &mut App)>;
191
192pub type OnLeave = Rc<dyn Fn(usize, &mut Window, &mut App)>;
194
195pub type OnResize = Rc<dyn Fn(usize, Pixels, &mut Window, &mut App)>;
198
199#[derive(Clone)]
202pub struct FenceHost {
203 pub rewrite: OnRewrite,
206 pub leave: OnLeave,
209 pub resize: Option<OnResize>,
212}
213
214pub const PAINTED_CONTEXT: &str = "MarkdownPaintedBlock";
217
218gpui::actions!(
219 markdown,
220 [
221 LeaveBlock
223 ]
224);
225
226#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
228pub enum ImageOverlayCorner {
229 TopLeft,
230 TopRight,
231 BottomLeft,
232 #[default]
233 BottomRight,
234}
235
236#[derive(Clone)]
242pub enum Toggle {
243 Handled(OnToggle),
246 HitTested,
252}
253
254#[derive(Clone)]
260pub struct Editing<'a> {
261 pub selection: Option<Selection>,
264 pub caret_on: bool,
267 pub layouts: Option<&'a BlockLayouts>,
273 pub annotations: &'a [(Selection, Annotation)],
275 pub placeholder: Option<SharedString>,
277 pub caption: Caption,
278 pub typography: Option<Typography>,
282 pub toggle: Option<Toggle>,
285 pub image: Option<OnImage>,
289 pub image_overlay: Option<ImageOverlay>,
292 pub image_overlay_corner: ImageOverlayCorner,
294 pub fence: Option<FenceHost>,
297 pub sizing: Option<(usize, u32)>,
300 pub table_controls: bool,
302 pub copy: CopyButton,
304 pub base: Option<&'a Path>,
307 pub keep: &'a [usize],
312 pub scroll: Option<&'a gpui::ScrollHandle>,
316 pub jump: Option<OnJump>,
320}
321
322impl Default for Editing<'_> {
323 fn default() -> Self {
324 Self {
325 selection: None,
326 caret_on: true,
329 layouts: None,
330 annotations: &[],
331 placeholder: None,
332 caption: Caption::default(),
333 typography: None,
334 toggle: None,
335 image: None,
336 image_overlay: None,
337 image_overlay_corner: ImageOverlayCorner::BottomRight,
338 fence: None,
339 sizing: None,
340 table_controls: false,
341 copy: CopyButton::default(),
342 base: None,
343 keep: &[],
344 scroll: None,
345 jump: None,
346 }
347 }
348}
349
350#[derive(Clone, Copy)]
356struct Overlay<'a> {
357 block: usize,
358 part: Part,
359 selection: Option<Selection>,
360 caret_on: bool,
361 caret_shape: ui::input::CaretShape,
362 caret_height: ui::input::CaretHeight,
363 caret_inactive: ui::input::InactiveCaret,
364 window_active: bool,
366 layouts: Option<&'a BlockLayouts>,
367 annotations: &'a [(Selection, Annotation)],
369 placeholder: Option<&'a SharedString>,
372 caption: Caption,
373 toggle: Option<&'a Toggle>,
376 image: Option<&'a OnImage>,
377 image_overlay: Option<&'a ImageOverlay>,
378 image_overlay_corner: ImageOverlayCorner,
379 fence: Option<&'a FenceHost>,
380 sizing: Option<(usize, u32)>,
381 table_controls: bool,
382 copy: CopyButton,
383 base: Option<&'a Path>,
384 highlight: crate::HighlightPaint,
385 find: crate::FindPaint,
386 jump: Option<&'a crate::link::Jump>,
387}
388
389fn resizable(overlay: &Overlay, theme: &Theme) -> Vec<AnyElement> {
393 let ix = overlay.block;
394 let mut parts = Vec::new();
395 if let Some(layouts) = overlay.layouts {
396 let layouts = layouts.clone();
397 parts.push(
398 canvas(
399 move |bounds, _, _| layouts.record_painted(ix, bounds),
400 |_, _, _, _| (),
401 )
402 .absolute()
403 .size_full()
404 .into_any_element(),
405 );
406 }
407 if let Some(resize) = overlay.fence.and_then(|host| host.resize.clone()) {
408 let dragging = overlay.held_height().is_some();
409 parts.push(
414 div()
415 .absolute()
416 .left_0()
417 .right_0()
418 .bottom_0()
419 .flex()
420 .justify_center()
421 .child(
422 theme
423 .grip_handle()
424 .id(ElementId::named_usize("painted-grip", ix))
425 .debug_selector(|| "painted-grip".into())
426 .w(px(PAINTED_GRIP_WIDTH))
427 .when(!dragging, |el| {
428 el.invisible()
429 .group_hover(painted_group(ix), |el| el.visible())
430 })
431 .on_mouse_down(MouseButton::Left, move |event, window, cx| {
432 cx.stop_propagation();
433 resize(ix, event.position.y, window, cx);
434 }),
435 )
436 .into_any_element(),
437 );
438 }
439 parts
440}
441
442const PAINTED_GRIP_WIDTH: f32 = 120.0;
444
445fn painted_group(ix: usize) -> SharedString {
446 SharedString::from(format!("painted-{ix}"))
447}
448
449impl<'a> Overlay<'a> {
450 fn at(self, part: Part) -> Self {
451 Self { part, ..self }
452 }
453
454 fn held_height(&self) -> Option<u32> {
456 self.sizing
457 .filter(|(ix, _)| *ix == self.block)
458 .map(|(_, height)| height)
459 }
460
461 fn here(&self) -> Cursor {
462 Cursor::new(self.block, self.part, 0)
463 }
464
465 fn caret_painted(&self) -> Option<usize> {
472 let collapsed = self.selection.is_some_and(|s| s.is_collapsed());
473 let shown = self
474 .caret_shape
475 .shown(self.window_active, self.caret_inactive);
476 (self.caret_on && collapsed && shown)
477 .then(|| self.caret())
478 .flatten()
479 }
480
481 fn affinity(&self) -> Affinity {
483 self.selection
484 .map_or_else(Affinity::default, |selection| selection.affinity)
485 }
486
487 fn covered(&self, text: &str, offset: usize) -> Option<Range<usize>> {
490 (self.affinity() == Affinity::Downstream)
491 .then(|| glyph_at(text, offset))
492 .flatten()
493 }
494
495 fn caret_hollow(&self) -> bool {
496 !self.window_active
497 }
498
499 fn caret(&self) -> Option<usize> {
501 self.selection
502 .map(|selection| selection.head)
503 .filter(|head| head.block == self.block && head.part == self.part)
504 .map(|head| head.offset)
505 }
506
507 fn selected(&self, len: usize) -> Option<Range<usize>> {
509 self.clip(self.selection?, len)
510 }
511
512 fn annotated(&self, len: usize, theme: &Theme) -> Vec<(Range<usize>, Hsla)> {
515 self.annotations
516 .iter()
517 .filter_map(|(range, kind)| {
518 Some((
519 self.clip(*range, len)?,
520 kind.wash(theme, self.highlight, self.find),
521 ))
522 })
523 .collect()
524 }
525
526 fn clip(&self, selection: Selection, len: usize) -> Option<Range<usize>> {
532 if selection.is_collapsed() {
533 return None;
534 }
535 let (start, end) = selection.ordered();
536 let here = self.here();
537 let (first, last) = (
538 Cursor::new(start.block, start.part, 0),
539 Cursor::new(end.block, end.part, 0),
540 );
541 if here < first || here > last {
542 return None;
543 }
544 let from = if here == first { start.offset } else { 0 };
545 let to = if here == last { end.offset } else { len };
546 (from < to).then_some(from..to.min(len))
547 }
548
549 fn covers_block(&self) -> bool {
553 let Some(selection) = self.selection.filter(|s| !s.is_collapsed()) else {
554 return false;
555 };
556 let (start, end) = selection.ordered();
557 start.block < self.block && self.block < end.block
558 }
559}
560
561pub fn image_source(url: &str, base: Option<&Path>) -> ImageSource {
567 if url.contains("://") {
568 return SharedString::from(url.to_string()).into();
569 }
570 match base {
573 Some(base) => base.join(url).into(),
574 None => std::path::PathBuf::from(url).into(),
575 }
576}
577
578pub fn markdown(source: &str, window: &mut Window, cx: &mut App) -> AnyElement {
580 let doc = crate::parse_with(source, &cx.marks());
581 render(&doc, Caption::default(), window, cx)
582}
583
584pub fn render(doc: &Doc, caption: Caption, window: &mut Window, cx: &mut App) -> AnyElement {
586 render_with(
587 doc,
588 Editing {
589 caption,
590 ..Editing::default()
591 },
592 window,
593 cx,
594 )
595}
596
597pub fn render_with(doc: &Doc, editing: Editing, window: &mut Window, cx: &mut App) -> AnyElement {
605 let Editing {
606 selection,
607 caret_on,
608 layouts,
609 annotations,
610 placeholder,
611 caption,
612 typography,
613 toggle,
614 image,
615 image_overlay,
616 image_overlay_corner,
617 fence,
618 sizing,
619 table_controls,
620 copy,
621 base,
622 keep,
623 scroll,
624 jump,
625 } = editing;
626 let theme = Theme::of(cx).clone();
629 let typography = typography.unwrap_or_else(|| cx.typography());
630 let highlight = crate::marks::highlight_paint_of(cx);
631 let find = crate::find::find_paint_of(cx);
632 let jump = jump.map(|to| crate::link::Jump::new(doc, to));
633 let gaps: Vec<Pixels> = doc
634 .blocks
635 .iter()
636 .enumerate()
637 .map(|(ix, block)| {
638 px(match doc.blocks.get(ix.wrapping_sub(1)) {
639 None => 0.0,
640 Some(previous) if tight(previous, block) => LIST_GAP,
641 Some(_) => BLOCK_GAP,
642 })
643 })
644 .collect();
645
646 let Some(layouts) = layouts else {
647 let mut column = div().flex().flex_col();
648 for (ix, block) in doc.blocks.iter().enumerate() {
649 let overlay = Overlay {
650 block: ix,
651 part: Part::Body,
652 selection,
653 caret_on,
654 caret_shape: cx.caret_shape(),
655 caret_height: cx.caret_height(),
656 caret_inactive: cx.inactive_caret(),
657 window_active: window.is_window_active(),
658 layouts: None,
659 annotations,
660 placeholder: placeholder.as_ref(),
661 caption,
662 toggle: toggle.as_ref(),
663 image: image.as_ref(),
664 image_overlay: image_overlay.as_ref(),
665 image_overlay_corner,
666 fence: fence.as_ref(),
667 sizing,
668 table_controls,
669 copy,
670 base,
671 highlight,
672 find,
673 jump: jump.as_ref(),
674 };
675 column = column
676 .child(block_box(block, overlay, &typography, &theme, window, cx).mt(gaps[ix]));
677 }
678 return column.into_any_element();
679 };
680
681 let keys: Vec<u64> = doc
682 .blocks
683 .iter()
684 .map(|block| block_key(block, &typography, table_controls))
685 .collect();
686 layouts.prune(&keys);
687 let guesses: Vec<Guess> = doc
688 .blocks
689 .iter()
690 .map(|block| {
691 let mut guess = guess(block, &typography);
692 if table_controls && matches!(block.kind, BlockKind::Table { .. }) {
693 guess.extra += px(2.0 * TABLE_CONTROL_SIZE);
694 }
695 guess
696 })
697 .collect();
698 let mut kept = keep.to_vec();
699 kept.extend(selection.map(|selection| selection.head.block));
700 kept.extend(selection.map(|selection| selection.anchor.block));
701 let owned = Owned {
702 blocks: doc.blocks.clone(),
703 selection,
704 caret_on,
705 layouts: layouts.clone(),
706 annotations: annotations.to_vec(),
707 placeholder,
708 caption,
709 toggle,
710 image,
711 image_overlay,
712 image_overlay_corner,
713 fence,
714 sizing,
715 table_controls,
716 copy,
717 base: base.map(Path::to_path_buf),
718 highlight,
719 find,
720 jump,
721 typography,
722 theme,
723 };
724 Column {
725 layouts: layouts.clone(),
726 keys: keys.into(),
727 gaps: gaps.into(),
728 guesses: guesses.into(),
729 keep: kept,
730 scroll: scroll.cloned(),
731 item_of: Box::new(|at| at.block),
732 build: Box::new(move |ix, window, cx| {
733 let overlay = Overlay {
734 block: ix,
735 part: Part::Body,
736 selection: owned.selection,
737 caret_on: owned.caret_on,
738 caret_shape: cx.caret_shape(),
739 caret_height: cx.caret_height(),
740 caret_inactive: cx.inactive_caret(),
741 window_active: window.is_window_active(),
742 layouts: Some(&owned.layouts),
743 annotations: &owned.annotations,
744 placeholder: owned.placeholder.as_ref(),
745 caption: owned.caption,
746 toggle: owned.toggle.as_ref(),
747 image: owned.image.as_ref(),
748 image_overlay: owned.image_overlay.as_ref(),
749 image_overlay_corner: owned.image_overlay_corner,
750 fence: owned.fence.as_ref(),
751 sizing: owned.sizing,
752 table_controls: owned.table_controls,
753 copy: owned.copy,
754 base: owned.base.as_deref(),
755 highlight: owned.highlight,
756 find: owned.find,
757 jump: owned.jump.as_ref(),
758 };
759 block_box(
760 &owned.blocks[ix],
761 overlay,
762 &owned.typography,
763 &owned.theme,
764 window,
765 cx,
766 )
767 .into_any_element()
768 }),
769 }
770 .into_any_element()
771}
772
773struct Owned {
775 blocks: Vec<Block>,
776 selection: Option<Selection>,
777 caret_on: bool,
778 layouts: BlockLayouts,
779 annotations: Vec<(Selection, Annotation)>,
780 placeholder: Option<SharedString>,
781 caption: Caption,
782 toggle: Option<Toggle>,
783 image: Option<OnImage>,
784 image_overlay: Option<ImageOverlay>,
785 image_overlay_corner: ImageOverlayCorner,
786 fence: Option<FenceHost>,
787 sizing: Option<(usize, u32)>,
788 table_controls: bool,
789 copy: CopyButton,
790 base: Option<std::path::PathBuf>,
791 highlight: crate::HighlightPaint,
792 find: crate::FindPaint,
793 jump: Option<crate::link::Jump>,
794 typography: Typography,
795 theme: Theme,
796}
797
798fn block_box(
801 block: &Block,
802 overlay: Overlay,
803 typography: &Typography,
804 theme: &Theme,
805 window: &mut Window,
806 cx: &mut App,
807) -> gpui::Div {
808 let ix = overlay.block;
809 let frame = overlay.layouts.map(|layouts| {
812 let layouts = layouts.clone();
813 canvas(
814 move |bounds, _, _| layouts.record_block(ix, bounds),
815 |_, _, _, _| (),
816 )
817 .absolute()
818 .size_full()
819 });
820 div()
826 .w_full()
827 .font_family(theme.font_body.clone())
830 .pl(px(block.indent as f32 * INDENT_WIDTH))
831 .child(
832 div()
833 .w_full()
834 .relative()
835 .children(frame)
836 .when(overlay.covers_block() && block.opaque(), |el| {
840 el.rounded(px(4.0)).bg(theme.selection)
841 })
842 .child(block_element(block, overlay, typography, theme, window, cx)),
843 )
844}
845
846fn block_key(block: &Block, typography: &Typography, table_controls: bool) -> u64 {
849 let mut hasher = DefaultHasher::new();
850 table_controls.hash(&mut hasher);
851 block.hash(&mut hasher);
852 typography.body.size().to_bits().hash(&mut hasher);
853 typography.body.line_height().to_bits().hash(&mut hasher);
854 hasher.finish()
855}
856
857fn guess(block: &Block, typography: &Typography) -> Guess {
859 let body = px(typography.body.line_height());
860 let prose = |chars: usize, line: Pixels| Guess {
861 chars,
862 line,
863 rows: 0,
864 extra: px(0.0),
865 indent: px(0.0),
866 };
867 let guess = match &block.kind {
868 BlockKind::Paragraph(text)
869 | BlockKind::Bullet(text)
870 | BlockKind::Ordered { text, .. }
871 | BlockKind::Task { text, .. }
872 | BlockKind::Quote { text, .. } => prose(text.text.len(), body),
873 BlockKind::Heading { level, text } => prose(
874 text.text.len(),
875 px(typography.heading(*level).line_height()),
876 ),
877 BlockKind::Code { code, .. } => Guess {
878 rows: code.text.lines().count().max(1),
879 line: px(typography.code.line_height()),
880 extra: px(2.0 * CODE_PADDING_Y) + body,
881 ..prose(0, body)
882 },
883 BlockKind::Table { rows, .. } => Guess {
884 rows: rows.len() + 1,
885 extra: px(2.0 * TABLE_CELL_PADDING + TABLE_DIVIDER) * (rows.len() + 1) as f32,
886 ..prose(0, body)
887 },
888 BlockKind::Image { alt, .. } => Guess {
889 extra: px(240.0),
890 ..prose(alt.text.len(), px(typography.caption.line_height()))
891 },
892 BlockKind::Bookmark { .. } => Guess {
893 extra: body * 3.0,
894 ..prose(0, body)
895 },
896 BlockKind::Rule => Guess {
897 extra: body,
898 ..prose(0, px(0.0))
899 },
900 };
901 Guess {
902 indent: px(block.indent as f32 * INDENT_WIDTH),
903 ..guess
904 }
905}
906
907fn tight(previous: &Block, next: &Block) -> bool {
909 let marker = |block: &Block| {
910 matches!(
911 block.kind,
912 BlockKind::Bullet(_) | BlockKind::Ordered { .. } | BlockKind::Task { .. }
913 )
914 };
915 marker(previous) && (marker(next) || next.indent > previous.indent)
916}
917
918fn block_element(
919 block: &Block,
920 overlay: Overlay,
921 typography: &Typography,
922 theme: &Theme,
923 window: &mut Window,
924 cx: &mut App,
925) -> AnyElement {
926 let body = overlay.at(Part::Body);
927 match &block.kind {
928 BlockKind::Paragraph(text) => text_element(
929 text,
930 typography.body.size(),
931 typography.body.line_height(),
932 FontWeight::NORMAL,
933 body,
934 theme,
935 cx,
936 ),
937 BlockKind::Heading { level, text } => {
938 let heading = typography.heading(*level);
939 text_element(
940 text,
941 heading.size(),
942 heading.line_height(),
943 heading.weight,
944 body,
945 theme,
946 cx,
947 )
948 }
949 BlockKind::Bullet(text) => {
950 marker_row(disc(typography, theme), text, body, typography, theme, cx)
951 }
952 BlockKind::Ordered { number, text } => marker_row(
953 div()
954 .flex_none()
955 .w(px(MARKER_WIDTH))
956 .text_size(px(typography.body.size()))
957 .line_height(px(typography.body.line_height()))
958 .text_color(theme.text_muted)
959 .child(SharedString::from(format!("{number}.")))
960 .into_any_element(),
961 text,
962 body,
963 typography,
964 theme,
965 cx,
966 ),
967 BlockKind::Task { checked, text } => marker_row(
968 checkbox(*checked, overlay, typography, theme),
969 text,
970 body,
971 typography,
972 theme,
973 cx,
974 ),
975 BlockKind::Quote { kind, text } => div()
976 .border_l_2()
977 .border_color(kind.map_or(theme.border_strong, |kind| alert_color(kind, theme)))
978 .pl(px(12.0))
979 .pr(px(10.0))
980 .py(px(2.0))
981 .text_color(theme.text_muted)
982 .children(kind.map(|kind| {
983 div()
984 .pb(px(2.0))
985 .text_size(px(typography.body.size()))
986 .line_height(px(typography.body.line_height()))
987 .font_weight(FontWeight::SEMIBOLD)
988 .text_color(alert_color(kind, theme))
989 .child(kind.label())
990 }))
991 .child(text_element(
992 text,
993 typography.body.size(),
994 typography.body.line_height(),
995 FontWeight::NORMAL,
996 body,
997 theme,
998 cx,
999 ))
1000 .into_any_element(),
1001 BlockKind::Code {
1002 language,
1003 code,
1004 height,
1005 } => {
1006 let overlay = overlay.at(Part::Code);
1007 let height = overlay.held_height().or(*height);
1008 let painted = overlay
1012 .caret()
1013 .is_none()
1014 .then(|| {
1015 let fence = block::Fence {
1016 language: language.as_deref()?,
1017 code: &code.text,
1018 height,
1019 rewrite: overlay.fence.map(|host| {
1020 let (rewrite, ix) = (host.rewrite.clone(), overlay.block);
1021 Rc::new(move |code: String, window: &mut Window, cx: &mut App| {
1022 rewrite(ix, code, window, cx)
1023 }) as block::Rewrite
1024 }),
1025 };
1026 block::render(&fence, window, cx)
1027 })
1028 .flatten();
1029 match painted {
1030 Some(element) => div()
1033 .key_context(PAINTED_CONTEXT)
1034 .relative()
1035 .when_some(overlay.fence, |el, host| {
1036 let (leave, ix) = (host.leave.clone(), overlay.block);
1037 el.on_action(move |_: &LeaveBlock, window, cx| leave(ix, window, cx))
1038 })
1039 .when(overlay.covers_block(), |el| {
1040 el.rounded(px(4.0)).bg(theme.selection)
1041 })
1042 .group(painted_group(overlay.block))
1043 .child(element)
1044 .children(resizable(&overlay, theme))
1045 .into_any_element(),
1046 None => code_block(
1047 language.as_deref(),
1048 &code.text,
1049 overlay,
1050 typography,
1051 theme,
1052 window,
1053 cx,
1054 ),
1055 }
1056 }
1057 BlockKind::Image { url, alt, width } => {
1058 image(url, alt, *width, overlay, typography, theme, window, cx)
1059 }
1060 BlockKind::Bookmark { url, form } => match crate::preview::card(
1061 url,
1062 match (*form, overlay.held_height()) {
1063 (Form::Embed(_), Some(held)) => Form::Embed(Some(held)),
1064 (form, _) => form,
1065 },
1066 window,
1067 cx,
1068 ) {
1069 Some(element) => div()
1072 .key_context(PAINTED_CONTEXT)
1073 .relative()
1074 .when_some(overlay.fence, |el, host| {
1075 let (leave, ix) = (host.leave.clone(), overlay.block);
1076 el.on_action(move |_: &LeaveBlock, window, cx| leave(ix, window, cx))
1077 })
1078 .when(overlay.covers_block(), |el| {
1079 el.rounded(px(4.0)).bg(theme.selection)
1080 })
1081 .group(painted_group(overlay.block))
1082 .child(element)
1083 .children(match form {
1084 Form::Embed(_) => resizable(&overlay, theme),
1085 _ => Vec::new(),
1086 })
1087 .into_any_element(),
1088 None => bookmark(overlay.block, url, *form, typography, theme, cx),
1089 },
1090 BlockKind::Table {
1091 align,
1092 header,
1093 rows,
1094 } => table(align, header, rows, overlay, typography, theme, window, cx),
1095 BlockKind::Rule => div()
1096 .h(px(1.0))
1097 .w_full()
1098 .bg(theme.border)
1099 .into_any_element(),
1100 }
1101}
1102
1103fn disc(typography: &Typography, theme: &Theme) -> AnyElement {
1105 div()
1106 .flex_none()
1107 .w(px(MARKER_WIDTH))
1108 .h(px(typography.body.line_height()))
1109 .flex()
1110 .items_center()
1111 .child(
1112 div()
1113 .ml(px(1.0))
1114 .w(px(5.0))
1115 .h(px(5.0))
1116 .rounded_full()
1117 .bg(theme.text_faint),
1118 )
1119 .into_any_element()
1120}
1121
1122fn checkbox(checked: bool, overlay: Overlay, typography: &Typography, theme: &Theme) -> AnyElement {
1123 let ix = overlay.block;
1124 let mut box_ = div()
1125 .relative()
1126 .w(px(13.0))
1127 .h(px(13.0))
1128 .rounded(px(3.5))
1129 .border_1()
1130 .flex()
1131 .items_center()
1132 .justify_center();
1133 box_ = if checked {
1134 box_.bg(theme.solid)
1135 .border_color(theme.solid)
1136 .text_style(TextStyle::Caption)
1137 .text_color(theme.on_solid)
1138 .child("✓")
1139 } else {
1140 box_.border_color(theme.border_strong)
1141 };
1142 box_ = box_.children(overlay.layouts.map(|layouts| {
1145 let layouts = layouts.clone();
1146 canvas(
1147 move |bounds, _, _| layouts.record_checkbox(ix, bounds),
1148 |_, _, _, _| (),
1149 )
1150 .absolute()
1151 .size_full()
1152 }));
1153 if overlay.toggle.is_some() {
1156 box_ = box_.cursor_pointer();
1157 }
1158 if let Some(Toggle::Handled(toggle)) = overlay.toggle.cloned() {
1159 box_ = box_.on_mouse_down(MouseButton::Left, move |_, window, cx| {
1160 cx.stop_propagation();
1164 toggle(ix, window, cx);
1165 });
1166 }
1167
1168 div()
1169 .flex_none()
1170 .w(px(MARKER_WIDTH))
1171 .h(px(typography.body.line_height()))
1172 .flex()
1173 .items_center()
1174 .child(box_)
1175 .into_any_element()
1176}
1177
1178fn alert_color(kind: QuoteKind, theme: &Theme) -> Hsla {
1180 match kind {
1181 QuoteKind::Note => theme.accent,
1182 QuoteKind::Tip => theme.success,
1183 QuoteKind::Important => theme.busy,
1184 QuoteKind::Warning => theme.warning,
1185 QuoteKind::Caution => theme.danger,
1186 }
1187}
1188
1189fn marker_row(
1190 marker: AnyElement,
1191 text: &Text,
1192 overlay: Overlay,
1193 typography: &Typography,
1194 theme: &Theme,
1195 cx: &App,
1196) -> AnyElement {
1197 div()
1198 .flex()
1199 .flex_row()
1200 .gap(px(MARKER_GAP))
1201 .child(marker)
1202 .child(div().flex_auto().min_w_0().child(text_element(
1203 text,
1204 typography.body.size(),
1205 typography.body.line_height(),
1206 FontWeight::NORMAL,
1207 overlay,
1208 theme,
1209 cx,
1210 )))
1211 .into_any_element()
1212}