#include "mologram/ui/ComposerSuggest.hpp"
#include <algorithm>
#include "mologram/ui/dialogs/DialogUtil.hpp"
namespace mologram::ui {
using namespace ttgui;
ComposerSuggest::ComposerSuggest(UiContext& c, ChatSession& s) : kit_(c.kit), app_(c.app), client_(c.client), s_(s) {
// Only references to objects that outlive every chat session are kept (not the UiContext itself).
auto self = self_;
s.surface().composer->editor->onChanged.connect([this, self]() { if (*self) refresh(); });
}
ComposerSuggest::~ComposerSuggest() {
*self_ = false;
close();
}
bool ComposerSuggest::visible() const { return win_ && alive_ && *alive_; }
int ComposerSuggest::selected() const { return visible() && list_ ? list_->selected : -1; }
void ComposerSuggest::close() {
if (visible()) kit_.close(win_);
win_ = nullptr;
list_ = nullptr;
items_.clear();
}
void ComposerSuggest::loadPeople() {
if (loading_ || !s_.isOpen()) return;
Peer p = s_.peer();
loading_ = true;
peopleFor_ = p.key();
auto self = self_;
js::Object params;
params["peer"] = p.toJson();
if (p.kind == PeerKind::User) { // a private chat has one person to mention
client_.request("load the person", "peer.info", std::move(params), [this, self](const RpcResult& r) {
if (!*self) return;
loading_ = false;
people_ = {PeerInfo::fromJson(r.value)};
refresh();
}, [this, self](const RpcError&) { if (*self) loading_ = false; });
} else {
client_.request("load members", "peer.members", std::move(params), [this, self](const RpcResult& r) {
if (!*self) return;
loading_ = false;
people_.clear();
if (const js::Array* a = js::getArr(r.value, "members")) for (const auto& e : *a) people_.push_back(PeerInfo::fromJson(e));
refresh();
}, [this, self](const RpcError&) { if (*self) loading_ = false; });
}
}
void ComposerSuggest::refresh() {
Composer* comp = s_.surface().composer;
if (!comp || !s_.isOpen()) { close(); return; }
TextEditor* ed = comp->editor;
ed->ensureValid();
auto tok = Suggest::tokenAt(ed->lines[(size_t)ed->cy], (size_t)ed->cx);
if (!tok) { close(); return; }
token_ = *tok;
std::vector<Suggestion> found;
if (tok->trigger == '@') {
if (peopleFor_ != s_.peer().key()) { people_.clear(); loadPeople(); }
found = Suggest::mentions(people_, tok->prefix);
} else if (tok->trigger == '#') {
std::vector<std::string> texts;
for (const auto& m : s_.surface().view->msgs) texts.push_back(m.text);
found = Suggest::hashtags(texts, tok->prefix);
} else {
found = Suggest::commands(s_.botCommands(), tok->prefix);
}
// typing exactly a suggestion with nothing else to choose from is complete: nothing left to offer
if (found.size() == 1 && found[0].insert == std::string(1, tok->trigger) + tok->prefix) found.clear();
if (found.empty()) { close(); return; }
items_ = std::move(found);
show();
}
void ComposerSuggest::show() {
Composer* comp = s_.surface().composer;
Rect a = comp->absoluteBounds();
Rect work = app_.wm.workArea;
int rows = std::min<int>((int)items_.size(), 8);
int h = rows + 2;
int w = std::min(46, std::max(20, a.w - 2));
int x = std::clamp(a.x + 1, work.x, std::max(work.x, work.right() - w));
int y = std::max(work.y, a.y - h);
std::vector<std::string> shown;
for (const auto& s : items_) shown.push_back(s.shown);
if (!visible()) {
Widget* prev = app_.focusedWidget;
Window* prevWin = app_.wm.focusedWin;
win_ = app_.wm.createWindow("Suggestions", "lightblue", {x, y, w, h});
win_->appName = "SuggestPopup";
win_->closable = false;
win_->resizable = false;
win_->popFrames = 0;
list_ = new ListBox();
list_->cfg = &app_.cfg;
win_->setContent(std::unique_ptr<Widget>(list_));
alive_ = dlg::track(win_);
list_->onActivated.connect([this](int i) { accept(i); });
if (prevWin) app_.wm.focusWindow(prevWin);
app_.setFocused(prev); // the composer keeps the keyboard
} else {
win_->bounds = {x, y, w, h};
}
list_->items = shown;
list_->selected = std::min(std::max(list_->selected, 0), (int)shown.size() - 1);
win_->layout();
}
bool ComposerSuggest::handleKey(const KeyEventData& k) {
if (!visible()) return false;
if (k.code == KeyCode::Escape) { close(); return true; }
if (k.code == KeyCode::Down) { list_->selected = std::min(list_->selected + 1, (int)items_.size() - 1); return true; }
if (k.code == KeyCode::Up) { list_->selected = std::max(list_->selected - 1, 0); return true; }
if (k.code == KeyCode::Tab || (k.code == KeyCode::Enter && !k.shift)) { accept(list_->selected); return true; }
return false;
}
void ComposerSuggest::accept(int index) {
if (index < 0 || index >= (int)items_.size()) return;
Composer* comp = s_.surface().composer;
TextEditor* ed = comp->editor;
ed->ensureValid();
Suggestion s = items_[(size_t)index];
size_t caret = 0;
std::string& line = ed->lines[(size_t)ed->cy];
line = Suggest::apply(line, token_, (size_t)ed->cx, s, caret);
ed->cx = (int)caret;
close();
ed->onChanged.emit();
}
} // namespace mologram::ui