use crate::{
components::{
CopyButton,
inline_code::{box_height, inline_code_fill, push_inline_code, with_code_boxes},
},
icons::{CarbonIcon, Icon},
t3::craft::{mono, rem, sans},
theme::{LayerLevel, color},
tokens::{self, ColorRole, FontFamilyKey},
typography::font,
u0::{
panels::head::{code_head, grow, head_icon},
primitives::{
IconButton,
parts::{flash, flash_on, flash_state},
},
},
};
use gpui_kit::{
AnyElement, App, ClipboardItem, Div, ElementId, Font, FontStyle, FontWeight, Hsla,
InteractiveElement as _, IntoElement, ParentElement, RenderOnce, SharedString,
StatefulInteractiveElement as _, Styled, StyledText, TextAlign, TextRun, UnderlineStyle,
Window, canvas, div, point, prelude::FluentBuilder as _, px,
};
use std::ops::Range;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Inline {
Text(SharedString),
Code(SharedString),
Strong(SharedString),
Em(SharedString),
Link(SharedString, SharedString),
FootnoteRef(SharedString),
Math(SharedString),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ListItem {
pub content: Vec<Inline>,
pub children: Vec<Block>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Block {
Heading(u8, Vec<Inline>),
Paragraph(Vec<Inline>),
List {
ordered: bool,
start: usize,
items: Vec<ListItem>,
},
TaskList(Vec<(bool, Vec<Inline>)>),
Quote(Vec<Inline>),
Table(Vec<Vec<Inline>>, Vec<Vec<Vec<Inline>>>),
Rule,
Code {
language: SharedString,
code: SharedString,
},
Math(SharedString),
Mermaid(SharedString),
Footnotes(Vec<Vec<Inline>>),
}
pub fn parse_inlines(s: &str) -> Vec<Inline> {
let mut out = Vec::new();
let mut text = String::new();
let mut i = 0;
let flush = |text: &mut String, out: &mut Vec<Inline>| {
if !text.is_empty() {
out.push(Inline::Text(std::mem::take(text).into()));
}
};
while i < s.len() {
let rest = &s[i..];
let closed = |open: &str, close: &str| -> Option<(usize, &str)> {
let body = rest.strip_prefix(open)?;
let end = body.find(close)?;
(end > 0).then(|| (open.len() + end + close.len(), &body[..end]))
};
let token = if let Some((n, b)) = closed("`", "`") {
Some((n, Inline::Code(b.to_string().into())))
} else if let Some((n, b)) = closed("**", "**") {
Some((n, Inline::Strong(b.to_string().into())))
} else if let Some((n, b)) = closed("[^", "]") {
Some((n, Inline::FootnoteRef(b.to_string().into())))
} else if let Some((n, b)) = closed("$", "$") {
Some((n, Inline::Math(b.to_string().into())))
} else if let Some((n, b)) = closed("*", "*").or_else(|| closed("_", "_")) {
Some((n, Inline::Em(b.to_string().into())))
} else if rest.starts_with('[') {
rest.find("](").and_then(|mid| {
let tail = &rest[mid + 2..];
tail.find(')').map(|end| {
(
mid + 2 + end + 1,
Inline::Link(
rest[1..mid].to_string().into(),
tail[..end].to_string().into(),
),
)
})
})
} else {
None
};
match token {
Some((n, inline)) => {
flush(&mut text, &mut out);
out.push(inline);
i += n;
}
None => {
let c = rest.chars().next().unwrap_or_default();
text.push(c);
i += c.len_utf8();
}
}
}
flush(&mut text, &mut out);
out
}
fn list_line(line: &str) -> Option<(usize, bool, usize, Option<bool>, &str)> {
let indent = line.len() - line.trim_start().len();
let t = line.trim_start();
let (ordered, number, rest) = if let Some(r) = t
.strip_prefix("- ")
.or_else(|| t.strip_prefix("* "))
.or_else(|| t.strip_prefix("+ "))
{
(false, 1, r)
} else {
let digits: String = t.chars().take_while(|c| c.is_ascii_digit()).collect();
let r = t[digits.len()..].strip_prefix(". ")?;
(true, digits.parse().ok()?, r)
};
let (task, rest) = if let Some(r) = rest.strip_prefix("[ ] ") {
(Some(false), r)
} else if let Some(r) = rest
.strip_prefix("[x] ")
.or_else(|| rest.strip_prefix("[X] "))
{
(Some(true), r)
} else {
(None, rest)
};
Some((indent, ordered, number, task, rest))
}
fn build_list(lines: &[(usize, bool, usize, Option<bool>, String)]) -> Block {
if lines.iter().all(|l| l.3.is_some()) {
return Block::TaskList(
lines
.iter()
.map(|l| (l.3.unwrap_or(false), parse_inlines(&l.4)))
.collect(),
);
}
let base = lines[0].0;
let mut items: Vec<ListItem> = Vec::new();
let mut i = 0;
while i < lines.len() {
let (_, _, _, _, text) = &lines[i];
let mut j = i + 1;
while j < lines.len() && lines[j].0 > base {
j += 1;
}
let children = if j > i + 1 {
vec![build_list(&lines[i + 1..j])]
} else {
Vec::new()
};
items.push(ListItem {
content: parse_inlines(text),
children,
});
i = j;
}
Block::List {
ordered: lines[0].1,
start: lines[0].2,
items,
}
}
fn table_cells(line: &str) -> Vec<Vec<Inline>> {
line.trim()
.trim_start_matches('|')
.trim_end_matches('|')
.split('|')
.map(|c| parse_inlines(c.trim()))
.collect()
}
pub fn parse_markdown(src: &str) -> Vec<Block> {
let lines: Vec<&str> = src.lines().collect();
let mut blocks = Vec::new();
let mut notes: Vec<Vec<Inline>> = Vec::new();
let mut para: Vec<&str> = Vec::new();
let flush = |para: &mut Vec<&str>, blocks: &mut Vec<Block>| {
if !para.is_empty() {
blocks.push(Block::Paragraph(parse_inlines(¶.join(" "))));
para.clear();
}
};
let mut i = 0;
while i < lines.len() {
let line = lines[i];
let t = line.trim();
if t.is_empty() {
flush(&mut para, &mut blocks);
i += 1;
} else if let Some(lang) = t.strip_prefix("```") {
flush(&mut para, &mut blocks);
let mut body = Vec::new();
i += 1;
while i < lines.len() && !lines[i].trim_start().starts_with("```") {
body.push(lines[i]);
i += 1;
}
i += 1;
let code: SharedString = body.join("\n").into();
blocks.push(match lang.trim() {
"mermaid" => Block::Mermaid(code),
"math" | "tex" | "latex" => Block::Math(code),
l => Block::Code {
language: l.to_string().into(),
code,
},
});
} else if let Some(rest) = t.strip_prefix("$$") {
flush(&mut para, &mut blocks);
if let Some(one) = rest.strip_suffix("$$") {
blocks.push(Block::Math(one.trim().to_string().into()));
i += 1;
} else {
let mut body = vec![rest];
i += 1;
while i < lines.len() && !lines[i].trim().ends_with("$$") {
body.push(lines[i].trim());
i += 1;
}
if let Some(last) = lines.get(i) {
body.push(last.trim().trim_end_matches("$$"));
}
i += 1;
blocks.push(Block::Math(body.join(" ").trim().to_string().into()));
}
} else if t.starts_with('#') {
flush(&mut para, &mut blocks);
let level = t.chars().take_while(|c| *c == '#').count();
blocks.push(Block::Heading(
level.clamp(1, 4) as u8,
parse_inlines(t[level..].trim()),
));
i += 1;
} else if t == "---" || t == "***" {
flush(&mut para, &mut blocks);
blocks.push(Block::Rule);
i += 1;
} else if t.starts_with('>') {
flush(&mut para, &mut blocks);
let mut body = Vec::new();
while i < lines.len() && lines[i].trim().starts_with('>') {
body.push(lines[i].trim().trim_start_matches('>').trim());
i += 1;
}
blocks.push(Block::Quote(parse_inlines(&body.join(" "))));
} else if t.starts_with('|') {
flush(&mut para, &mut blocks);
let head = table_cells(t);
i += 1;
if i < lines.len() && lines[i].contains("---") {
i += 1;
}
let mut rows = Vec::new();
while i < lines.len() && lines[i].trim().starts_with('|') {
rows.push(table_cells(lines[i]));
i += 1;
}
blocks.push(Block::Table(head, rows));
} else if let Some(rest) = t.strip_prefix("[^") {
flush(&mut para, &mut blocks);
let text = rest.split_once("]:").map_or(rest, |(_, r)| r).trim();
notes.push(parse_inlines(text));
i += 1;
} else if list_line(line).is_some() {
flush(&mut para, &mut blocks);
let mut items = Vec::new();
while i < lines.len() {
match list_line(lines[i]) {
Some((indent, ordered, n, task, text)) => {
items.push((indent, ordered, n, task, text.to_string()));
i += 1;
}
None => break,
}
}
blocks.push(build_list(&items));
} else {
para.push(t);
i += 1;
}
}
flush(&mut para, &mut blocks);
if !notes.is_empty() {
blocks.push(Block::Footnotes(notes));
}
blocks
}
pub const BODY: (f32, f32) = (14., 22.);
pub const MAX_WIDTH: f32 = 736.;
const GAP: f32 = 14. * 0.85;
pub fn block_margins(block: &Block) -> (f32, f32) {
match block {
Block::Heading(level, _) => {
let s = heading_size(*level).0;
(1.5 * s, 0.5 * s)
}
Block::Rule => (21., 21.),
Block::Math(_) => (0., 0.),
Block::Footnotes(_) => (18., 0.),
_ => (0., GAP),
}
}
pub fn block_gaps(blocks: &[Block]) -> Vec<f32> {
let mut out = Vec::with_capacity(blocks.len());
let mut prev_bottom: Option<f32> = None;
for b in blocks {
let (top, bottom) = block_margins(b);
out.push(prev_bottom.map_or(0., |p| p.max(top)));
prev_bottom = Some(bottom);
}
out
}
pub fn heading_size(level: u8) -> (f32, u16) {
match level {
1 => (24., 400),
2 => (20., 600),
3 => (16., 600),
_ => (14., 600),
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RunBase {
pub weight: u16,
pub ink: Hsla,
}
impl RunBase {
pub fn regular(role: ColorRole) -> Self {
Self {
weight: 400,
ink: color(role),
}
}
}
const SUP_PAD: &str = "\u{200A}";
pub fn sup_raise(body: f32) -> f32 {
body / 3. + 1.
}
pub fn sup_room(body: f32) -> f32 {
sup_raise(body) + 1.
}
struct InlineRuns {
text: String,
runs: Vec<TextRun>,
code: Vec<Range<usize>>,
sups: Vec<(Range<usize>, Font)>,
}
fn runs(inlines: &[Inline], base: RunBase, body: f32) -> InlineRuns {
let ink = base.ink;
let mut text = String::new();
let mut runs = Vec::new();
let mut code = Vec::new();
let mut sups = Vec::new();
let sans = |w: u16, italic: bool| {
let mut f = font(FontFamilyKey::Sans, w);
if italic {
f.style = FontStyle::Italic;
}
f
};
for inline in inlines {
if let Inline::Code(s) = inline {
code.push(push_inline_code(&mut text, &mut runs, s, ink, body));
continue;
}
let (s, f, c, underline) = match inline {
Inline::Text(s) => (s.to_string(), sans(base.weight, false), ink, false),
Inline::Strong(s) => (s.to_string(), sans(600, false), ink, false),
Inline::Em(s) => (s.to_string(), sans(base.weight, true), ink, false),
Inline::Link(t, _) => (
t.to_string(),
sans(base.weight, false),
color(ColorRole::LinkPrimary),
true,
),
Inline::FootnoteRef(n) => {
let f = sans(base.weight, false);
for (s, hidden) in [(SUP_PAD, false), (n.as_ref(), true), (SUP_PAD, false)] {
let start = text.len();
text.push_str(s);
if hidden {
sups.push((start..text.len(), f.clone()));
}
runs.push(TextRun {
len: s.len(),
font: f.clone(),
color: if hidden {
gpui_kit::transparent_black()
} else {
ink
},
background_color: None,
underline: None,
strikethrough: None,
});
}
continue;
}
Inline::Code(_) => continue,
Inline::Math(s) => (
s.to_string(),
font(FontFamilyKey::Mono, base.weight),
ink,
false,
),
};
text.push_str(&s);
runs.push(TextRun {
len: s.len(),
font: f,
color: c,
background_color: None,
underline: underline.then_some(UnderlineStyle {
thickness: px(1.),
color: Some(c),
wavy: false,
}),
strikethrough: None,
});
}
InlineRuns {
text,
runs,
code,
sups,
}
}
fn inline_text(inlines: &[Inline], base: RunBase, body: f32) -> Div {
let InlineRuns {
text,
runs,
code,
sups,
} = runs(inlines, base, body);
let styled = StyledText::new(text.clone()).with_runs(runs);
if sups.is_empty() {
return with_code_boxes(styled, code, body);
}
let layout = styled.layout().clone();
let link = color(ColorRole::LinkPrimary);
let painted = canvas(
|_, _, _| (),
move |_, _, window, cx| {
let px_of = |v: f32| window.rem_size() * (v / 16.);
let (size, raise) = (px_of(body), px_of(sup_raise(body)));
for (r, f) in &sups {
let Some(at) = layout.position_for_index(r.start) else {
continue;
};
let digits = SharedString::from(text[r.clone()].to_string());
let run = TextRun {
len: digits.len(),
font: f.clone(),
color: link,
background_color: None,
underline: None,
strikethrough: None,
};
let line = window.text_system().shape_line(digits, size, &[run], None);
let _ = line.paint(
point(at.x, at.y - raise),
layout.line_height(),
TextAlign::Left,
None,
window,
cx,
);
}
},
)
.absolute()
.top_0()
.left_0()
.size_full();
div()
.pt(rem(sup_room(body)))
.child(with_code_boxes(styled, code, body).child(painted))
}
#[derive(Clone, Debug)]
pub struct ProseTexts {
pub copy_code: SharedString,
pub copied: SharedString,
pub mermaid: SharedString,
pub copy_source: SharedString,
}
impl Default for ProseTexts {
fn default() -> Self {
Self {
copy_code: "Copy code".into(),
copied: "Copied".into(),
mermaid: "Mermaid".into(),
copy_source: "Copy source".into(),
}
}
}
#[derive(IntoElement)]
pub struct ProseCodeBlock {
id: ElementId,
language: SharedString,
code: SharedString,
texts: ProseTexts,
}
impl ProseCodeBlock {
pub fn new(
id: impl Into<ElementId>,
language: impl Into<SharedString>,
code: impl Into<SharedString>,
) -> Self {
Self {
id: id.into(),
language: language.into(),
code: code.into(),
texts: ProseTexts::default(),
}
}
pub fn texts(mut self, texts: ProseTexts) -> Self {
self.texts = texts;
self
}
}
const FLASH_MS: u64 = 1500;
pub const CODE_LINE: f32 = 13. * 1.5;
impl RenderOnce for ProseCodeBlock {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let state = flash_state((id.clone(), "flash"), window, cx);
let copied = flash_on(&state, FLASH_MS, cx);
let code = self.code.clone();
let count = self.code.split('\n').count();
let tint = inline_code_fill();
let lines: Vec<AnyElement> = self
.code
.split('\n')
.enumerate()
.map(|(i, l)| {
let (first, last) = (i == 0, i + 1 == count);
let inset = px((CODE_LINE - box_height(14.)) / 2.);
div()
.flex()
.h(rem(CODE_LINE))
.whitespace_nowrap()
.child(
div()
.relative()
.flex_none()
.when(first, |d| d.pl(px(4.)))
.when(last, |d| d.pr(px(4.)))
.when(first || last || !l.is_empty(), |d| {
d.child(
div()
.absolute()
.left_0()
.right_0()
.top(inset)
.bottom(inset)
.bg(tint),
)
})
.child(div().relative().child(SharedString::from(l.to_string()))),
)
.into_any_element()
})
.collect();
div()
.id(id.clone())
.flex()
.flex_col()
.w_full()
.bg(color(ColorRole::Layer01))
.child(
code_head()
.child(
mono(div(), 12., 400)
.text_color(color(ColorRole::TextSecondary))
.child(self.language.clone()),
)
.child(grow())
.child(
IconButton::new(
(id.clone(), "copy"),
if copied {
CarbonIcon::Checkmark
} else {
CarbonIcon::Copy
},
if copied {
self.texts.copied.clone()
} else {
self.texts.copy_code.clone()
},
)
.icon_px(14.)
.on_click(move |_, _, cx| {
cx.write_to_clipboard(ClipboardItem::new_string(code.to_string()));
flash(&state, FLASH_MS, cx);
}),
),
)
.child(
mono(div(), 13., 400)
.id((id, "pre"))
.overflow_x_scroll()
.p(tokens::SPACING_04)
.line_height(rem(CODE_LINE))
.text_color(color(ColorRole::TextPrimary))
.child(div().flex().flex_col().children(lines)),
)
}
}
#[derive(IntoElement)]
pub struct MathBlock {
tex: SharedString,
}
impl MathBlock {
pub fn new(tex: impl Into<SharedString>) -> Self {
Self { tex: tex.into() }
}
}
impl RenderOnce for MathBlock {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
mono(div(), 13., 400)
.flex()
.justify_center()
.py(tokens::SPACING_03)
.text_color(color(ColorRole::TextPrimary))
.child(self.tex)
}
}
#[derive(IntoElement)]
pub struct MermaidBlock {
id: ElementId,
code: SharedString,
texts: ProseTexts,
}
impl MermaidBlock {
pub fn new(id: impl Into<ElementId>, code: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
code: code.into(),
texts: ProseTexts::default(),
}
}
pub fn texts(mut self, texts: ProseTexts) -> Self {
self.texts = texts;
self
}
}
impl RenderOnce for MermaidBlock {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let id = self.id.clone();
div()
.id(id.clone())
.flex()
.flex_col()
.w_full()
.bg(color(ColorRole::Layer01))
.child(
code_head()
.child(head_icon(CarbonIcon::Flow))
.child(self.texts.mermaid.clone())
.child(grow())
.child(
CopyButton::new((id.clone(), "copy"), self.code.clone())
.label(self.texts.copy_source.clone())
.size(32.)
.quiet(true)
.layer(LayerLevel::One),
),
)
.child(
div()
.id((id, "canvas"))
.flex()
.justify_center()
.p(tokens::SPACING_04)
.overflow_x_scroll()
.child(
mono(div(), 12., 400)
.flex()
.flex_col()
.flex_none()
.text_color(color(ColorRole::TextSecondary))
.children(self.code.split('\n').map(|l| {
div()
.whitespace_nowrap()
.min_h(rem(16.))
.child(SharedString::from(l.to_string()))
})),
),
)
}
}
#[derive(IntoElement)]
pub struct MarkdownProse {
id: ElementId,
blocks: Vec<Block>,
texts: ProseTexts,
}
impl MarkdownProse {
pub fn new(id: impl Into<ElementId>, blocks: impl IntoIterator<Item = Block>) -> Self {
Self {
id: id.into(),
blocks: blocks.into_iter().collect(),
texts: ProseTexts::default(),
}
}
pub fn markdown(id: impl Into<ElementId>, src: &str) -> Self {
Self::new(id, parse_markdown(src))
}
pub fn texts(mut self, texts: ProseTexts) -> Self {
self.texts = texts;
self
}
}
pub fn disc_geometry(body: f32) -> (f32, f32, f32) {
let k = body / BODY.0;
(5. * k, 5. * k, 9. * k)
}
fn list(
ordered: bool,
start: usize,
items: &[ListItem],
id: &ElementId,
body: f32,
base: RunBase,
) -> Div {
let li_gap = px(0.2 * body);
div()
.flex()
.flex_col()
.children(items.iter().enumerate().map(|(i, it)| {
let marker = div()
.flex()
.flex_none()
.w(rem(1.5 * body))
.text_color(color(ColorRole::TextSecondary));
let marker = if ordered {
marker
.justify_end()
.pr(px(6.))
.child(format!("{}.", start + i))
} else {
let (size, left, top) = disc_geometry(body);
marker.child(
div()
.flex_none()
.size(rem(size))
.ml(rem(left))
.mt(rem(top))
.rounded_full()
.bg(color(ColorRole::TextSecondary)),
)
};
div()
.flex()
.when(i > 0, |d| d.mt(li_gap))
.child(marker)
.child(
div()
.flex()
.flex_col()
.flex_1()
.min_w_0()
.child(inline_text(&it.content, base, body))
.children(it.children.iter().map(|b| {
match b {
Block::List {
ordered,
start,
items,
} => div()
.mt(li_gap)
.child(list(*ordered, *start, items, id, body, base))
.into_any_element(),
other => render_block(other, id, 0, &ProseTexts::default()),
}
})),
)
}))
}
fn task_box(checked: bool) -> Div {
div()
.flex()
.flex_none()
.items_center()
.justify_center()
.size(rem(13.))
.mt(px(5.))
.rounded(px(2.))
.when(checked, |d| {
d.bg(color(ColorRole::Interactive)).child(
Icon::carbon(CarbonIcon::Checkmark)
.size_length(rem(11.))
.color(color(ColorRole::TextOnColor)),
)
})
.when(!checked, |d| {
d.border_1().border_color(color(ColorRole::BorderStrong01))
})
}
fn render_block(block: &Block, id: &ElementId, i: usize, texts: &ProseTexts) -> AnyElement {
let primary = RunBase::regular(ColorRole::TextPrimary);
let secondary = RunBase::regular(ColorRole::TextSecondary);
let sub = |name: &str| -> ElementId {
(id.clone(), SharedString::from(format!("{name}-{i}"))).into()
};
match block {
Block::Heading(level, inlines) => {
let (s, w) = heading_size(*level);
div()
.text_size(rem(s))
.line_height(gpui_kit::relative(1.3))
.font_weight(FontWeight(w as f32))
.child(inline_text(
inlines,
RunBase {
weight: w,
..primary
},
s,
))
.into_any_element()
}
Block::Paragraph(inlines) => inline_text(inlines, primary, BODY.0).into_any_element(),
Block::List {
ordered,
start,
items,
} => list(*ordered, *start, items, id, BODY.0, primary).into_any_element(),
Block::TaskList(items) => div()
.flex()
.flex_col()
.pl(px(3.5))
.children(items.iter().enumerate().map(|(k, (done, inlines))| {
div()
.flex()
.items_start()
.gap(tokens::SPACING_03)
.when(k > 0, |d| d.mt(px(2.8)))
.child(task_box(*done))
.child(inline_text(inlines, primary, BODY.0))
}))
.into_any_element(),
Block::Quote(inlines) => div()
.px(tokens::SPACING_05)
.border_l(px(3.))
.border_color(color(ColorRole::BorderStrong01))
.text_color(secondary.ink)
.child(inline_text(inlines, secondary, BODY.0))
.into_any_element(),
Block::Table(head, rows) => {
let cols = head.len().max(rows.iter().map(Vec::len).max().unwrap_or(0));
let cell = |inlines: Option<&Vec<Inline>>, th: bool| {
let weight = if th { 600 } else { 400 };
sans(div(), 13., weight)
.line_height(rem(20.))
.py(tokens::SPACING_02)
.px(tokens::SPACING_04)
.border_b_1()
.border_color(color(ColorRole::BorderSubtle01))
.when(th, |d| d.bg(color(ColorRole::LayerAccent01)))
.whitespace_nowrap()
.child(inline_text(
inlines.map_or(&[][..], |v| v),
RunBase { weight, ..primary },
13.,
))
};
div()
.id(sub("table"))
.flex()
.overflow_x_scroll()
.children((0..cols).map(|c| {
div()
.flex()
.flex_col()
.flex_none()
.child(cell(head.get(c), true))
.children(rows.iter().map(|r| cell(r.get(c), false)))
}))
.into_any_element()
}
Block::Rule => div()
.h(px(1.))
.bg(color(ColorRole::BorderSubtle01))
.into_any_element(),
Block::Code { language, code } => {
ProseCodeBlock::new(sub("code"), language.clone(), code.clone())
.texts(texts.clone())
.into_any_element()
}
Block::Math(tex) => MathBlock::new(tex.clone()).into_any_element(),
Block::Mermaid(code) => MermaidBlock::new(sub("mermaid"), code.clone())
.texts(texts.clone())
.into_any_element(),
Block::Footnotes(notes) => sans(div(), 12., 400)
.pt(tokens::SPACING_04)
.border_t_1()
.border_color(color(ColorRole::BorderSubtle01))
.text_color(secondary.ink)
.line_height(rem(BODY.1))
.child(list(
true,
1,
¬es
.iter()
.map(|n| ListItem {
content: n.clone(),
children: Vec::new(),
})
.collect::<Vec<_>>(),
id,
12.,
secondary,
))
.into_any_element(),
}
}
impl RenderOnce for MarkdownProse {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
let gaps = block_gaps(&self.blocks);
sans(div(), BODY.0, 400)
.id(self.id.clone())
.flex()
.flex_col()
.w_full()
.max_w(rem(MAX_WIDTH))
.line_height(rem(BODY.1))
.text_color(color(ColorRole::TextPrimary))
.children(self.blocks.iter().enumerate().map(|(i, b)| {
div()
.mt(px(gaps[i]))
.child(render_block(b, &self.id, i, &self.texts))
}))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn t(s: &str) -> Inline {
Inline::Text(s.to_string().into())
}
#[test]
fn inlines() {
assert_eq!(
parse_inlines("The `g90` theme now matches [Carbon v11](#). Two[^1]:"),
vec![
t("The "),
Inline::Code("g90".into()),
t(" theme now matches "),
Inline::Link("Carbon v11".into(), "#".into()),
t(". Two"),
Inline::FootnoteRef("1".into()),
t(":"),
]
);
assert_eq!(
parse_inlines("**a** *b* $c$ ` x"),
vec![
Inline::Strong("a".into()),
t(" "),
Inline::Em("b".into()),
t(" "),
Inline::Math("c".into()),
t(" ` x"),
]
);
}
#[test]
fn blocks_from_the_reference_document() {
let md = "## Token migration\n\nThe `g90` theme.\n\n- [x] Add tokens\n- [ ] Update the cover\n\n1. Read tokens\n2. Patch components\n - Card\n - Tabs\n\n> Layer tokens are contextual.\n\n| Token | White | G100 |\n|---|---|---|\n| layer-01 | #f4f4f4 | #262626 |\n\n```ts\nexport const x = 1;\n```\n\n$$c = \\sqrt{a^2 + b^2}$$\n\n```mermaid\ngraph LR\n A --> B\n```\n\n[^1]: See the release notes.";
let b = parse_markdown(md);
assert!(matches!(b[0], Block::Heading(2, _)));
assert!(matches!(b[1], Block::Paragraph(_)));
assert_eq!(
b[2],
Block::TaskList(vec![
(true, vec![t("Add tokens")]),
(false, vec![t("Update the cover")])
])
);
match &b[3] {
Block::List {
ordered,
start,
items,
} => {
assert!(*ordered);
assert_eq!(*start, 1);
assert_eq!(items.len(), 2);
assert!(
matches!(&items[1].children[0], Block::List { ordered: false, items, .. } if items.len() == 2)
);
}
other => panic!("{other:?}"),
}
assert!(matches!(b[4], Block::Quote(_)));
match &b[5] {
Block::Table(head, rows) => {
assert_eq!(head.len(), 3);
assert_eq!(rows.len(), 1);
}
other => panic!("{other:?}"),
}
assert_eq!(
b[6],
Block::Code {
language: "ts".into(),
code: "export const x = 1;".into()
}
);
assert_eq!(b[7], Block::Math("c = \\sqrt{a^2 + b^2}".into()));
assert_eq!(b[8], Block::Mermaid("graph LR\n A --> B".into()));
assert_eq!(
b[9],
Block::Footnotes(vec![vec![t("See the release notes.")]])
);
}
#[test]
fn margins_collapse() {
let blocks = [
Block::Heading(2, vec![]),
Block::Paragraph(vec![]),
Block::Heading(3, vec![]),
Block::Rule,
Block::Footnotes(vec![]),
];
assert_eq!(block_gaps(&blocks), vec![0., 10., 24., 21., 21.]);
assert_eq!(heading_size(1), (24., 400));
}
#[test]
fn inline_code_is_the_shared_tint() {
crate::theme::tests_set(crate::CarbonTheme::White);
let InlineRuns {
text, runs, code, ..
} = runs(
&[t("a "), Inline::Code("x".into())],
RunBase::regular(ColorRole::TextPrimary),
BODY.0,
);
assert_eq!(&text[code[0].clone()], "\u{202F}x\u{202F}");
assert!(runs.iter().all(|r| r.background_color.is_none()));
}
#[test]
fn runs_inherit_the_block_weight_and_colour() {
crate::theme::tests_set(crate::CarbonTheme::White);
let secondary = color(ColorRole::TextSecondary);
let link = color(ColorRole::LinkPrimary);
let inlines = [
t("a"),
Inline::Em("b".into()),
Inline::Link("c".into(), "#".into()),
Inline::Strong("d".into()),
Inline::Math("e".into()),
];
let InlineRuns { runs: r, .. } = runs(
&inlines,
RunBase {
weight: 600,
ink: color(ColorRole::TextPrimary),
},
20.,
);
assert!(r.iter().all(|r| r.font.weight == FontWeight(600.)));
let InlineRuns { runs: r, .. } =
runs(&inlines, RunBase::regular(ColorRole::TextSecondary), 12.);
let colours: Vec<Hsla> = r.iter().map(|r| r.color).collect();
assert_eq!(
colours,
vec![secondary, secondary, link, secondary, secondary]
);
assert_eq!(r[0].font.weight, FontWeight(400.));
assert_eq!(r[3].font.weight, FontWeight(600.));
assert_eq!(r[1].font.style, FontStyle::Italic);
}
#[test]
fn footnote_reference_is_a_raised_full_size_link() {
crate::theme::tests_set(crate::CarbonTheme::White);
let InlineRuns {
text,
runs: r,
sups,
..
} = runs(
&[t("x"), Inline::FootnoteRef("1".into())],
RunBase::regular(ColorRole::TextPrimary),
BODY.0,
);
assert_eq!(text, "x\u{200A}1\u{200A}");
assert_eq!(sups.len(), 1);
assert_eq!(&text[sups[0].0.clone()], "1");
assert_eq!(r[2].color.a, 0.);
assert!(r.iter().all(|r| r.underline.is_none()));
assert!((sup_raise(14.) - 5.667).abs() < 1e-3);
assert!((sup_room(14.) - 6.667).abs() < 1e-3);
}
#[test]
fn code_block_lines_follow_the_prose_code_rule() {
assert_eq!(CODE_LINE, 19.5);
assert!(box_height(14.) < CODE_LINE);
}
#[test]
fn bullets_are_chromium_discs() {
let (size, left, top) = disc_geometry(BODY.0);
assert_eq!((size, left, top), (5., 5., 9.));
assert_eq!(1.5 * BODY.0 - left - size, 11.);
assert!((top + size / 2. - BODY.1 / 2.).abs() <= 0.5);
}
}