Skip to content
Repos

DevPlaceApp

C++ 10.0 KB255 lines Opens in site

Directory Raw Download

#include "ui/MarkdownRenderer.hpp"

#include "spec/MarkdownTheme.hpp"
#include "ui/MarkdownImageView.hpp"
#include "ui/MarkdownTableView.hpp"

namespace dp::ui {

using T = spec::MarkdownTheme;

MarkdownRenderer::MarkdownRenderer(float baseFontSize) : base_(std::clamp(baseFontSize, 8.0f, 72.0f)) {}

ViewPtr MarkdownRenderer::render(const MarkdownDocument& doc) const {
  Ctx ctx;
  ctx.size = base_;
  ctx.color = Palette::fg1();
  std::vector<Built> parts;
  parts.push_back({stack(doc.blocks, ctx), 0, 0});
  if (doc.truncated) {
    parts.push_back({Text("Content truncated")->font(FontSpec::system(base_ * 0.8f))->foreground(Palette::fg2()), 8, 0});
  }
  return join(parts)->maxWidth(Alignment::leading());
}

// MarkdownUI collapses margins: the gap between two blocks is max(bottom of the first, top of the second);
// the outer top and bottom margins are dropped.
ViewPtr MarkdownRenderer::join(const std::vector<Built>& blocks) {
  std::vector<ViewPtr> views;
  float prevBottom = 0;
  for (const Built& b : blocks) {
    if (!b.view) continue;
    views.push_back(views.empty() ? b.view : b.view->paddingTop(std::max(prevBottom, b.top)));
    prevBottom = b.bottom;
  }
  return VStack(std::move(views), 0, HAlign::Leading);
}

ViewPtr MarkdownRenderer::stack(const std::vector<MdBlock>& blocks, const Ctx& ctx) const {
  std::vector<Built> built;
  built.reserve(blocks.size());
  for (const MdBlock& b : blocks) built.push_back(block(b, ctx));
  return join(built);
}

MarkdownRenderer::Built MarkdownRenderer::block(const MdBlock& b, const Ctx& ctx) const {
  switch (b.kind) {
    case MdBlock::Kind::Heading: return heading(b, ctx);
    case MdBlock::Kind::Paragraph: return paragraph(b, ctx);
    case MdBlock::Kind::Quote: return quote(b, ctx);
    case MdBlock::Kind::CodeBlock: return codeBlock(b, ctx);
    case MdBlock::Kind::List: return list(b, ctx);
    case MdBlock::Kind::Table: return table(b, ctx);
    case MdBlock::Kind::Rule: return rule(ctx);
    default: return {};
  }
}

FontSpec MarkdownRenderer::fontOf(const InlineStyle& st, bool mono) {
  FontSpec f{st.size, st.weight, st.italic, mono};
  return f;
}

void MarkdownRenderer::flushSpans(Flow& flow, float lineSpacing) {
  if (flow.spans.empty()) return;
  // TextLayout drops whitespace that ends a span when the next span starts with a word, so a trailing
  // space moves to the start of the next span (before a line break it is dropped).
  for (std::size_t i = 0; i + 1 < flow.spans.size(); ++i) {
    std::string& t = flow.spans[i].text;
    bool moved = false;
    while (!t.empty() && t.back() == ' ') {
      t.pop_back();
      moved = true;
    }
    std::string& next = flow.spans[i + 1].text;
    if (moved && next != "\n" && (next.empty() || next[0] != ' ')) next.insert(0, " ");
  }
  flow.views.push_back(RichText(std::move(flow.spans))->lineSpacing(lineSpacing));
  flow.spans.clear();
}

void MarkdownRenderer::collect(const std::vector<MdInline>& nodes, const InlineStyle& st, bool allowImages,
                               Flow& flow) const {
  auto addText = [&](const std::string& text, const InlineStyle& s) {
    StyledSpan sp;
    sp.text = text;
    sp.font = fontOf(s);
    sp.color = s.color;
    sp.strikethrough = s.strike;
    sp.link = s.link;
    flow.spans.push_back(std::move(sp));
  };
  for (const MdInline& n : nodes) {
    switch (n.kind) {
      case MdInline::Kind::Text: addText(n.text, st); break;
      case MdInline::Kind::SoftBreak:  // .markdownSoftBreakMode(.lineBreak)
      case MdInline::Kind::HardBreak: addText("\n", st); break;
      case MdInline::Kind::Code: {
        StyledSpan sp;
        sp.text = n.text;
        sp.font = FontSpec{st.size * T::kCodeFontEm, st.weight, st.italic, true};
        sp.color = st.color;
        sp.background = Palette::bg2();
        sp.strikethrough = st.strike;
        sp.link = st.link;
        flow.spans.push_back(std::move(sp));
        break;
      }
      case MdInline::Kind::Emphasis: {
        InlineStyle s = st;
        s.italic = true;
        collect(n.children, s, allowImages, flow);
        break;
      }
      case MdInline::Kind::Strong: {
        InlineStyle s = st;
        s.weight = st.weight == Weight::Bold ? Weight::Bold : Weight::Semibold;
        collect(n.children, s, allowImages, flow);
        break;
      }
      case MdInline::Kind::Strike: {
        InlineStyle s = st;
        s.strike = true;
        collect(n.children, s, allowImages, flow);
        break;
      }
      case MdInline::Kind::Link: {
        InlineStyle s = st;
        s.color = Palette::accent();
        s.link = n.text;
        collect(n.children, s, allowImages, flow);
        break;
      }
      case MdInline::Kind::Image:
        if (allowImages) {
          flushSpans(flow, 0);
          flow.views.push_back(MarkdownImage(n.text, MarkdownParser::plainText(n.children), st.size));
        } else {
          addText(MarkdownParser::plainText(n.children), st);
        }
        break;
    }
  }
}

ViewPtr MarkdownRenderer::flowView(const std::vector<MdInline>& nodes, const InlineStyle& st, bool allowImages,
                                   float lineSpacing) const {
  Flow flow;
  collect(nodes, st, allowImages, flow);
  flushSpans(flow, lineSpacing);
  if (flow.views.empty()) return EmptyView();
  if (flow.views.size() == 1) return flow.views[0];
  return VStack(std::move(flow.views), 4, HAlign::Leading);
}

MarkdownRenderer::Built MarkdownRenderer::heading(const MdBlock& b, const Ctx& ctx) const {
  const int lv = std::clamp(b.level, 1, 6);
  InlineStyle st;
  st.size = ctx.size * T::kHeadingEm[lv - 1];
  st.weight = lv <= 2 ? Weight::Bold : Weight::Semibold;
  st.color = lv == 6 ? Palette::fg2() : ctx.color;
  return {flowView(b.inlines, st, false, st.size * T::kHeadingLineSpacingEm), T::kHeadingMarginTop,
          T::kHeadingMarginBottom};
}

MarkdownRenderer::Built MarkdownRenderer::paragraph(const MdBlock& b, const Ctx& ctx) const {
  InlineStyle st;
  st.size = ctx.size;
  st.color = ctx.color;
  return {flowView(b.inlines, st, true, ctx.size * T::kParagraphLineSpacingEm), 0,
          ctx.tight ? 0 : T::kBlockMarginBottom};
}

MarkdownRenderer::Built MarkdownRenderer::quote(const MdBlock& b, const Ctx& ctx) const {
  Ctx inner = ctx;
  inner.color = Palette::fg2();
  ViewPtr bar = RoundedRectShape(T::kQuoteBarRadius, Palette::fg2())->frame(ctx.size * T::kQuoteBarEm, std::nullopt);
  ViewPtr content = stack(b.children, inner)->paddingH(ctx.size * T::kQuotePaddingEm);
  return {HStack({bar, content}, 0, VAlign::Top)->fixedSize(false, true), 0, ctx.tight ? 0 : T::kBlockMarginBottom};
}

MarkdownRenderer::Built MarkdownRenderer::codeBlock(const MdBlock& b, const Ctx& ctx) const {
  StyledSpan sp;
  sp.text = b.text.empty() ? " " : b.text;
  sp.font = FontSpec{ctx.size * T::kCodeFontEm, Weight::Regular, false, true};
  sp.color = ctx.color;
  ViewPtr text = RichText({sp})->lineSpacing(ctx.size * T::kCodeBlockLineSpacingEm)
                     ->padding(Insets::symmetric(T::kCodeBlockPadH, T::kCodeBlockPadV));
  ScrollOptions so;
  so.axis = Axis::Horizontal;
  so.showsIndicator = false;
  ViewPtr view = ScrollView(text, so)->fixedSize(false, true)->maxWidth(Alignment::leading())
                     ->background(Palette::bg2(), Corners::all(T::kCodeBlockRadius))
                     ->clipRounded(T::kCodeBlockRadius);
  return {view, T::kCodeBlockMarginTop, T::kCodeBlockMarginBottom};
}

ViewPtr MarkdownRenderer::marker(const MdBlock& lst, const MdBlock& item, int index, const Ctx& ctx) const {
  const float minW = ctx.size * T::kListMarkerMinWidthEm;
  ViewPtr m;
  if (item.task >= 0) {
    const float box = ctx.size * T::kTaskBoxEm;
    const float lineH = FontSpec{ctx.size}.lineHeight();
    ViewPtr glyph = item.task == 1
                        ? ZStack({RoundedRectShape(3, Palette::accent()), Icon("checkmark", box * 0.7f)->foreground(Palette::onGradient())})
                        : StrokedRoundedRect(3, ctx.color, 1.5f);
    m = glyph->frame(box, box)->frame(std::nullopt, lineH);
  } else {
    static const char* const bullets[] = {"\xE2\x80\xA2", "\xE2\x97\xA6", "\xE2\x96\xAA"};
    const std::string text = lst.ordered ? std::to_string(lst.start + index) + "." : bullets[ctx.listDepth % 3];
    m = RichText({StyledSpan{text, FontSpec{ctx.size}, ctx.color, false, false, std::nullopt, ""}});
  }
  return m->frameFlex(minW, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, Alignment::trailing());
}

MarkdownRenderer::Built MarkdownRenderer::list(const MdBlock& b, const Ctx& ctx) const {
  std::vector<Built> items;
  int index = 0;
  for (const MdBlock& item : b.children) {
    Ctx inner = ctx;
    inner.tight = b.tight;
    inner.listDepth = ctx.listDepth + 1;
    ViewPtr content = stack(item.children, inner);
    ViewPtr row = HStack({marker(b, item, index, ctx), content}, ctx.size * T::kListMarkerGapEm, VAlign::Top);
    items.push_back({row->maxWidth(Alignment::leading()), ctx.size * T::kListItemMarginTopEm, b.tight ? 0 : T::kBlockMarginBottom});
    ++index;
  }
  return {join(items), 0, ctx.tight ? 0 : T::kBlockMarginBottom};
}

MarkdownRenderer::Built MarkdownRenderer::table(const MdBlock& b, const Ctx& ctx) const {
  std::vector<std::vector<ViewPtr>> rows;
  for (const MdBlock& row : b.children) {
    std::vector<ViewPtr> cells;
    for (const MdBlock& cell : row.children) {
      InlineStyle st;
      st.size = ctx.size;
      st.weight = row.header ? Weight::Semibold : Weight::Regular;
      st.color = ctx.color;
      cells.push_back(flowView(cell.inlines, st, false, ctx.size * T::kParagraphLineSpacingEm));
    }
    rows.push_back(std::move(cells));
  }
  ScrollOptions so;
  so.axis = Axis::Horizontal;
  so.showsIndicator = false;
  ViewPtr grid = std::make_shared<MarkdownTableView>(rows, b.aligns);
  return {ScrollView(grid, so)->fixedSize(false, true), 0, ctx.tight ? 0 : T::kBlockMarginBottom};
}

MarkdownRenderer::Built MarkdownRenderer::rule(const Ctx& ctx) const {
  ViewPtr bar = RectangleShape(Palette::fg2().opacity(T::kRuleOpacity))->frame(std::nullopt, ctx.size * T::kRuleHeightEm);
  return {bar->maxWidth(Alignment::leading()), T::kRuleMargin, T::kRuleMargin};
}

}  // namespace dp::ui
35.0ms