Repos
C++
1.7 KB53 lines Opens in site
Directory
Raw
Download
#pragma once
// Spec: INV-posts 9 (PollView+ViewModel). Optimistic single choice with rollback and an alert on failure.
#include <cstdint>
#include <memory>
#include <optional>
#include <string>
#include <vector>
#include "model/Poll.hpp"
namespace dp {
class PollViewModel {
public:
explicit PollViewModel(const Poll& poll);
// Cached per poll id. A poll that differs from the one passed last time overwrites options, total and choice.
static std::shared_ptr<PollViewModel> shared(const Poll& poll);
static void clearCache();
const std::string& question() const { return question_; }
const std::vector<PollOption>& options() const { return options_; }
std::int64_t total() const { return total_; }
const std::optional<std::string>& myChoice() const { return myChoice_; }
bool isLoading() const { return loading_; }
bool userCanVote() const;
// "1 vote" / "N votes" (singular only when total == 1).
std::string votesLabel() const;
void select(const std::string& optionId);
struct Recomputed {
std::vector<PollOption> options;
std::int64_t total = 0;
};
// PVM.swift:66-92. pct = round(count / total * 100) half away from zero, 0 when total <= 0.
static Recomputed recompute(const std::vector<PollOption>& options, std::int64_t total,
const std::optional<std::string>& previousChoice, const std::optional<std::string>& newChoice);
private:
void syncProps(const Poll& poll);
std::string pollId_;
std::string question_;
std::vector<PollOption> options_;
std::int64_t total_;
std::optional<std::string> myChoice_;
Poll prop_;
bool loading_ = false;
std::weak_ptr<PollViewModel> self_;
};
} // namespace dp