Skip to content
Repos

DevPlaceApp

C++ 1.5 KB49 lines Opens in site

Directory Raw Download

#pragma once
// Spec: INV-posts 8 (VoteView+ViewModel). Optimistic vote with rollback and an alert on failure. One instance per
// target (cached), so state survives the per-frame view rebuild.
#include <cstdint>
#include <memory>
#include <string>

#include "model/TargetType.hpp"
#include "model/Vote.hpp"

namespace dp {

class VoteViewModel {
 public:
  VoteViewModel(TargetType type, std::string targetId, std::int64_t count, Vote vote);

  // Cached instance for the target. When the parent passes a count or vote different from what it passed last
  // time, the model is overwritten (VoteView.swift onChange).
  static std::shared_ptr<VoteViewModel> shared(TargetType type, const std::string& targetId, std::int64_t count, Vote vote);
  static void clearCache();

  std::int64_t count() const { return count_; }
  Vote currentVote() const { return vote_; }
  bool isLoading() const { return loading_; }
  bool userCanVote() const;

  void voteUp();
  void voteDown();

  // Pure rules (unit tested): tapping the held direction clears, else selects; count moves by the vote delta.
  static Vote nextVote(Vote current, Vote tapped);
  static std::int64_t nextCount(std::int64_t count, Vote previous, Vote next);

 private:
  void apply(Vote selected, Vote newVote);
  void syncToFeed() const;
  void syncProps(std::int64_t count, Vote vote);

  TargetType type_;
  std::string targetId_;
  std::int64_t count_;
  Vote vote_;
  std::int64_t propCount_;
  Vote propVote_;
  bool loading_ = false;
  std::weak_ptr<VoteViewModel> self_;
};

}  // namespace dp
49.1ms