Skip to content
Repos

DevPlaceApp

C++ 2.2 KB69 lines Opens in site

Directory Raw Download

#include "screens/components/TypingIndicator.hpp"

#include <cmath>

#include "spec/SocialSpec.hpp"
#include "ui/Palette.hpp"

namespace dp {

using namespace ui;

float typingDotOpacity(int index, double seconds) {
  using T = spec::SocialTiming;
  using M = spec::SocialMetrics;
  const double t = seconds - index * T::kDotDelaySeconds;
  if (t < 0) return M::kDotMinOpacity;
  const double period = 2 * T::kDotPeriodSeconds;
  const double phase = std::fmod(t, period) / T::kDotPeriodSeconds;  // 0..2
  const double p = phase <= 1 ? phase : 2 - phase;
  const double eased = p < 0.5 ? 2 * p * p : 1 - 2 * (1 - p) * (1 - p);  // easeInOut
  return static_cast<float>(M::kDotMinOpacity + (1 - M::kDotMinOpacity) * eased);
}

namespace {

class DotsView : public View {
 public:
  explicit DotsView(std::string username) : username_(std::move(username)) {}
  std::string label() const override { return username_ + spec::SocialStrings::kTypingSuffix; }

 protected:
  Size compute(const Proposal&) override {
    using M = spec::SocialMetrics;
    return {3 * M::kDotSize + 2 * M::kDotSize * M::kDotSpacingFactor, M::kDotSize};
  }

 public:
  void draw(Canvas& c) override {
    using M = spec::SocialMetrics;
    UiState& ui = UiState::instance();
    Slot& s = ui.slot(id_);
    if (!s.flag || ui.now - s.anim > spec::SocialTiming::kAppearGapSeconds) {
      s.flag = true;
      s.stamp = ui.now;  // onAppear: isAnimating = true
    }
    s.anim = static_cast<float>(ui.now);
    ui.animating = true;
    const double elapsed = ui.now - s.stamp;
    const float step = M::kDotSize * (1 + M::kDotSpacingFactor);
    for (int i = 0; i < 3; ++i) {
      c.fillRRect({frame_.x + step * static_cast<float>(i), frame_.y, M::kDotSize, M::kDotSize}, Corners::all(M::kDotSize / 2),
                  Palette::fg2(), typingDotOpacity(i, elapsed));
    }
  }

 private:
  std::string username_;
};

}  // namespace

ViewPtr TypingIndicatorView(const std::string& username) {
  using M = spec::SocialMetrics;
  return std::make_shared<DotsView>(username)->paddingH(M::kTypingPadH)->paddingV(M::kTypingPadV)
      ->background(Palette::bg1(), Corners::all(M::kTypingRadius))
      ->border(Palette::fg2(), M::kTypingRadius, 1, M::kBubbleBorderOpacity);
}

}  // namespace dp
34.5ms