#pragma once
// Spec: INV-posts 1.3 (isAtTop), 2.3 (scrollTo with animation), 1.3 (mention list height scrolls the composer anchor to
// the bottom). Programmatic scrolling of one ScrollView on top of ScrollCommand: reads the scroll offset from marks on
// the viewport and the content, and animates an offset change over a duration with ease in and out.
#include <optional>
#include <string>
#include "ui/Views.hpp"
namespace dp {
class ScrollDriver {
public:
explicit ScrollDriver(std::string scrollKey);
~ScrollDriver();
const std::string& scrollKey() const { return key_; }
// Wrap the ScrollView and its content so their placement is recorded.
ui::ViewPtr markViewport(ui::ViewPtr scrollView);
ui::ViewPtr markContent(ui::ViewPtr content);
// Registers an anchor key to look up later (call once, then wrap the view with AnchorMark(view, qualified(key))).
void watchAnchor(const std::string& anchor);
void unwatchAnchor(const std::string& anchor);
std::string qualified(const std::string& anchor) const { return key_ + "#" + anchor; }
// Current scroll offset from the last placed frame (0 before the first frame).
float currentY() const;
bool atTop() const { return currentY() <= 0.5f; }
bool hasLayout() const;
// Offset that puts the anchor's top at the viewport top (scrollTo(id, anchor: .top)); nullopt until it was placed.
std::optional<float> offsetForTop(const std::string& anchor) const;
// Offset that puts the anchor's bottom at the viewport bottom (anchor: .bottom).
std::optional<float> offsetForBottom(const std::string& anchor) const;
void animateTo(float y, double seconds);
void jumpTo(float y);
// Call once per frame while building the body: pushes the animated offset into the ScrollView.
void tick();
bool animating() const { return anim_; }
static float ease(float t);
private:
std::string key_;
bool anim_ = false;
float from_ = 0, to_ = 0;
double start_ = 0, duration_ = 0;
};
} // namespace dp