Skip to content
Repos

DevPlaceApp

C++ 7.2 KB208 lines Opens in site

Directory Raw Download

#pragma once
// Spec: SPEC.md UX-LAYOUT-01..04. SwiftUI-style declarative views: rebuilt every frame from presenter
// state, laid out with the SwiftUI proposal protocol, drawn on the software Canvas.
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include "ui/Canvas.hpp"
#include "ui/Font.hpp"
#include "ui/Geometry.hpp"
#include "ui/TextLayout.hpp"

namespace dp::ui {

class View;
using ViewPtr = std::shared_ptr<View>;

// Inherited values (SwiftUI environment). Wrappers push a modified copy while measuring, placing, drawing.
struct EnvValues {
  std::optional<FontSpec> font;
  std::optional<Color> foreground;
  int lineLimit = 0;
  TextAlign multilineAlign = TextAlign::Leading;
  bool disabled = false;
  float lineSpacing = 0;
};

class Env {
 public:
  static const EnvValues& cur() { return stack_.back(); }
  static void push(const EnvValues& v) { stack_.push_back(v); }
  static void pop() { if (stack_.size() > 1) stack_.pop_back(); }
  static void reset() { stack_.assign(1, EnvValues{}); }

 private:
  static inline std::vector<EnvValues> stack_{EnvValues{}};
};

class EnvScope {
 public:
  explicit EnvScope(const EnvValues& v) { Env::push(v); }
  ~EnvScope() { Env::pop(); }
  EnvScope(const EnvScope&) = delete;
  EnvScope& operator=(const EnvScope&) = delete;
};

struct Binding {
  std::function<std::string()> get;
  std::function<void(const std::string&)> set;
};
struct BoolBinding {
  std::function<bool()> get;
  std::function<void(bool)> set;
};

// Per-view persistent interaction state, keyed by view id (scroll offsets, carets, animation values).
struct Slot {
  float scrollX = 0, scrollY = 0;
  float velX = 0, velY = 0;
  int caret = 0, anchor = 0;
  float anim = 0;
  double stamp = 0;
  bool flag = false;
  float lastMax = 0;  // scroll views: previous maximum offset (bottom anchoring)
};

class UiState {
 public:
  static UiState& instance();
  Slot& slot(std::uint64_t id) { return slots_[id]; }
  bool has(std::uint64_t id) const { return slots_.count(id) != 0; }
  void prune(std::size_t keepAtMost);
  std::uint64_t pressedId = 0;
  std::uint64_t hoverId = 0;
  std::uint64_t focusedId = 0;
  double now = 0;  // seconds, advanced by the host every frame
  float navScrollY = 0;      // scroll offset of the first scroll view of the previous frame (nav bar title fade)
  float nextNavScrollY = 0;
  bool navScrollSet = false;
  bool animating = false;  // set by views that need another frame (scroll momentum, spinners)

 private:
  std::unordered_map<std::uint64_t, Slot> slots_;
};

struct Hit {
  View* view;
  Point local;
};

class View : public std::enable_shared_from_this<View> {
 public:
  virtual ~View() = default;

  // ---- layout (memoized per frame; override compute) ----
  Size measure(const Proposal& p);
  virtual void place(const Rect& r);
  const Rect& bounds() const { return frame_; }

  // ---- paint ----
  virtual void draw(Canvas& c);

  // ---- identity ----
  virtual void assignIds(std::uint64_t parent, std::uint64_t index);
  std::uint64_t id() const { return id_; }
  void overrideKey(const std::string& key) { key_ = key; hasKey_ = true; }

  // ---- interaction ----
  virtual float priority() const { return 0; }
  // Visible text of this view (accessibility label, smoke scripts); empty for non-text views.
  virtual std::string label() const { return ""; }
  virtual bool acceptsPress() const { return false; }
  virtual bool scrollable() const { return false; }
  virtual bool isTextInput() const { return false; }
  // Press targets that want raw drag callbacks (sliders, edge swipes, text selection) instead of tap.
  virtual bool wantsDrag() const { return false; }
  virtual void onTap(Point) {}
  virtual bool onKey(std::uint32_t /*sdlKey*/, std::uint16_t /*mods*/) { return false; }
  virtual void onText(const std::string& /*utf8*/) {}
  virtual void onFocus(bool /*focused*/) {}
  View* findById(std::uint64_t target);
  virtual void onLongPress(Point) {}
  virtual void onDragBegin(Point) {}
  virtual void onDragMove(Point, Point /*delta*/) {}
  virtual void onDragEnd(Point) {}
  virtual bool onScrollWheel(float /*dx*/, float /*dy*/) { return false; }
  virtual bool scrollBy(float /*dx*/, float /*dy*/) { return false; }
  virtual void fling(float /*vx*/, float /*vy*/) {}
  virtual void releaseDrag() {}
  // Appends interactive views under p, deepest first.
  virtual void hits(Point p, std::vector<View*>& out);

  // ---- children ----
  const std::vector<ViewPtr>& children() const { return children_; }
  std::vector<ViewPtr>& children() { return children_; }

  // ---- fluent modifiers (SwiftUI-style) ----
  ViewPtr padding(float all = 16);
  ViewPtr padding(const Insets& insets);
  ViewPtr paddingH(float h);
  ViewPtr paddingV(float v);
  ViewPtr paddingTop(float v);
  ViewPtr paddingBottom(float v);
  ViewPtr paddingLeading(float v);
  ViewPtr paddingTrailing(float v);
  ViewPtr frame(std::optional<float> w, std::optional<float> h, Alignment a = Alignment::center());
  ViewPtr frameFlex(std::optional<float> minW, std::optional<float> idealW, std::optional<float> maxW,
                    std::optional<float> minH, std::optional<float> idealH, std::optional<float> maxH,
                    Alignment a = Alignment::center());
  ViewPtr maxWidth(Alignment a = Alignment::center());   // maxWidth: .infinity
  ViewPtr maxHeight(Alignment a = Alignment::center());  // maxHeight: .infinity
  ViewPtr maxSize(Alignment a = Alignment::center());    // both axes
  ViewPtr fixedSize(bool horizontal = true, bool vertical = true);
  ViewPtr layoutPriority(float p);
  ViewPtr background(Color c, const Corners& radius = {});
  ViewPtr background(ViewPtr v, Alignment a = Alignment::center());
  ViewPtr overlay(ViewPtr v, Alignment a = Alignment::center());
  ViewPtr roundedBackground(Color c, float radius);
  ViewPtr border(Color c, float radius, float width = 1, float opacity = 1);  // strokeBorder overlay
  ViewPtr clipRounded(float radius);
  ViewPtr clipCircle();
  ViewPtr clipRect();
  ViewPtr opacity(float f);
  ViewPtr offset(float dx, float dy);
  ViewPtr offsetFraction(float fx, float fy);  // fraction of the view's own size
  ViewPtr scale(float s);
  ViewPtr shadow(Color c, float blur, float dx = 0, float dy = 0, const Corners& shape = {});
  ViewPtr font(const FontSpec& f);
  ViewPtr bold();
  ViewPtr weight(Weight w);
  ViewPtr foreground(Color c);
  ViewPtr lineLimit(int n);
  ViewPtr multilineAlign(TextAlign a);
  ViewPtr lineSpacing(float v);
  ViewPtr disabled(bool v = true);
  ViewPtr id(const std::string& key);
  ViewPtr onTap(std::function<void()> fn);
  ViewPtr onLongPress(std::function<void()> fn);
  ViewPtr contentShape(bool fullRect = true);

 protected:
  virtual Size compute(const Proposal& p) = 0;
  ViewPtr self() { return shared_from_this(); }
  void addChild(ViewPtr v) { if (v) children_.push_back(std::move(v)); }

  Rect frame_;
  std::uint64_t id_ = 0;
  std::string key_;
  bool hasKey_ = false;
  std::vector<ViewPtr> children_;

 private:
  struct CacheEntry {
    std::optional<float> w, h;
    Size size;
  };
  std::vector<CacheEntry> cache_;
};

std::uint64_t hashCombine(std::uint64_t a, std::uint64_t b);
std::uint64_t hashString(const std::string& s);

}  // namespace dp::ui
34.6ms