// Spec: INV-posts 3 (feed card actions), 5 (comments), 7 (reactions), 8 (votes), 9 (polls), 11 (report), 12 (model
// updates): presenter logic of the posts area through the real mock API and the real stores.
#include "ModelSamples.hpp"
#include "TestHarness.hpp"
#include "TestPump.hpp"
#include "TestTempDir.hpp"
#include "api/mock/MockDevPlaceApi.hpp"
#include "api/mock/MockFixtures.hpp"
#include "core/TextCount.hpp"
#include "core/Timer.hpp"
#include "screens/AppContext.hpp"
#include "screens/comments/CommentEditor.hpp"
#include "screens/comments/CommentView.hpp"
#include "screens/comments/CommentsProps.hpp"
#include "screens/comments/CommentsSession.hpp"
#include "screens/comments/MentionParticipants.hpp"
#include "screens/components/PollViewModel.hpp"
#include "screens/components/ReportViewModel.hpp"
#include "screens/components/VoteViewModel.hpp"
#include "screens/feed/FeedPostActions.hpp"
#include "screens/feed/FeedScreen.hpp"
#include "screens/post/Accessible.hpp"
#include "screens/post/AnchorMark.hpp"
#include "screens/post/ModelCache.hpp"
#include "screens/post/PostDetailAdapter.hpp"
#include "screens/post/PostScreen.hpp"
#include "screens/post/ScrollDriver.hpp"
#include "screens/post/TapGesture.hpp"
#include "screens/reactions/ReactionRowView.hpp"
#include "screens/reactions/ReactionsStack.hpp"
#include "spec/PostsSpec.hpp"
#include "store/AppState.hpp"
#include "store/SessionStore.hpp"
#include "store/SettingsStore.hpp"
#include "ui/Overlays.hpp"
using namespace dp;
namespace {
// A mock API whose write calls fail, to prove the rollback paths.
class FailingApi : public MockDevPlaceApi {
public:
using MockDevPlaceApi::vote;
CancelPtr vote(TargetType, const std::string&, Vote, Done<Unit> done) override { return fail(std::move(done)); }
CancelPtr submitPollChoice(const std::string&, const std::string&, Done<Unit> done) override { return fail(std::move(done)); }
CancelPtr react(TargetType, const std::string&, const std::string&, Done<Unit> done) override { return fail(std::move(done)); }
CancelPtr report(TargetType, const std::string&, const std::string&, const Str&, Done<Unit> done) override { return fail(std::move(done)); }
CancelPtr reportReasons(Done<std::vector<ReportReason>> done) override {
return Timer::after(0, [done = std::move(done)] { done(Result<std::vector<ReportReason>>(Error::generic())); });
}
private:
CancelPtr fail(Done<Unit> done) {
return Timer::after(0, [done = std::move(done)] { done(Result<Unit>(Error::generic())); });
}
};
struct PostsScope {
PostsScope() {
static test::TempDir storeDir;
SessionStore::instance().rebind(storeDir.path());
SettingsStore::instance().rebind(storeDir.path());
SettingsStore::instance().setDraftReplyMessage("");
MockDevPlaceApi::shared().setDelayScale(0.0);
AppContext::setApi(&MockDevPlaceApi::shared());
AppState::instance().clear();
ui::Overlays::instance().clear();
VoteViewModel::clearCache();
PollViewModel::clearCache();
ReportViewModel::clearCache();
}
~PostsScope() {
AppState::instance().clear();
ui::Overlays::instance().clear();
AppContext::setApi(&MockDevPlaceApi::shared());
}
static void login() {
bool done = false;
MockDevPlaceApi::shared().logIn("a@b.c", "pw", [&](Result<Unit>) { done = true; });
test::pumpUntil([&] { return done; });
}
static void loadFeed() {
bool done = false;
AppState::instance().loadFeed(AppContext::api(), [&](Result<Unit>) { done = true; });
test::pumpUntil([&] { return done; });
}
};
} // namespace
// ---- votes (INV-posts 8) ----
DP_TEST(posts_vote_rules_toggle_and_count_delta) {
CHECK(VoteViewModel::nextVote(Vote(Vote::None), Vote(Vote::Up)) == Vote(Vote::Up));
CHECK(VoteViewModel::nextVote(Vote(Vote::Up), Vote(Vote::Up)) == Vote(Vote::None));
CHECK(VoteViewModel::nextVote(Vote(Vote::Up), Vote(Vote::Down)) == Vote(Vote::Down));
CHECK_EQ(VoteViewModel::nextCount(5, Vote(Vote::Up), Vote(Vote::Down)), 3); // up to down moves by -2
CHECK_EQ(VoteViewModel::nextCount(5, Vote(Vote::None), Vote(Vote::Up)), 6);
CHECK_EQ(VoteViewModel::nextCount(5, Vote(Vote::Down), Vote(Vote::None)), 6);
CHECK_EQ(FeedPostActions::votedCount(10, Vote(Vote::Up), Vote(Vote::None)), 9);
}
DP_TEST(posts_vote_optimistic_then_synced_to_feed) {
PostsScope scope;
PostsScope::login();
PostsScope::loadFeed();
const Post first = AppState::instance().feed()->posts.front();
auto model = VoteViewModel::shared(TargetType::Post, first.data.id, first.data.stars, Vote(Vote::None));
CHECK(model->userCanVote());
model->voteUp();
CHECK(model->currentVote() == Vote(Vote::Up)); // optimistic, before the request returns
CHECK_EQ(model->count(), first.data.stars + 1);
CHECK(model->isLoading());
model->voteUp(); // ignored while loading
CHECK_EQ(model->count(), first.data.stars + 1);
CHECK(test::pumpUntil([&] { return !model->isLoading(); }));
CHECK(model->currentVote() == Vote(Vote::Up));
const Post& after = AppState::instance().feed()->posts.front();
CHECK_EQ(after.data.stars, first.data.stars + 1);
CHECK(after.myVote == Vote(Vote::Up));
}
DP_TEST(posts_vote_failure_rolls_back_and_alerts) {
PostsScope scope;
PostsScope::login();
FailingApi failing;
AppContext::setApi(&failing);
auto model = VoteViewModel::shared(TargetType::Post, "p-x", 7, Vote(Vote::None));
model->voteDown();
CHECK_EQ(model->count(), 6);
CHECK(test::pumpUntil([&] { return !model->isLoading(); }));
CHECK_EQ(model->count(), 7);
CHECK(model->currentVote() == Vote(Vote::None));
CHECK(ui::Overlays::instance().any()); // alert "Error"
}
DP_TEST(posts_vote_logged_out_cannot_vote) {
PostsScope scope;
auto model = VoteViewModel::shared(TargetType::Comment, "c-x", 1, Vote(Vote::None));
CHECK(!model->userCanVote());
}
DP_TEST(posts_vote_parent_props_overwrite_the_model) {
PostsScope scope;
auto a = VoteViewModel::shared(TargetType::Post, "p-sync", 3, Vote(Vote::None));
auto b = VoteViewModel::shared(TargetType::Post, "p-sync", 9, Vote(Vote::Up));
CHECK(a.get() == b.get());
CHECK_EQ(b->count(), 9);
CHECK(b->currentVote() == Vote(Vote::Up));
}
// ---- polls (INV-posts 9) ----
DP_TEST(posts_poll_recompute_matches_swift) {
PollOption a{"a", "A", 3, 0, 0}, b{"b", "B", 1, 0, 0};
auto fresh = PollViewModel::recompute({a, b}, 4, std::nullopt, std::optional<std::string>("a"));
CHECK_EQ(fresh.total, 5);
CHECK_EQ(fresh.options[0].count, 4);
CHECK_EQ(fresh.options[0].pct, 80);
CHECK_EQ(fresh.options[1].pct, 20);
auto sw = PollViewModel::recompute(fresh.options, 5, std::optional<std::string>("a"), std::optional<std::string>("b"));
CHECK_EQ(sw.total, 5); // switching keeps the total
CHECK_EQ(sw.options[0].count, 3);
CHECK_EQ(sw.options[1].count, 2);
auto cleared = PollViewModel::recompute(sw.options, 5, std::optional<std::string>("b"), std::nullopt);
CHECK_EQ(cleared.total, 4);
CHECK_EQ(cleared.options[1].count, 1);
auto zero = PollViewModel::recompute({PollOption{"a", "A", 1, 0, 100}}, 1, std::optional<std::string>("a"), std::nullopt);
CHECK_EQ(zero.total, 0);
CHECK_EQ(zero.options[0].pct, 0); // total 0 gives 0 percent
// 1/8 = 12.5 rounds half away from zero to 13
auto half = PollViewModel::recompute({PollOption{"a", "A", 0, 0, 0}, PollOption{"b", "B", 7, 0, 0}}, 7, std::nullopt, std::optional<std::string>("a"));
CHECK_EQ(half.options[0].pct, 13);
}
DP_TEST(posts_poll_votes_label_singular_only_for_one) {
Poll p;
p.id = "label-poll";
p.question = "Q";
p.total = 1;
CHECK_EQ(PollViewModel::shared(p)->votesLabel(), std::string("1 vote"));
p.id = "label-poll2";
p.total = 0;
CHECK_EQ(PollViewModel::shared(p)->votesLabel(), std::string("0 votes"));
p.id = "label-poll3";
p.total = 20;
CHECK_EQ(PollViewModel::shared(p)->votesLabel(), std::string("20 votes"));
}
DP_TEST(posts_poll_select_optimistic_and_rollback) {
PostsScope scope;
PostsScope::login();
Poll poll = MockFixtures::pollLayoutContainer();
auto model = PollViewModel::shared(poll);
const std::int64_t before = model->total();
const std::string first = poll.options.front().id;
model->select(first);
CHECK(model->myChoice() && *model->myChoice() == first);
CHECK(model->isLoading());
CHECK(test::pumpUntil([&] { return !model->isLoading(); }));
model->select(first); // tapping the selection again clears it
CHECK(!model->myChoice());
CHECK(test::pumpUntil([&] { return !model->isLoading(); }));
CHECK_EQ(model->total(), before);
FailingApi failing;
AppContext::setApi(&failing);
const auto optionsBefore = model->options();
model->select(first);
CHECK(test::pumpUntil([&] { return !model->isLoading(); }));
CHECK(!model->myChoice());
CHECK_EQ(model->total(), before);
CHECK_EQ(model->options().size(), optionsBefore.size());
CHECK(ui::Overlays::instance().any());
}
DP_TEST(posts_poll_ignores_taps_when_logged_out) {
PostsScope scope;
auto model = PollViewModel::shared(MockFixtures::pollConcurrency());
const auto choice = model->myChoice();
model->select(model->options().front().id);
CHECK(model->myChoice() == choice);
CHECK(!model->isLoading());
}
// ---- report (INV-posts 11) ----
DP_TEST(posts_report_detail_trim_and_limits) {
CHECK(!ReportViewModel::trimmedDetail(" \n\t ").has_value());
CHECK_EQ(*ReportViewModel::trimmedDetail(" spam \n"), std::string("spam"));
PostsScope scope;
auto m = ReportViewModel::shared(TargetType::Comment, "c1");
CHECK_EQ(m->targetNoun(), std::string("comment"));
CHECK_EQ(m->sheetTitle(), std::string("Report this comment"));
CHECK(!m->canSubmit()); // no reason yet
m->selectReason("spam");
CHECK(m->canSubmit());
m->detail = std::string(2000, 'a');
CHECK(m->canSubmit());
m->detail = std::string(2001, 'a');
CHECK(!m->canSubmit());
m->prepareForPresentation();
CHECK(!m->selectedReasonKey().has_value());
CHECK(m->detail.empty());
CHECK_EQ(ReportViewModel::shared(TargetType::Post, "p1")->targetNoun(), std::string("post"));
}
DP_TEST(posts_report_loads_reasons_once_and_submits) {
PostsScope scope;
PostsScope::login();
auto m = ReportViewModel::shared(TargetType::Post, "p9");
m->loadReasons();
m->loadReasons(); // second call while loading is a no-op
CHECK(test::pumpUntil([&] { return !m->reasons().empty(); }));
CHECK(!m->didFailToLoadReasons());
m->selectReason(m->reasons().front().key);
bool done = false, ok = false;
m->submit([&](bool success) {
done = true;
ok = success;
});
CHECK(m->isSubmitting());
CHECK(!m->canSubmit());
CHECK(test::pumpUntil([&] { return done; }));
CHECK(ok);
CHECK(!m->isSubmitting());
}
DP_TEST(posts_report_failure_flags_and_retry) {
PostsScope scope;
FailingApi failing;
AppContext::setApi(&failing);
auto m = ReportViewModel::shared(TargetType::Post, "p-fail");
m->loadReasons();
CHECK(test::pumpUntil([&] { return m->didFailToLoadReasons(); }));
CHECK(m->reasons().empty());
AppContext::setApi(&MockDevPlaceApi::shared());
m->loadReasons(); // Retry
CHECK(test::pumpUntil([&] { return !m->reasons().empty(); }));
CHECK(!m->didFailToLoadReasons());
m->selectReason("x");
AppContext::setApi(&failing);
bool done = false, ok = true;
m->submit([&](bool s) {
done = true;
ok = s;
});
CHECK(test::pumpUntil([&] { return done; }));
CHECK(!ok);
CHECK(ui::Overlays::instance().any()); // error alert, sheet stays
}
// ---- reactions (INV-posts 7) ----
DP_TEST(posts_reactions_sorted_by_count_then_emoji) {
Reactions r;
r.counts = {{"b", 2}, {"a", 2}, {"c", 5}, {"d", 1}};
r.mine = {"d"};
const auto items = ReactionsStack::items(r);
CHECK_EQ(items.size(), static_cast<std::size_t>(4));
CHECK_EQ(items[0].emoji, std::string("c"));
CHECK_EQ(items[1].emoji, std::string("a"));
CHECK_EQ(items[2].emoji, std::string("b"));
CHECK_EQ(items[3].emoji, std::string("d"));
CHECK(items[3].isMine && !items[0].isMine);
CHECK(ReactionsStack::view(Reactions{}, nullptr) == nullptr); // hidden entirely without reactions
}
DP_TEST(posts_reaction_row_plan_truncates_with_more_chip) {
using ui::Size;
const std::vector<Size> chips(5, Size{50, 24});
auto all = ReactionRowView::plan(chips, Size{30, 24}, 6, 1000);
CHECK_EQ(all.size.w, 5 * 50 + 4 * 6);
for (std::size_t i = 0; i < 5; ++i) CHECK(all.visible[i]);
CHECK(!all.visible[5]);
// 200 wide: chips 50+6+50+6+50 = 162, + 6 + 30 = 198 fits three chips and the more chip
auto cut = ReactionRowView::plan(chips, Size{30, 24}, 6, 200);
CHECK(cut.visible[0] && cut.visible[1] && cut.visible[2]);
CHECK(!cut.visible[3] && !cut.visible[4]);
CHECK(cut.visible[5]);
CHECK_EQ(cut.size.w, 198);
// nothing fits: only the more chip
auto none = ReactionRowView::plan(chips, Size{30, 24}, 6, 40);
CHECK(!none.visible[0] && none.visible[5]);
CHECK_EQ(none.size.w, 30);
// exactly fitting keeps all chips
auto exact = ReactionRowView::plan(chips, Size{30, 24}, 6, 5 * 50 + 4 * 6);
CHECK(exact.visible[4] && !exact.visible[5]);
}
// ---- comments (INV-posts 5) ----
DP_TEST(posts_comment_levels_and_divider_alignment) {
CHECK_EQ(commentEffectiveLevel(0), 0);
CHECK_EQ(commentEffectiveLevel(3), 3);
CHECK_EQ(commentEffectiveLevel(7), 3); // capped at maxIndentationLevel
CHECK_EQ(commentDividerLeading(1, std::nullopt), 16.0f);
CHECK_EQ(commentDividerLeading(1, std::optional<int>(3)), 48.0f); // 16 + (3 - 1) * 16
CHECK_EQ(commentDividerLeading(3, std::optional<int>(1)), 16.0f);
CHECK_EQ(commentDividerLeading(5, std::optional<int>(4)), 16.0f);
}
DP_TEST(posts_comments_flatten_depth_first_with_levels) {
const auto comments = MockFixtures::comments();
const auto rows = flattenComments(comments, 1);
CHECK(!rows.empty());
CHECK_EQ(rows.front().level, 1);
CHECK(rows.front().comment == &comments.front());
std::size_t total = 0;
std::vector<const Comment*> stack;
for (const Comment& c : comments) stack.push_back(&c);
while (!stack.empty()) {
const Comment* c = stack.back();
stack.pop_back();
++total;
for (const Comment& ch : c->children) stack.push_back(&ch);
}
CHECK_EQ(rows.size(), total);
// children come right after their parent with level + 1
for (std::size_t i = 0; i + 1 < rows.size(); ++i) {
if (!rows[i].comment->children.empty()) {
CHECK(rows[i + 1].comment == &rows[i].comment->children.front());
CHECK_EQ(rows[i + 1].level, rows[i].level + 1);
}
}
}
DP_TEST(posts_comment_editor_submit_bounds_use_utf16_units) {
CHECK(!CommentEditor::canSubmit(""));
CHECK(!CommentEditor::canSubmit("ab"));
CHECK(CommentEditor::canSubmit("abc"));
CHECK_EQ(TextCount::utf16("\xF0\x9F\x98\x80"), 2); // one emoji = 2 UTF-16 units
CHECK(!CommentEditor::canSubmit("\xF0\x9F\x98\x80")); // too short
CHECK(CommentEditor::canSubmit("\xF0\x9F\x98\x80" "a")); // 3 units
CHECK(CommentEditor::canSubmit(std::string(125000, 'a')));
CHECK(!CommentEditor::canSubmit(std::string(125001, 'a')));
}
DP_TEST(posts_mention_participants_exclude_self_and_dedupe) {
PostsScope scope;
PostsScope::login(); // current user = cheeze_on_wheels
const PostDetail detail = MockFixtures::postDetail();
const auto list = MentionParticipants::from(detail.author, detail.comments);
std::set<std::string> ids;
for (const auto& p : list) {
CHECK(!AppState::instance().isCurrentUser(p.id));
CHECK(ids.insert(p.id).second);
}
CHECK(!list.empty());
}
DP_TEST(posts_session_reply_edit_and_quote_rules) {
PostsScope scope;
CommentsSession s;
CHECK(!s.isComposing());
s.insertQuote("> x\n\n"); // nothing open: ignored
CHECK_EQ(SettingsStore::instance().draftReplyMessage(), std::string(""));
s.beginReply("p1");
CHECK(s.isReplying("p1") && s.isComposing());
const int epoch = s.epoch();
s.insertQuote("> quoted\n\n");
CHECK_EQ(SettingsStore::instance().draftReplyMessage(), std::string("> quoted\n\n"));
s.beginReply("comment:c1");
CHECK(!s.isReplying("p1") && s.isReplying("comment:c1"));
CHECK(s.epoch() > epoch);
s.setAttachments({UploadResponse{"a1", std::nullopt, "u", std::nullopt, true, false, false, "image/png"}});
auto taken = s.takeAttachmentsAndClose();
CHECK_EQ(taken.size(), static_cast<std::size_t>(1));
CHECK(s.attachments().empty() && !s.activeReply());
// editing wins over replying and keeps the quote pending for the edit editor
s.beginEditing("comment:c2", "old text");
CHECK(s.row("comment:c2").isEditing);
CHECK_EQ(s.row("comment:c2").editedText, std::string("old text"));
s.insertQuote("> q\n\n");
auto pending = s.takePendingEditQuote();
CHECK(pending && *pending == "> q\n\n");
CHECK(!s.takePendingEditQuote());
s.endEditing("comment:c2");
CHECK(!s.row("comment:c2").isEditing && !s.isComposing());
SettingsStore::instance().setDraftReplyMessage("");
}
DP_TEST(posts_session_cancel_deletes_unsubmitted_attachments) {
PostsScope scope;
CommentsSession s;
s.beginReply("p1");
s.setAttachments({UploadResponse{"a1", std::nullopt, "u", std::nullopt, true, false, false, "image/png"},
UploadResponse{"a2", std::nullopt, "u", std::nullopt, true, false, false, "image/png"}});
s.cancelReply();
CHECK(!s.activeReply());
CHECK(s.attachments().empty());
test::pumpFor(0.05);
}
DP_TEST(posts_session_attachment_cap) {
CommentsSession s;
std::vector<UploadResponse> many(25);
for (std::size_t i = 0; i < many.size(); ++i) many[i].id = std::to_string(i);
s.setAttachments(many);
CHECK_EQ(s.attachments().size(), spec::PostsLimits::kMaxPendingAttachments);
}
// ---- feed screen and card actions (INV-posts 1, 3.1) ----
DP_TEST(posts_feed_double_tap_post_votes_others_and_edits_own) {
PostsScope scope;
PostsScope::login();
PostsScope::loadFeed();
// The mock fixtures give every post to the mock user; hand the second one to somebody else.
Feed feed = *AppState::instance().feed();
CHECK(feed.posts.size() >= 2);
feed.posts[1].data.userId = "u-other";
AppState::instance().setFeed(feed);
const Post own = feed.posts[0];
const Post others = feed.posts[1];
CHECK(AppState::instance().isCurrentUser(own.data.userId));
CHECK(!FeedPostActions::doubleTapPost(own)); // caller opens the editor
const std::int64_t stars = others.data.stars;
const Vote before = others.myVote;
CHECK(FeedPostActions::doubleTapPost(others));
const Vote expected = before == Vote(Vote::Up) ? Vote(Vote::None) : Vote(Vote::Up);
const Post& optimistic = AppState::instance().feed()->posts[1];
CHECK(optimistic.myVote == expected); // applied before the request returns
CHECK_EQ(optimistic.data.stars, stars + expected.value() - before.value());
test::pumpFor(0.02);
CHECK(AppState::instance().feed()->posts[1].myVote == expected);
// a failing request rolls the vote back
FailingApi failing;
AppContext::setApi(&failing);
const Post current = AppState::instance().feed()->posts[1];
CHECK(FeedPostActions::doubleTapPost(current));
test::pumpFor(0.05);
CHECK(AppState::instance().feed()->posts[1].myVote == current.myVote);
CHECK_EQ(AppState::instance().feed()->posts[1].data.stars, current.data.stars);
}
DP_TEST(posts_feed_reaction_toggle_is_optimistic_and_rolls_back) {
PostsScope scope;
PostsScope::login();
PostsScope::loadFeed();
const Post post = AppState::instance().feed()->posts.front();
const std::int64_t before = post.reactions.counts.count("x") ? post.reactions.counts.at("x") : 0;
FeedPostActions::reactPost(post, "x");
CHECK_EQ(AppState::instance().feed()->posts.front().reactions.counts.at("x"), before + 1); // optimistic
test::pumpFor(0.02);
CHECK_EQ(AppState::instance().feed()->posts.front().reactions.counts.at("x"), before + 1);
FailingApi failing;
AppContext::setApi(&failing);
FeedPostActions::reactPost(post, "y");
test::pumpFor(0.05); // toggled and toggled back
const auto& counts = AppState::instance().feed()->posts.front().reactions.counts;
CHECK(counts.count("y") == 0);
}
DP_TEST(posts_feed_refresh_publishes_after_delay_and_load_more_guards) {
PostsScope scope;
PostsScope::login();
FeedScreen feed;
feed.load();
CHECK(feed.busy());
CHECK(test::pumpUntil([&] { return AppState::instance().feed().has_value() && !feed.busy(); }));
const auto count = AppState::instance().feed()->posts.size();
feed.refresh();
CHECK(feed.isRefreshing());
feed.refresh(); // second call while refreshing is a no-op
CHECK(test::pumpUntil([&] { return !feed.isRefreshing(); }));
CHECK(feed.busy()); // the new feed is still waiting for its 300 ms publish
CHECK(test::pumpUntil([&] { return !feed.busy(); }));
CHECK_EQ(AppState::instance().feed()->posts.size(), count);
// duplicate guard: the mock page repeats the same posts, load more adds none and stops auto loading
Feed withCursor = *AppState::instance().feed();
withCursor.nextCursor = DateCodec::now();
AppState::instance().setFeed(withCursor);
feed.loadMore();
CHECK(feed.isLoadingMore());
feed.loadMore(); // guarded
CHECK(test::pumpUntil([&] { return !feed.isLoadingMore(); }));
CHECK_EQ(AppState::instance().feed()->posts.size(), count);
}
// ---- post screen (INV-posts 2) ----
DP_TEST(posts_post_screen_loads_votes_and_reacts) {
PostsScope scope;
PostsScope::login();
PostScreen screen(PostDestination{"a-post-with-several-attachments", std::nullopt});
CHECK_EQ(screen.title(), std::string("Post")); // fallback until loaded
screen.load();
CHECK(test::pumpUntil([&] { return screen.detail().has_value(); }));
CHECK(screen.title() != "Post");
// reload is guarded while running
screen.reload();
CHECK(screen.isReloading());
screen.reload();
CHECK(test::pumpUntil([&] { return !screen.isReloading(); }));
const PostDetail detail = *screen.detail();
const bool own = AppState::instance().isCurrentUser(detail.post.userId);
if (!own) {
screen.upvoteForeignPost();
const Vote expected = detail.myVote == Vote(Vote::Up) ? Vote(Vote::None) : Vote(Vote::Up);
CHECK(screen.detail()->myVote == expected);
CHECK_EQ(screen.detail()->starCount, detail.starCount + expected.value() - detail.myVote.value());
test::pumpFor(0.02);
}
screen.reactToPost("z");
CHECK_EQ(screen.detail()->reactions.counts.at("z"), 1);
test::pumpFor(0.02);
screen.reactToPost("z"); // toggles off again
CHECK(screen.detail()->reactions.counts.count("z") == 0);
test::pumpFor(0.02);
}
DP_TEST(posts_post_screen_double_tap_comment_votes_only_others) {
PostsScope scope;
PostsScope::login();
PostScreen screen(PostDestination{"a-post-with-several-attachments", std::nullopt});
screen.load();
CHECK(test::pumpUntil([&] { return screen.detail().has_value(); }));
const Comment* foreign = nullptr;
const Comment* mine = nullptr;
for (const Comment& c : screen.detail()->comments) {
if (AppState::instance().isCurrentUser(c.data.userId)) mine = mine ? mine : &c;
else foreign = foreign ? foreign : &c;
}
CHECK(foreign);
const Vote before = foreign->myVote;
const std::string id = foreign->data.id;
screen.doubleTapComment(id);
const Comment* now = nullptr;
for (const Comment& c : screen.detail()->comments) if (c.data.id == id) now = &c;
CHECK(now && now->myVote == (before == Vote(Vote::Up) ? Vote(Vote::None) : Vote(Vote::Up)));
test::pumpFor(0.02);
if (mine) {
const Vote mineBefore = mine->myVote;
const std::string mineId = mine->data.id;
screen.doubleTapComment(mineId); // own comments never vote (a double tap edits them)
for (const Comment& c : screen.detail()->comments) if (c.data.id == mineId) CHECK(c.myVote == mineBefore);
}
}
DP_TEST(posts_post_screen_failed_load_alerts) {
PostsScope scope;
class MissingApi : public MockDevPlaceApi {
public:
CancelPtr postDetail(const std::string&, Done<PostDetail> done) override {
return Timer::after(0, [done = std::move(done)] { done(Result<PostDetail>(Error::generic())); });
}
} missing;
AppContext::setApi(&missing);
PostScreen screen(PostDestination{"nope", std::nullopt});
screen.load();
test::pumpFor(0.05);
CHECK(!screen.detail().has_value());
CHECK(ui::Overlays::instance().any());
}
DP_TEST(posts_post_detail_adapter_round_trip) {
const PostDetail detail = MockFixtures::postDetail();
const Post post = PostDetailAdapter::toPost(detail);
CHECK_EQ(post.data.id, detail.post.id);
CHECK_EQ(post.recentComments.size(), detail.comments.size());
const PostDetail back = PostDetailAdapter::fromPost(post);
CHECK_EQ(back.post.id, detail.post.id);
CHECK_EQ(back.starCount, detail.post.stars);
CHECK_EQ(back.attachments.size(), detail.attachments.size());
}
// ---- gestures, scrolling, caches ----
DP_TEST(posts_tap_gesture_single_waits_for_double_window) {
const std::uint64_t slot = 0xAB01;
ui::UiState::instance().slot(slot) = ui::Slot{};
int singles = 0, doubles = 0;
TapHandlers h;
h.single = [&] { ++singles; };
h.doubleTap = [&] { ++doubles; };
ui::UiState::instance().now = 100.0;
TapGesture::tap(slot, h);
ui::UiState::instance().now = 100.1; // second tap inside the window
TapGesture::tap(slot, h);
CHECK_EQ(doubles, 1);
test::pumpFor(0.4);
CHECK_EQ(singles, 0); // the pending single tap was consumed
ui::UiState::instance().now = 200.0;
TapGesture::tap(slot, h);
test::pumpFor(0.4);
CHECK_EQ(singles, 1);
CHECK_EQ(doubles, 1);
// without a double tap handler the single tap is immediate
TapHandlers onlySingle;
onlySingle.single = [&] { ++singles; };
TapGesture::tap(slot + 1, onlySingle);
CHECK_EQ(singles, 2);
}
DP_TEST(posts_scroll_driver_offsets_from_anchor_marks) {
ScrollDriver d("test-scroll");
d.watchAnchor("a");
auto& reg = AnchorRegistry::instance();
CHECK(!d.hasLayout());
reg.record(d.qualified("viewport"), 100, 500);
reg.record(d.qualified("content"), 40, 2000); // scrolled down by 60
reg.record(d.qualified("a"), 700, 760);
CHECK(d.hasLayout());
CHECK_EQ(d.currentY(), 60.0f);
CHECK(!d.atTop());
CHECK_EQ(*d.offsetForTop("a"), 660.0f);
CHECK_EQ(*d.offsetForBottom("a"), 760.0f - 40.0f - 400.0f);
reg.record(d.qualified("content"), 100, 2000);
CHECK(d.atTop());
CHECK_EQ(ScrollDriver::ease(0.0f), 0.0f);
CHECK_EQ(ScrollDriver::ease(1.0f), 1.0f);
CHECK_EQ(ScrollDriver::ease(0.5f), 0.5f);
CHECK(ScrollDriver::ease(0.25f) < 0.25f);
}
DP_TEST(posts_model_cache_is_capped_and_reuses_entries) {
ModelCache<int> cache;
auto a = cache.get("k", [] { return std::make_shared<int>(1); });
auto b = cache.get("k", [] { return std::make_shared<int>(2); });
CHECK(a.get() == b.get());
for (std::size_t i = 0; i < spec::PostsLimits::kModelCacheEntries + 50; ++i) {
cache.get("key" + std::to_string(i), [] { return std::make_shared<int>(0); });
}
CHECK(cache.size() <= spec::PostsLimits::kModelCacheEntries);
}
DP_TEST(posts_accessible_view_exposes_its_label) {
ui::ViewPtr v = Accessible(ui::Text("x"), "Reply to post");
CHECK_EQ(v->label(), std::string("Reply to post"));
}