#include "screens/components/MentionSuggestions.hpp"
#include <algorithm>
#include <cctype>
#include "core/Log.hpp"
#include "core/Timer.hpp"
#include "screens/AppContext.hpp"
#include "screens/components/AccessibleLabel.hpp"
#include "screens/components/Box.hpp"
#include "screens/components/UserViews.hpp"
#include "spec/ComposeSpec.hpp"
#include "store/AppState.hpp"
#include "ui/Palette.hpp"
namespace dp {
using namespace ui;
using spec::ComposeSpec;
namespace {
bool isMentionByte(unsigned char c) { return c >= 0x80 || std::isalnum(c) || c == '_'; }
std::size_t prevBoundary(const std::string& s, std::size_t pos) {
if (pos == 0) return 0;
--pos;
while (pos > 0 && (static_cast<unsigned char>(s[pos]) & 0xC0) == 0x80) --pos;
return pos;
}
std::size_t nextBoundary(const std::string& s, std::size_t pos) {
if (pos >= s.size()) return s.size();
++pos;
while (pos < s.size() && (static_cast<unsigned char>(s[pos]) & 0xC0) == 0x80) ++pos;
return pos;
}
bool isSpaceByte(unsigned char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'; }
constexpr float kRowHeight = 30 + 2 * ComposeSpec::kMentionRowPadV;
} // namespace
std::optional<MentionToken> MentionToken::active(const std::string& text, std::optional<int> caretOffset) {
std::size_t caret = caretOffset ? static_cast<std::size_t>(std::max(0, *caretOffset)) : text.size();
caret = std::min(caret, text.size());
std::size_t cursor = caret;
while (cursor > 0) {
const std::size_t previous = prevBoundary(text, cursor);
const unsigned char ch = static_cast<unsigned char>(text[previous]);
if (ch == '@') {
const bool wordStart = previous == 0 || isSpaceByte(static_cast<unsigned char>(text[prevBoundary(text, previous)]));
if (!wordStart) return std::nullopt;
MentionToken t;
t.begin = previous;
t.query = text.substr(cursor, caret - cursor);
std::size_t end = caret;
while (end < text.size() && isMentionByte(static_cast<unsigned char>(text[end]))) end = nextBoundary(text, end);
t.end = end;
return t;
}
if (!isMentionByte(ch)) return std::nullopt;
cursor = previous;
}
return std::nullopt;
}
MentionSuggestions::MentionSuggestions() : alive_(std::make_shared<bool>(true)) {}
MentionSuggestions::~MentionSuggestions() {
*alive_ = false;
if (timer_) timer_->cancel();
if (search_) search_->cancel();
}
std::vector<UserSearch::Result> MentionSuggestions::mentionable(const std::vector<UserSearch::Result>& users) const {
std::vector<UserSearch::Result> out;
for (const auto& u : users) {
if (AppState::instance().isCurrentUser(u.id)) continue;
out.push_back(u);
if (out.size() >= ComposeSpec::kMentionMaxSuggestions) break;
}
return out;
}
void MentionSuggestions::deactivate() {
if (timer_) timer_->cancel();
if (search_) search_->cancel();
timer_.reset();
search_.reset();
activeQuery_.reset();
active_ = false;
suggestions_.clear();
}
void MentionSuggestions::dismiss() { deactivate(); }
void MentionSuggestions::update(const std::string& text, std::optional<int> caret, const std::vector<UserSearch::Result>& participants) {
participants_ = participants;
const auto token = MentionToken::active(text, caret);
if (!token) {
if (active_ || !suggestions_.empty() || timer_ || search_) deactivate();
return;
}
active_ = true;
std::string query = token->query;
if (query.size() > ComposeSpec::kMentionMaxQueryChars) query.resize(ComposeSpec::kMentionMaxQueryChars);
if (query.empty()) {
if (timer_) timer_->cancel();
if (search_) search_->cancel();
timer_.reset();
search_.reset();
activeQuery_.reset();
suggestions_ = mentionable(participants_);
} else if (!activeQuery_ || *activeQuery_ != query) {
activeQuery_ = query;
scheduleSearch(query);
}
}
void MentionSuggestions::scheduleSearch(const std::string& query) {
if (timer_) timer_->cancel();
if (search_) search_->cancel();
auto alive = alive_;
timer_ = Timer::after(ComposeSpec::kMentionDebounceMs, [this, alive, query] {
if (!*alive) return;
search_ = AppContext::api().usersForMentioning(query, [this, alive, query](Result<UserSearch> r) {
if (!*alive) return;
if (!activeQuery_ || *activeQuery_ != query) return; // stale
if (r.ok()) {
suggestions_ = mentionable(r.value().results);
} else {
Log::warn("Mention search failed for \"" + query + "\": " + r.error().message);
}
});
});
}
float MentionSuggestions::listHeight() const {
if (!isShowing()) return 0;
const float rows = static_cast<float>(suggestions_.size()) * kRowHeight;
return std::min(std::max(rows, ComposeSpec::kMentionMinHeight), ComposeSpec::kMentionMaxHeight);
}
ViewPtr MentionSuggestions::view(std::function<void(const UserSearch::Result&)> onSelect) {
if (!isShowing()) return EmptyView();
std::vector<ViewPtr> rows;
for (const UserSearch::Result& s : suggestions_) {
const UserSearch::Result copy = s;
ViewPtr row = HStack({UserImage(s.avatarSeed.value_or(s.username), AvatarSize::Small),
Text(s.username)->weight(Weight::Medium)->lineLimit(1)->maxWidth(Alignment::leading())},
ComposeSpec::kMentionRowSpacing)
->paddingH(ComposeSpec::kMentionRowPadH)->paddingV(ComposeSpec::kMentionRowPadV)
->foreground(Palette::fg1())->maxWidth(Alignment::leading())->contentShape();
rows.push_back(Button(row, [onSelect, copy] { if (onSelect) onSelect(copy); }, ButtonStyles::plain())->id("mention-" + s.username));
}
ViewPtr list = ScrollView(VStack(rows, 0, HAlign::Leading))->frame(std::nullopt, listHeight())->maxWidth()
->clipRounded(ComposeSpec::kMentionRadius);
BoxStyle style;
style.borderOpacity = 0.5f;
style.corner = BoxStyle::Corner::Big;
style.padding = BoxStyle::Pad::None;
ViewPtr close = WithAccessibleLabel(Button(Icon("xmark", 11)->weight(Weight::Semibold)->foreground(Palette::fg2())->padding(ComposeSpec::kMentionCloseInner)
->background(Palette::bg1(), Corners::all(100))->padding(ComposeSpec::kMentionCloseOuter),
[this] { dismiss(); }, ButtonStyles::plain())->id("close-suggestions"),
ComposeSpec::kLabelCloseSuggestions);
return BoxView(list, style)->overlay(close, Alignment::topTrailing())
->shadow(Color{0, 0, 0, 51}, 12, 0, 4, Corners::all(ComposeSpec::kMentionRadius))
->paddingBottom(ComposeSpec::kMentionBottomGap);
}
std::optional<MentionSuggestions::Completion> MentionSuggestions::complete(const std::string& text, std::optional<int> caret,
const std::string& username) {
const auto token = MentionToken::active(text, caret);
if (!token) return std::nullopt;
const bool followedBySpace = token->end < text.size() && isSpaceByte(static_cast<unsigned char>(text[token->end]));
const std::string insertion = followedBySpace ? "@" + username : "@" + username + " ";
Completion c;
c.text = text.substr(0, token->begin) + insertion + text.substr(token->end);
c.caret = static_cast<int>(token->begin + insertion.size()) + (followedBySpace ? 1 : 0);
return c;
}
bool MentionSuggestions::insertMention(TextInputHandle& handle, const Binding& text, const std::string& username) {
if (!text.get || !text.set) return false;
const auto done = complete(text.get(), handle.caret(), username);
if (!done) return false;
text.set(done->text);
handle.setCaret(done->caret);
return true;
}
} // namespace dp