Skip to content
Repos

DevPlaceApp

C++ 2.2 KB84 lines Opens in site

Directory Raw Download

#include "screens/components/VFlowStack.hpp"

#include <algorithm>

namespace dp {

using namespace ui;

namespace {

class FlowView : public View {
 public:
  FlowView(std::vector<ViewPtr> kids, HAlign align, float spacing) : align_(align), spacing_(spacing) {
    for (auto& k : kids) addChild(std::move(k));
  }

 protected:
  struct Row {
    std::vector<std::size_t> items;
    float width = 0;
    float height = 0;
  };

  std::vector<Row> rows(float maxWidth, std::vector<Size>& sizes) {
    sizes.clear();
    for (auto& c : children_) sizes.push_back(c->measure(Proposal::ideal()));
    std::vector<Row> out;
    Row cur;
    for (std::size_t i = 0; i < sizes.size(); ++i) {
      const float w = sizes[i].w;
      if (!cur.items.empty() && cur.width + spacing_ + w > maxWidth) {
        out.push_back(cur);
        cur = Row{};
      }
      cur.width += (cur.items.empty() ? 0.0f : spacing_) + w;
      cur.height = std::max(cur.height, sizes[i].h);
      cur.items.push_back(i);
    }
    if (!cur.items.empty()) out.push_back(cur);
    return out;
  }

  Size compute(const Proposal& p) override {
    std::vector<Size> sizes;
    const float maxW = p.w && *p.w < kInf / 2 ? *p.w : kInf;
    auto rs = rows(maxW, sizes);
    float w = 0, h = 0;
    for (std::size_t i = 0; i < rs.size(); ++i) {
      w = std::max(w, rs[i].width);
      h += rs[i].height + (i ? spacing_ : 0);
    }
    return {w, h};
  }

 public:
  void place(const Rect& r) override {
    frame_ = r;
    std::vector<Size> sizes;
    auto rs = rows(r.w, sizes);
    float y = r.y;
    for (const Row& row : rs) {
      float x = r.x;
      if (align_ == HAlign::Trailing) x = r.x + r.w - row.width;
      else if (align_ == HAlign::Center) x = r.x + (r.w - row.width) / 2;
      for (std::size_t idx : row.items) {
        children_[idx]->place({x, y, sizes[idx].w, sizes[idx].h});
        x += sizes[idx].w + spacing_;
      }
      y += row.height + spacing_;
    }
  }

 private:
  HAlign align_;
  float spacing_;
};

}  // namespace

ViewPtr VFlowStack(std::vector<ViewPtr> children, HAlign alignment, float spacing) {
  return std::make_shared<FlowView>(std::move(children), alignment, spacing);
}

}  // namespace dp
18.1ms