Skip to content
Repos

DevPlaceApp

C++ 1.9 KB52 lines Opens in site

Directory Raw Download

#include "ui/MarkdownImageView.hpp"

#include "spec/MarkdownTheme.hpp"
#include "ui/Palette.hpp"
#include "ui/RemoteImageView.hpp"
#include "ui/RemoteImages.hpp"

namespace dp::ui {

namespace {

using T = spec::MarkdownTheme;

class MarkdownImageImpl : public View {
 public:
  MarkdownImageImpl(std::string url, ViewPtr image) : url_(std::move(url)) { addChild(std::move(image)); }

  void place(const Rect& r) override {
    frame_ = r;
    children_[0]->place(r);
  }

 protected:
  Size compute(const Proposal& p) override {
    const bool hasW = p.w && *p.w < kInf / 2;
    BitmapPtr bmp = RemoteImages::instance().get(url_, T::kImageRasterPx);
    if (!bmp) return children_[0]->measure(hasW ? Proposal::width(*p.w) : Proposal::width(T::kTableMaxCellWidth));
    const float natural = static_cast<float>(bmp->width());
    return children_[0]->measure(Proposal::width(hasW ? std::min(natural, *p.w) : natural));
  }

 private:
  std::string url_;
};

}  // namespace

ViewPtr MarkdownImage(const std::string& url, const std::string& alt, float fontSize) {
  const bool failed = RemoteImages::instance().failed(url);
  ViewPtr inner = failed ? VStack({Icon("photo", fontSize * 1.4f)->foreground(Palette::fg2()),
                                   Text(alt.empty() ? url : alt)->font(FontSpec::system(fontSize * 0.85f))
                                       ->foreground(Palette::fg2())->lineLimit(2)},
                                  4)
                         : ProgressSpinner(20)->foreground(Palette::fg2());
  ViewPtr placeholder = ZStack({RoundedRectShape(T::kImagePlaceholderRadius, Palette::bg2()), inner})
                            ->frame(std::nullopt, T::kImagePlaceholderHeight)
                            ->maxWidth();
  return std::make_shared<MarkdownImageImpl>(
      url, RemoteImage(url, ContentMode::Fit, std::move(placeholder), T::kImageRasterPx)->clipRounded(T::kImagePlaceholderRadius));
}

}  // namespace dp::ui
36.0ms