Skip to content
Repos

DevPlaceApp

C++ 15.9 KB382 lines Opens in site

Directory Raw Download

#include "screens/post/PostScreen.hpp"

#include "core/Timer.hpp"
#include "model/CommentTree.hpp"
#include "screens/AppContext.hpp"
#include "screens/Routes.hpp"
#include "screens/comments/CommentsView.hpp"
#include "screens/comments/FadeInView.hpp"
#include "screens/comments/MentionParticipants.hpp"
#include "screens/comments/ReplyDraft.hpp"
#include "screens/components/AlertPresenter.hpp"
#include "screens/components/AttachmentViews.hpp"
#include "screens/components/PollView.hpp"
#include "screens/post/Accessible.hpp"
#include "screens/post/DoubleTapView.hpp"
#include "screens/post/PostContentView.hpp"
#include "screens/post/PostDetailAdapter.hpp"
#include "screens/post/PostFooterView.hpp"
#include "screens/post/PostHeaderView.hpp"
#include "spec/PostsSpec.hpp"
#include "store/AppState.hpp"
#include "ui/Overlays.hpp"
#include "ui/Palette.hpp"

namespace dp {

using namespace ui;
using spec::PostsLayout;
using spec::PostsText;
using spec::PostsTiming;

namespace {
constexpr int kMaxScrollTries = 240;  // frames spent waiting for the target comment to be placed
}

PostScreen::PostScreen(PostDestination destination) : destination_(std::move(destination)) {
  scroll_.watchAnchor(CommentEditor::scrollAnchorName());
  if (destination_.scrollToCommentId) scrollToComment(*destination_.scrollToCommentId);
}

PostScreen::~PostScreen() {
  *alive_ = false;
  if (pendingScroll_) scroll_.unwatchAnchor(*pendingScroll_);
}

std::string PostScreen::title() const {
  if (detail_ && detail_->post.title) return *detail_->post.title;
  return PostsText::kPostFallbackTitle;
}

bool PostScreen::busy() const { return inflight_ > 0 || scrollArmed_ || scroll_.animating(); }

void PostScreen::onAppear() { load(); }

void PostScreen::onDisappear() { session_.discardAttachments(); }

void PostScreen::scrollToComment(const std::string& commentId) {
  if (pendingScroll_) scroll_.unwatchAnchor(*pendingScroll_);
  pendingScroll_ = commentId;
  scroll_.watchAnchor(commentId);
  scrollTries_ = 0;
}

// ---- view model (PostVM.swift) ----

void PostScreen::fetchDetail(std::function<void(bool)> done) {
  ++inflight_;
  auto alive = alive_;
  AppContext::api().postDetail(destination_.slug, [this, alive, done = std::move(done)](Result<PostDetail> r) {
    if (!*alive) return;
    --inflight_;
    if (!r.ok()) {
      AlertPresenter::showError(r.error());
      if (done) done(false);
      return;
    }
    const bool first = !detail_.has_value();
    detail_ = std::move(r.value());
    if (first && pendingScroll_) {
      // PostView.scrollToTargetComment: 50 ms after the content appears.
      Timer::after(static_cast<unsigned>(PostsTiming::kScrollToCommentDelayMs), [this, alive] { if (*alive) scrollArmed_ = true; });
    }
    if (done) done(true);
  });
}

void PostScreen::load() { fetchDetail({}); }

void PostScreen::reload() {
  if (reloading_) return;
  reloading_ = true;
  auto alive = alive_;
  fetchDetail([this, alive](bool) { if (*alive) reloading_ = false; });
}

// postDetail, then loadFeed: the tail of every comment mutation.
void PostScreen::afterMutation(std::function<void(bool)> done) {
  auto alive = alive_;
  fetchDetail([alive, done](bool ok) {
    if (!ok) {
      if (done) done(false);
      return;
    }
    AppState::instance().loadFeed(AppContext::api(), [done, alive](Result<Unit> f) {
      if (!f.ok()) AlertPresenter::showError(f.error());
      if (done) done(f.ok());
    });
  });
}

void PostScreen::deletePost() {
  auto alive = alive_;
  AppContext::api().deletePost(destination_.slug, [this, alive](Result<Unit> r) {
    if (!r.ok()) return AlertPresenter::showError(r.error());
    AppState::instance().loadFeed(AppContext::api(), [this, alive](Result<Unit> f) {
      if (!f.ok()) return AlertPresenter::showError(f.error());
      if (*alive && navigator()) navigator()->pop();
    });
  });
}

void PostScreen::deleteComment(const std::string& commentId) {
  AppContext::api().deleteComment(commentId, [this](Result<Unit> r) {
    if (!r.ok()) return AlertPresenter::showError(r.error());
    afterMutation({});
  });
}

void PostScreen::editComment(const std::string& commentId, const std::string& content) {
  AppContext::api().editComment(commentId, content, [this](Result<Unit> r) {
    if (!r.ok()) return AlertPresenter::showError(r.error());
    afterMutation({});
  });
}

void PostScreen::submitComment(TargetType targetType, const std::string& targetId, const std::optional<std::string>& parentId,
                               const std::string& content, const std::vector<UploadResponse>& attachments, std::function<void(bool)> done) {
  AppContext::api().createComment(targetType, targetId, content, parentId, attachments, [this, done](Result<Unit> r) {
    if (!r.ok()) {
      AlertPresenter::showError(r.error());
      if (done) done(false);
      return;
    }
    afterMutation(done);
  });
}

void PostScreen::upvoteForeignPost() {
  if (!detail_) return;
  if (AppState::instance().isCurrentUser(detail_->post.userId)) return;
  const std::string id = detail_->post.id;
  const std::int64_t stars = detail_->starCount;
  const Vote previous = detail_->myVote;
  auto alive = alive_;
  AppState::instance().performVoteToggle(TargetType::Post, id, previous, AppContext::api(), [this, alive, id, stars, previous](Vote newVote) {
    const std::int64_t count = stars + newVote.value() - previous.value();
    if (*alive && detail_) detail_ = detail_->with(newVote, count);
    AppState::instance().updatePostVoteInFeed(id, newVote, count);
  });
}

void PostScreen::doubleTapComment(const std::string& commentId) {
  if (!detail_) return;
  const Comment* found = nullptr;
  std::vector<const Comment*> stack;
  for (const Comment& c : detail_->comments) stack.push_back(&c);
  while (!stack.empty()) {
    const Comment* c = stack.back();
    stack.pop_back();
    if (c->data.id == commentId) {
      found = c;
      break;
    }
    for (const Comment& child : c->children) stack.push_back(&child);
  }
  if (!found || AppState::instance().isCurrentUser(found->data.userId)) return;
  auto alive = alive_;
  AppState::instance().performVoteToggle(TargetType::Comment, commentId, found->myVote, AppContext::api(), [this, alive, commentId](Vote newVote) {
    if (*alive && detail_) detail_ = detail_->with(std::nullopt, std::nullopt, CommentTree::updatingVote(detail_->comments, commentId, newVote));
    AppState::instance().updateCommentVoteInFeed(commentId, newVote);
  });
}

void PostScreen::reactToPost(const std::string& emoji) {
  if (!detail_) return;
  const std::string id = detail_->post.id;
  auto alive = alive_;
  AppState::instance().performReactionToggle(TargetType::Post, id, emoji, AppContext::api(), [this, alive, id, emoji] {
    if (*alive && detail_) detail_ = detail_->with(std::nullopt, std::nullopt, std::nullopt, detail_->reactions.toggling(emoji));
    AppState::instance().updatePostReactionInFeed(id, emoji);
  });
}

void PostScreen::reactToComment(const std::string& commentId, const std::string& emoji) {
  if (!detail_) return;
  auto alive = alive_;
  AppState::instance().performReactionToggle(TargetType::Comment, commentId, emoji, AppContext::api(), [this, alive, commentId, emoji] {
    if (*alive && detail_) detail_ = detail_->with(std::nullopt, std::nullopt, CommentTree::updatingReaction(detail_->comments, commentId, emoji));
    AppState::instance().updateCommentReactionInFeed(commentId, emoji);
  });
}

// ---- replies ----

void PostScreen::submitReplyToPost(const std::string& postId, const std::string& content) {
  std::vector<UploadResponse> attachments = session_.takeAttachmentsAndClose();
  submitComment(TargetType::Post, postId, std::nullopt, content, attachments, [](bool ok) { if (ok) ReplyDraft::clear(); });
}

void PostScreen::submitReplyToComment(const std::string& commentId, const std::string& targetType, const std::string& targetId,
                                      const std::string& content) {
  std::vector<UploadResponse> attachments = session_.takeAttachmentsAndClose();
  const std::optional<TargetType> type = TargetType::fromRaw(targetType);
  submitComment(type.value_or(TargetType(TargetType::Post)), targetId, commentId, content, attachments, [](bool ok) { if (ok) ReplyDraft::clear(); });
}

void PostScreen::presentEdit() {
  if (!detail_) return;
  auto alive = alive_;
  Overlays::instance().sheet(makeCreatePostScreen(*detail_), SheetStyle::FullScreen, [this, alive] {
    if (*alive) reload();  // CreatePostView onComplete
  });
}

ViewPtr PostScreen::composer(const PostDetail& detail, const std::string& anchor, const std::string& placeholder) {
  CommentEditorProps props;
  props.text = ReplyDraft::binding();
  props.placeholder = placeholder;
  props.initialLineCount = PostsLayout::kEditorInitialLines;
  props.focusOnAppear = true;
  props.attachments = session_.attachments();
  props.onAttachmentsChange = [this](const std::vector<UploadResponse>& list) { session_.setAttachments(list); };
  props.mentionParticipants = MentionParticipants::from(detail.author, detail.comments);
  props.anchorKey = scroll_.qualified(CommentEditor::scrollAnchorName());
  props.onCancel = [this] { session_.cancelReply(); };
  const std::string postId = detail.post.id;
  props.onSubmit = [this, postId](const std::string& content) { submitReplyToPost(postId, content); };
  return FadeIn(session_.editor("reply:" + anchor).view(props), "reply-" + anchor + "-" + std::to_string(session_.epoch()));
}

// ---- view ----

ViewPtr PostScreen::postBody(const PostDetail& detail) {
  const bool own = AppState::instance().isCurrentUser(detail.post.userId);
  TapHandlers taps;
  taps.doubleTap = [this, own] {
    if (own) presentEdit();
    else upvoteForeignPost();
  };
  PostEnvironment env;
  env.taps = taps;
  env.quote.active = session_.isComposing();
  env.quote.insert = [this](const std::string& q) { session_.insertQuote(q); };
  env.openProfile = [this](const std::string& username) {
    if (navigator()) navigator()->push(makeProfileScreen(username));
  };

  PostHeaderOptions header;
  header.commentCount = detail.commentCount;
  std::vector<ViewPtr> parts;
  parts.push_back(PostHeaderView(detail.author, detail.post.createdAt, header, env));
  parts.push_back(PostContentView(detail.post.topic, detail.post.title, detail.post.content, env));
  if (detail.poll) parts.push_back(PollView(*detail.poll));
  for (const Attachment& attachment : detail.attachments) parts.push_back(AttachmentViewer(attachment));

  PostFooterProps footer;
  footer.targetId = detail.post.id;
  footer.authorId = detail.post.userId;
  footer.starCount = detail.starCount;
  footer.currentVote = detail.myVote;
  footer.reactions = detail.reactions;
  footer.onReact = [this](const std::string& emoji) { reactToPost(emoji); };
  footer.onReply = [this] { session_.beginReply(CommentsSession::kPostAnchor); };
  footer.isReplying = session_.isReplying(CommentsSession::kPostAnchor);
  if (own) {
    footer.onEdit = [this] { presentEdit(); };
    footer.onDelete = [this] { deletePost(); };
  }
  parts.push_back(PostFooterView(footer));
  if (session_.isReplying(CommentsSession::kPostAnchor)) parts.push_back(composer(detail, CommentsSession::kPostAnchor, ""));

  ViewPtr body = VStack(parts, PostsLayout::kCardSpacing, HAlign::Leading)->maxWidth(Alignment::leading())->padding(PostsLayout::kScreenPadding)
                     ->foreground(Palette::fg1())->background(Palette::bg1());
  return OnTaps(body, taps);
}

ViewPtr PostScreen::commentsSection(const PostDetail& detail) {
  if (detail.comments.empty()) return nullptr;
  CommentsProps cp;
  cp.comments = &detail.comments;
  cp.session = &session_;
  cp.rowAnchorPrefix = scroll_.qualified("");
  cp.composerAnchorKey = scroll_.qualified(CommentEditor::scrollAnchorName());
  cp.env.quote.active = session_.isComposing();
  cp.env.quote.insert = [this](const std::string& q) { session_.insertQuote(q); };
  cp.env.openProfile = [this](const std::string& username) {
    if (navigator()) navigator()->push(makeProfileScreen(username));
  };
  cp.onDoubleTap = [this](const CommentRef& c) { doubleTapComment(c.id); };
  cp.onReact = [this](const CommentRef& c, const std::string& emoji) { reactToComment(c.id, emoji); };
  cp.onDelete = [this](const CommentRef& c) { deleteComment(c.id); };
  cp.onEdit = [this](const CommentRef& c, const std::string& content) { editComment(c.id, content); };
  cp.onReply = [this](const CommentRef& c) { session_.beginReply(c.prefixedId); };
  cp.replyingCommentId = session_.activeReply();
  cp.replyText = ReplyDraft::binding();
  cp.onReplyAttachmentsChange = [this](const std::vector<UploadResponse>& list) { session_.setAttachments(list); };
  cp.onSubmitReply = [this](const CommentRef& c, const std::string& content) { submitReplyToComment(c.id, c.targetType, c.targetId, content); };
  cp.onCancelReply = [this] { session_.cancelReply(); };
  cp.mentionParticipants = MentionParticipants::from(detail.author, detail.comments);
  cp.showsDividers = true;
  ViewPtr header = Text(PostsText::kCommentsHeader)->font(FontSpec::title3().with(Weight::Semibold))
                       ->paddingH(PostsLayout::kScreenPadding)->paddingTop(PostsLayout::kScreenPadding)->maxWidth(Alignment::leading());
  return VStack({header, CommentsView(cp)}, PostsLayout::kCardSpacing, HAlign::Leading)->maxWidth(Alignment::leading());
}

ViewPtr PostScreen::bottomCommentSection(const PostDetail& detail) {
  ViewPtr inner;
  if (session_.isReplying(CommentsSession::kBottomAnchor)) {
    inner = composer(detail, CommentsSession::kBottomAnchor, PostsText::kBottomPlaceholder);
  } else {
    ViewPtr label = HStack({Icon("bubble.left", PostsLayout::kActionIconSize), Text(PostsText::kCommentButton)}, 6);
    inner = Accessible(Button(label, [this] { session_.beginReply(CommentsSession::kBottomAnchor); }, ButtonStyles::form())->id("comment-button"),
                       PostsText::kCommentButton);
  }
  return VStack({inner}, PostsLayout::kCardSpacing, HAlign::Leading)->maxWidth(Alignment::leading())->padding(PostsLayout::kScreenPadding);
}

ViewPtr PostScreen::content(const PostDetail& detail) {
  std::vector<ViewPtr> sections{postBody(detail), commentsSection(detail), bottomCommentSection(detail)};
  return VStack(sections, 0, HAlign::Center)->maxWidth(Alignment::top());
}

ViewPtr PostScreen::toolbarTrailing() {
  if (reloading_) return ProgressSpinner(20);
  return Accessible(ToolbarIconButton("arrow.clockwise", [this] { reload(); }), PostsText::kReload);
}

void PostScreen::runScrollToComment() {
  if (!scrollArmed_ || !pendingScroll_ || !detail_) return;
  if (++scrollTries_ > kMaxScrollTries) {
    scrollArmed_ = false;
    return;
  }
  if (auto y = scroll_.offsetForTop(*pendingScroll_)) {
    scroll_.animateTo(*y, PostsTiming::kScrollAnimationSeconds);
    scrollArmed_ = false;
    scroll_.unwatchAnchor(*pendingScroll_);
    pendingScroll_.reset();
  } else {
    UiState::instance().animating = true;  // keep rendering until the comment is placed
  }
}

// A change of the mention list height re-scrolls the composer anchor to the bottom (PostView.swift:102-107).
void PostScreen::followMentionList() {
  // The anchor positions come from the previous frame, so the scroll runs one frame after the height changed.
  if (followPending_) {
    followPending_ = false;
    if (auto y = scroll_.offsetForBottom(CommentEditor::scrollAnchorName())) scroll_.jumpTo(*y);
  }
  const float height = session_.isComposing() ? session_.mentionListHeight() : 0.0f;
  if (height != lastMentionHeight_) {
    lastMentionHeight_ = height;
    followPending_ = true;
    UiState::instance().animating = true;
  }
}

ViewPtr PostScreen::body() {
  if (!detail_) return ProgressSpinner(28)->maxSize()->background(Palette::bg1());
  session_.beginFrame();
  runScrollToComment();
  scroll_.tick();
  followMentionList();
  ScrollOptions options;
  options.scrollKey = scroll_.scrollKey();
  ViewPtr list = scroll_.markViewport(ScrollView(scroll_.markContent(ContentColumn(content(*detail_))), options)->maxSize(Alignment::topLeading()));
  session_.endFrame();
  return list->maxSize(Alignment::topLeading())->background(Palette::bg1())->foreground(Palette::fg1());
}

}  // namespace dp
31.1ms