#include "screens/conversation/ConversationScreen.hpp"
#include <algorithm>
#include <chrono>
#include "core/Timer.hpp"
#include "screens/AppContext.hpp"
#include "screens/components/Box.hpp"
#include "screens/components/MessageBubble.hpp"
#include "screens/components/TypingIndicator.hpp"
#include "screens/conversation/ComposerRow.hpp"
#include "spec/Layout.hpp"
#include "spec/ModelLimits.hpp"
#include "spec/SocialSpec.hpp"
#include "ui/Controls.hpp"
#include "ui/Palette.hpp"
#include "ui/TextInput.hpp"
namespace dp {
using namespace ui;
using S = spec::SocialStrings;
using M = spec::SocialMetrics;
using T = spec::SocialTiming;
namespace {
const char* const kScrollKey = "conversation-scroll";
// onGeometryChange(for: width): reports the width it is laid out in.
class WidthProbe : public View {
public:
explicit WidthProbe(std::function<void(float)> report) : report_(std::move(report)) {}
protected:
Size compute(const Proposal& p) override {
return {p.w ? std::min(*p.w, 10000.0f) : 0.0f, p.h ? std::min(*p.h, 10000.0f) : 0.0f};
}
public:
void place(const Rect& r) override {
frame_ = r;
report_(r.w);
}
private:
std::function<void(float)> report_;
};
double steadyNow() {
return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
}
float easeInOut(float t) { return t < 0.5f ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t); }
} // namespace
ConversationScreen::ConversationScreen(User otherUser)
: model_(std::move(otherUser), AppContext::api()),
typingFade_(T::kSnappySeconds),
buttonFade_(T::kSnappySeconds) {
focus_ = std::make_unique<WindowFocusWatcher>([this, alive = alive_](bool active) {
if (!*alive || !appeared_) return;
if (active) loadAndConnect();
else model_.stopRealtime();
});
}
ConversationScreen::~ConversationScreen() {
*alive_ = false;
onDisappear();
}
float ConversationScreen::bubbleMaxWidth() const {
if (scrollViewWidth_ <= 0) return M::kBubbleDefaultWidth;
return std::max(scrollViewWidth_ - M::kInsetH * 2 - M::kBubbleOppositeGap, M::kBubbleMinWidth);
}
void ConversationScreen::loadAndConnect() {
model_.load([this, alive = alive_] {
if (*alive && appeared_) model_.startRealtime();
});
}
void ConversationScreen::onAppear() {
appeared_ = true;
hiddenByTab_ = false;
lastBodyAt_ = steadyNow();
startWatchdog();
loadAndConnect();
}
// The tab shell only builds the selected tab, so a conversation in a hidden tab never gets onDisappear. A 1 s tick
// (which also keeps the relative time labels fresh) notices that body() stopped running and stops the realtime
// session; the next body() call reconnects, like the SwiftUI onDisappear / onAppear pair of a TabView.
void ConversationScreen::startWatchdog() {
stopWatchdog();
watchdog_ = Timer::after(T::kWatchdogMs, [this, alive = alive_] {
if (*alive) watchdogTick();
});
}
void ConversationScreen::stopWatchdog() {
if (watchdog_) watchdog_->cancel();
watchdog_.reset();
}
void ConversationScreen::watchdogTick() {
if (!appeared_) return;
if (!hiddenByTab_ && steadyNow() - lastBodyAt_ > T::kHiddenAfterSeconds) {
hiddenByTab_ = true;
model_.stopRealtime();
}
startWatchdog();
}
void ConversationScreen::onDisappear() {
if (!appeared_) return;
appeared_ = false;
stopWatchdog();
model_.stopRealtime();
model_.deleteUnsubmittedAttachments();
if (uploader_) uploader_->forget();
}
ViewPtr ConversationScreen::toolbarTrailing() {
if (model_.isReloading()) return ProgressSpinner(20)->frame(spec::Layout::kNavButtonSize, spec::Layout::kNavButtonSize);
return ToolbarIconButton("arrow.clockwise", [this, alive = alive_] { if (*alive) model_.reload(); });
}
void ConversationScreen::onGeometry(float offset, float maxOffset, float) {
lastOffset_ = offset;
lastMax_ = maxOffset;
const bool atBottom = (maxOffset - offset) <= M::kAtBottomDistance;
if (atBottom != isAtBottom_) {
isAtBottom_ = atBottom;
UiState::instance().animating = true;
}
}
void ConversationScreen::scrollToBottom(bool animated) {
if (animated) {
scrollAnimating_ = true;
scrollAnimStart_ = UiState::instance().now;
scrollAnimFrom_ = lastOffset_;
UiState::instance().animating = true;
} else {
ScrollCommand::toOffset(kScrollKey, kInf);
}
}
ViewPtr ConversationScreen::scrollToBottomButton() {
const float p = buttonFade_.update(!isAtBottom_);
if (p <= 0.001f) return nullptr;
ViewPtr button = Button(Icon("chevron.down", 17), [this, alive = alive_] { if (*alive) scrollToBottom(true); },
ButtonStyles::accentGradient(true))
->id(S::kScrollToLatest);
return button->padding(M::kScrollButtonPadding)->scale(std::max(p, 0.01f))->opacity(p);
}
ViewPtr ConversationScreen::messagesArea() {
QuoteComposer quote{true, [this, alive = alive_](const std::string& text) { if (*alive) model_.appendToDraft(text); }};
std::vector<ViewPtr> bubbles;
for (const Message& m : model_.messages()) bubbles.push_back(MessageBubbleView(m, bubbleMaxWidth(), quote));
ViewPtr list = VStack(bubbles, M::kMessageSpacing)->maxWidth()->paddingH(M::kInsetH)->paddingV(M::kMessagesVertical);
if (scrollAnimating_) {
UiState& ui = UiState::instance();
const float t = std::clamp(static_cast<float>((ui.now - scrollAnimStart_) / T::kScrollSeconds), 0.0f, 1.0f);
if (t >= 1.0f) {
scrollAnimating_ = false;
ScrollCommand::toOffset(kScrollKey, kInf);
} else {
ScrollCommand::toOffset(kScrollKey, scrollAnimFrom_ + (lastMax_ - scrollAnimFrom_) * easeInOut(t));
ui.animating = true;
}
}
ScrollOptions so;
so.anchorBottom = true;
so.anchorThreshold = M::kAtBottomDistance;
so.scrollKey = kScrollKey;
so.onGeometry = [this, alive = alive_](float o, float m, float v) { if (*alive) onGeometry(o, m, v); };
ViewPtr scroll = ScrollView(list, so)->background(std::make_shared<WidthProbe>([this, alive = alive_](float w) {
if (!*alive || w == scrollViewWidth_) return;
scrollViewWidth_ = w;
UiState::instance().animating = true;
}));
// The overlay layers are always present (possibly empty) so the scroll view keeps its identity, and with it its
// scroll offset, while the typing indicator and the scroll to latest button come and go.
const float typing = typingFade_.update(model_.isOtherTyping());
ViewPtr typingLayer = typing > 0.001f
? TypingIndicatorView(model_.otherUser().username)->paddingBottom(M::kTypingBottom)->opacity(typing)
: EmptyView();
ViewPtr buttonLayer = scrollToBottomButton();
scroll = scroll->overlay(typingLayer, Alignment::bottom())->overlay(buttonLayer ? buttonLayer : EmptyView(), Alignment::bottomTrailing());
return scroll->maxSize();
}
ViewPtr ConversationScreen::uploader(bool small) {
// `.id(attachmentsResetToken)`: a new uploader (seeded with the composer attachments) per token and per size.
if (!uploader_ || small != uploaderSmall_ || uploaderToken_ != attachmentsResetToken_) {
AttachmentUploader::Options o;
o.isSmall = small;
o.attachments = model_.attachments();
o.onAttachmentsChange = [this, alive = alive_](const std::vector<UploadResponse>& list) {
if (*alive) model_.setAttachments(list);
};
uploader_ = std::make_unique<AttachmentUploader>(std::move(o));
uploaderSmall_ = small;
uploaderToken_ = attachmentsResetToken_;
}
return uploader_->view();
}
ViewPtr ConversationScreen::sendButton() {
const bool can = model_.canSend();
ViewPtr label = model_.isSending() ? ProgressSpinner(17) : Icon("paperplane.fill", 17);
ViewPtr button = Button(label, [this, alive = alive_] {
model_.send([this, alive](bool ok) { if (*alive && ok) ++attachmentsResetToken_; });
}, ButtonStyles::accentGradient(true))->id(S::kSendMessage);
return button->disabled(!can)->opacity(can ? 1.0f : M::kSendOpacityDisabled);
}
ViewPtr ConversationScreen::composer() {
Binding draft{[this] { return model_.draft(); }, [this, alive = alive_](const std::string& s) { if (*alive) model_.setDraft(s); }};
TextInputOptions options;
options.placeholder = S::kComposerPlaceholder;
options.minLines = 1;
options.maxLines = M::kComposerMaxLines;
ViewPtr field = DevPlaceField(TextEditor(draft, options), Palette::bg0());
std::vector<ViewPtr> counters{CharacterCounter(model_.draftCount(), static_cast<int>(spec::ModelLimits::kMaxDirectMessageLength),
model_.minCharacterCount())};
if (model_.attachments().empty()) {
counters.push_back(Spacer(0));
counters.push_back(uploader(true));
}
ViewPtr below = HStack(counters, M::kComposerRowSpacing)->paddingH(M::kCounterPadH);
std::vector<ViewPtr> rows{ComposerRow(field, below, sendButton())};
if (!model_.attachments().empty()) rows.push_back(uploader(false)->maxWidth(Alignment::leading())->paddingTop(M::kComposerSpacing));
return VStack(rows, M::kComposerSpacing, HAlign::Leading)
->paddingH(M::kComposerPadH)->paddingV(M::kComposerPadV)->maxWidth()
->background(Palette::bg1())
->overlay(Divider(Palette::separator()), Alignment::top());
}
ViewPtr ConversationScreen::body() {
lastBodyAt_ = steadyNow();
if (hiddenByTab_ && appeared_) {
hiddenByTab_ = false;
loadAndConnect();
}
return VStack({messagesArea(), composer()}, 0, HAlign::Center)->maxSize(Alignment::topLeading());
}
} // namespace dp