549 lines
20 KiB
C++
549 lines
20 KiB
C++
// SPDX-License-Identifier: GPL-3.0-only
|
|
#include "modern/ui/select_menu.hpp"
|
|
#include <RmlUi/Core.h>
|
|
#include <RmlUi/Core/ElementText.h>
|
|
#include <RmlUi/Core/Elements/ElementFormControlSelect.h>
|
|
#include <RmlUi/Core/StringUtilities.h>
|
|
#include <algorithm>
|
|
#include <chrono>
|
|
#include <cmath>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
namespace bmh::modern_ui {
|
|
namespace {
|
|
using Select = Rml::ElementFormControlSelect;
|
|
using Clock = std::chrono::steady_clock;
|
|
|
|
std::string plain_text(Rml::Element *node) {
|
|
if (auto *text = dynamic_cast<Rml::ElementText *>(node))
|
|
return Rml::StringUtilities::DecodeRml(text->GetText());
|
|
std::string text;
|
|
for (int i = 0; i < node->GetNumChildren(); ++i)
|
|
text += plain_text(node->GetChild(i));
|
|
return text;
|
|
}
|
|
std::string tidy(std::string text) {
|
|
std::string out;
|
|
bool space = false;
|
|
for (const auto c : text) {
|
|
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
|
|
space = !out.empty();
|
|
continue;
|
|
}
|
|
if (space)
|
|
out += ' ';
|
|
space = false;
|
|
out += c;
|
|
}
|
|
return out;
|
|
}
|
|
// Country/league labels use Latin scripts. Keep UTF-8 intact and support their
|
|
// common accented capitals, rather than lowercasing individual non-ASCII bytes.
|
|
std::string folded(std::string text) {
|
|
for (size_t i = 0; i < text.size(); ++i) {
|
|
const auto c = static_cast<unsigned char>(text[i]);
|
|
if (c >= 'A' && c <= 'Z')
|
|
text[i] = char(c + ('a' - 'A'));
|
|
else if (c == 0xc3 && i + 1 < text.size()) {
|
|
const auto next = static_cast<unsigned char>(text[i + 1]);
|
|
if (next >= 0x80 && next <= 0x9e && next != 0x97)
|
|
text[++i] = char(next + 0x20);
|
|
}
|
|
}
|
|
return text;
|
|
}
|
|
bool within(Rml::Element *node, const Rml::Element *root) {
|
|
for (; node; node = node->GetParentNode())
|
|
if (node == root)
|
|
return true;
|
|
return false;
|
|
}
|
|
Select *native_select(Rml::Element *node) {
|
|
for (; node; node = node->GetParentNode())
|
|
if (auto *select = dynamic_cast<Select *>(node))
|
|
return select;
|
|
return nullptr;
|
|
}
|
|
bool supported(Select *select) {
|
|
return select && !select->GetId().empty() &&
|
|
!select->HasAttribute("multiple");
|
|
}
|
|
bool available(Select *select) {
|
|
if (!supported(select) || select->IsDisabled() || !select->IsVisible(true))
|
|
return false;
|
|
for (auto *node = select->GetParentNode(); node; node = node->GetParentNode())
|
|
if (node->HasAttribute("inert") || node->HasAttribute("hidden"))
|
|
return false;
|
|
return true;
|
|
}
|
|
bool pixels(Rml::Element &node, Rml::PropertyId property, float value) {
|
|
const auto *old = node.GetLocalProperty(property);
|
|
if (old && old->unit == Rml::Unit::PX &&
|
|
std::abs(old->Get<float>() - value) < .02f)
|
|
return false;
|
|
node.SetProperty(property, Rml::Property(value, Rml::Unit::PX));
|
|
return true;
|
|
}
|
|
} // namespace
|
|
|
|
struct SelectMenu::Impl {
|
|
struct Option {
|
|
std::string text, value;
|
|
bool disabled = false;
|
|
bool operator==(const Option &) const = default;
|
|
};
|
|
Rml::Context &context;
|
|
Rml::ElementDocument &document;
|
|
CheckMarkupFn check;
|
|
CommitFn on_commit;
|
|
Rml::ObserverPtr<Rml::Element> anchor, canvas, popup;
|
|
std::vector<Option> options;
|
|
std::string id, typed;
|
|
Clock::time_point typed_at{};
|
|
int cursor = -1, selected = -1;
|
|
bool open = false, league = false, reveal_cursor = false,
|
|
focus_cursor = false;
|
|
bool suppress_right_release = false, suppress_context_menu = false;
|
|
Clock::time_point right_dismissed_at{};
|
|
float max_height = 0;
|
|
|
|
Impl(Rml::Context &c, Rml::ElementDocument &d, CheckMarkupFn glyph,
|
|
CommitFn commit)
|
|
: context(c), document(d), check(std::move(glyph)),
|
|
on_commit(std::move(commit)) {}
|
|
|
|
Select *control() const { return dynamic_cast<Select *>(anchor.get()); }
|
|
std::vector<Option> read_options(Select &select) const {
|
|
std::vector<Option> rows;
|
|
const int count = select.GetNumOptions();
|
|
rows.reserve(size_t(std::max(0, count)));
|
|
for (int i = 0; i < count; ++i) {
|
|
auto *node = select.GetOption(i);
|
|
rows.push_back({tidy(plain_text(node)),
|
|
node->GetAttribute<Rml::String>("value", ""),
|
|
node->HasAttribute("disabled")});
|
|
}
|
|
return rows;
|
|
}
|
|
void remove_popup() {
|
|
if (popup)
|
|
if (auto *parent = popup->GetParentNode())
|
|
parent->RemoveChild(popup.get());
|
|
popup.reset();
|
|
}
|
|
void close(bool focus) {
|
|
auto old = anchor;
|
|
if (auto *select = control()) {
|
|
select->HideSelectBox();
|
|
if (select->GetAttribute<Rml::String>("aria-expanded", "") != "false")
|
|
select->SetAttribute("aria-expanded", "false");
|
|
select->RemoveAttribute("aria-controls");
|
|
}
|
|
// An ongoing Tab event can still hold its original popup-row target.
|
|
// Hide now, but destroy only at the next safe layout/render boundary.
|
|
if (popup)
|
|
popup->SetProperty("display", "none");
|
|
open = false;
|
|
anchor.reset();
|
|
canvas.reset();
|
|
id.clear();
|
|
options.clear();
|
|
typed.clear();
|
|
cursor = selected = -1;
|
|
max_height = 0;
|
|
reveal_cursor = focus_cursor = false;
|
|
if (focus)
|
|
if (auto *select = dynamic_cast<Select *>(old.get()); available(select))
|
|
select->Focus(true);
|
|
}
|
|
int endpoint(bool last) const {
|
|
if (last) {
|
|
for (int i = int(options.size()) - 1; i >= 0; --i)
|
|
if (!options[size_t(i)].disabled)
|
|
return i;
|
|
} else {
|
|
for (size_t i = 0; i < options.size(); ++i)
|
|
if (!options[i].disabled)
|
|
return int(i);
|
|
}
|
|
return -1;
|
|
}
|
|
void mark_cursor(bool focus) {
|
|
if (!popup)
|
|
return;
|
|
for (int i = 0; i < popup->GetNumChildren(); ++i) {
|
|
auto *row = popup->GetChild(i);
|
|
const bool active = i == cursor;
|
|
if (row->IsClassSet("is-cursor") != active)
|
|
row->SetClass("is-cursor", active);
|
|
}
|
|
if (cursor >= 0)
|
|
if (auto *row = popup->GetChild(cursor)) {
|
|
if (focus)
|
|
focus_cursor = true;
|
|
reveal_cursor = true;
|
|
}
|
|
}
|
|
bool show(Select &select, bool last) {
|
|
close(false);
|
|
remove_popup();
|
|
if (!available(&select))
|
|
return false;
|
|
auto rows = read_options(select);
|
|
if (rows.empty() || std::none_of(rows.begin(), rows.end(),
|
|
[](const auto &o) { return !o.disabled; }))
|
|
return false;
|
|
auto *stage = document.GetElementById("canvas");
|
|
if (!stage)
|
|
return false;
|
|
anchor = select.GetObserverPtr();
|
|
canvas = stage->GetObserverPtr();
|
|
id = select.GetId();
|
|
options = std::move(rows);
|
|
selected = select.GetSelection();
|
|
league =
|
|
select.GetAttribute<Rml::String>("data-select-style", "") == "league";
|
|
cursor = last ? endpoint(true) : selected;
|
|
if (cursor < 0 || cursor >= int(options.size()) ||
|
|
options[size_t(cursor)].disabled)
|
|
cursor = endpoint(false);
|
|
std::string rml;
|
|
const auto marker = check ? check(league ? 28.f : 24.f) : std::string();
|
|
for (size_t i = 0; i < options.size(); ++i) {
|
|
const auto &option = options[i];
|
|
rml += "<button type=\"button\" class=\"native-select-option\" "
|
|
"id=\"native-select-option-" +
|
|
std::to_string(i) +
|
|
"\" role=\"option\" tabindex=\"-1\" data-index=\"" +
|
|
std::to_string(i) + "\" aria-selected=\"" +
|
|
(int(i) == selected ? "true" : "false") + "\" " +
|
|
(option.disabled ? "disabled" : "") +
|
|
"><span class=\"native-select-check\" aria-hidden=\"true\">" +
|
|
(int(i) == selected ? marker : "") +
|
|
"</span><span class=\"native-select-text\">" +
|
|
editor::escaped(option.text) + "</span></button>";
|
|
}
|
|
auto layer = document.CreateElement("div");
|
|
layer->SetId("native-select-menu");
|
|
layer->SetClassNames(std::string("native-select-menu") +
|
|
(league ? " league" : ""));
|
|
layer->SetAttribute("role", "listbox");
|
|
layer->SetAttribute("aria-label", select.GetAttribute<Rml::String>(
|
|
"aria-label", "Auswahl"));
|
|
layer->SetAttribute("data-select-id", id);
|
|
layer->SetInnerRML(rml);
|
|
popup = stage->AppendChild(std::move(layer))->GetObserverPtr();
|
|
select.HideSelectBox();
|
|
select.SetAttribute("aria-haspopup", "listbox");
|
|
select.SetAttribute("aria-expanded", "true");
|
|
select.SetAttribute("aria-controls", "native-select-menu");
|
|
open = true;
|
|
mark_cursor(true);
|
|
layout();
|
|
return true;
|
|
}
|
|
void commit(int index) {
|
|
if (!open)
|
|
return;
|
|
if (!fresh()) {
|
|
close(false);
|
|
return;
|
|
}
|
|
if (index < 0 || index >= int(options.size()) ||
|
|
options[size_t(index)].disabled)
|
|
return;
|
|
auto old = anchor;
|
|
const auto committed_id = id;
|
|
const bool reselected = index == selected;
|
|
close(true);
|
|
if (auto *select = dynamic_cast<Select *>(old.get()); available(select)) {
|
|
// A changed index sends the native change itself. Reselection sends none.
|
|
if (!reselected)
|
|
select->SetSelection(index);
|
|
if (on_commit)
|
|
on_commit(committed_id, index, reselected);
|
|
}
|
|
}
|
|
void move(int direction) {
|
|
if (options.empty())
|
|
return;
|
|
int next = cursor;
|
|
for (size_t tried = 0; tried < options.size(); ++tried) {
|
|
next = (next + direction + int(options.size())) % int(options.size());
|
|
if (!options[size_t(next)].disabled) {
|
|
cursor = next;
|
|
mark_cursor(true);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
void type(const std::string &text) {
|
|
if (text.empty())
|
|
return;
|
|
const auto now = Clock::now();
|
|
typed =
|
|
now - typed_at < std::chrono::milliseconds(700) ? typed + text : text;
|
|
typed_at = now;
|
|
const auto prefix = folded(typed);
|
|
for (size_t i = 0; i < options.size(); ++i)
|
|
if (!options[i].disabled && folded(options[i].text).starts_with(prefix)) {
|
|
cursor = int(i);
|
|
mark_cursor(true);
|
|
return;
|
|
}
|
|
}
|
|
bool fresh() const {
|
|
auto *select = control();
|
|
return available(select) && canvas && popup &&
|
|
document.GetElementById(id) == select &&
|
|
document.GetElementById("canvas") == canvas.get() &&
|
|
select->GetSelection() == selected &&
|
|
read_options(*select) == options;
|
|
}
|
|
void layout() {
|
|
if (!open) {
|
|
remove_popup();
|
|
return;
|
|
}
|
|
if (!fresh()) {
|
|
close(false);
|
|
remove_popup();
|
|
return;
|
|
}
|
|
auto *select = control();
|
|
select->HideSelectBox();
|
|
const float ratio =
|
|
std::max(.001f, context.GetDensityIndependentPixelRatio());
|
|
Rml::Element *owner = select->GetParentNode();
|
|
while (owner && !owner->IsClassSet("window"))
|
|
owner = owner->GetParentNode();
|
|
if (!owner)
|
|
owner = canvas.get();
|
|
const auto owner_at = owner->GetAbsoluteOffset(Rml::BoxArea::Border);
|
|
const auto at = select->GetAbsoluteOffset(Rml::BoxArea::Border);
|
|
const auto size = select->GetBox().GetSize(Rml::BoxArea::Border);
|
|
const auto stage_at = canvas->GetAbsoluteOffset(Rml::BoxArea::Border);
|
|
const auto border_origin =
|
|
owner->GetBox().GetPosition(Rml::BoxArea::Padding);
|
|
const float left_edge = owner_at.x + border_origin.x,
|
|
top_edge = owner_at.y + border_origin.y;
|
|
const float right_edge = left_edge + owner->GetClientWidth();
|
|
const float bottom_edge = top_edge + owner->GetClientHeight();
|
|
const float padding = 20 * ratio, gap = (league ? 12.f : 8.f) * ratio;
|
|
const float width =
|
|
std::min(std::max(0.f, right_edge - left_edge - 2 * padding),
|
|
std::max(size.x, 360 * ratio));
|
|
const float left =
|
|
std::clamp(at.x, left_edge + padding,
|
|
std::max(left_edge + padding, right_edge - padding - width));
|
|
const float above = std::max(0.f, at.y - top_edge - padding),
|
|
below = std::max(0.f, bottom_edge - at.y - size.y - padding);
|
|
float cap_dp = league ? 740.f : 480.f;
|
|
const float custom =
|
|
select->GetAttribute<float>("data-select-max-height", cap_dp);
|
|
if (std::isfinite(custom) && custom > 0)
|
|
cap_dp = std::min(cap_dp, custom);
|
|
const float cap = cap_dp * ratio;
|
|
const float desired =
|
|
std::min(float(options.size()) * 58 * ratio + 20 * ratio, cap);
|
|
const bool down = below >= std::min(desired, 220 * ratio) || below >= above;
|
|
max_height = std::min(cap, std::max(0.f, (down ? below : above) - gap));
|
|
bool changed = pixels(*popup.get(), Rml::PropertyId::Width, width);
|
|
changed |= pixels(*popup.get(), Rml::PropertyId::FontSize,
|
|
select->GetComputedValues().font_size());
|
|
changed |= pixels(*popup.get(), Rml::PropertyId::MaxHeight, max_height);
|
|
changed |= pixels(*popup.get(), Rml::PropertyId::Left, left - stage_at.x);
|
|
if (changed)
|
|
context.Update();
|
|
const float height = popup->GetBox().GetSize(Rml::BoxArea::Border).y;
|
|
const float top = down ? at.y + size.y + gap : at.y - height - gap;
|
|
if (pixels(*popup.get(), Rml::PropertyId::Top, top - stage_at.y))
|
|
context.Update();
|
|
if (reveal_cursor && cursor >= 0) {
|
|
if (auto *row = popup->GetChild(cursor)) {
|
|
if (focus_cursor)
|
|
row->Focus(true);
|
|
// Match the HTML list's local scroll adjustment. Pinned RmlUI's
|
|
// generic ScrollIntoView adds the popup border to the start offset,
|
|
// which clips the first row at larger density factors.
|
|
const float row_top = row->GetAbsoluteOffset(Rml::BoxArea::Border).y;
|
|
const float row_bottom =
|
|
row_top + row->GetBox().GetSize(Rml::BoxArea::Border).y;
|
|
const float view_top =
|
|
popup->GetAbsoluteOffset(Rml::BoxArea::Border).y +
|
|
popup->GetClientTop();
|
|
const float view_bottom = view_top + popup->GetClientHeight();
|
|
const float scroll = popup->GetScrollTop();
|
|
if (row_top < view_top)
|
|
popup->SetScrollTop(scroll + row_top - view_top);
|
|
else if (row_bottom > view_bottom)
|
|
popup->SetScrollTop(scroll + row_bottom - view_bottom);
|
|
}
|
|
reveal_cursor = focus_cursor = false;
|
|
}
|
|
}
|
|
Rml::Element *row(Rml::Element *target) const {
|
|
for (auto *node = target; node && node != popup.get();
|
|
node = node->GetParentNode())
|
|
if (node->IsClassSet("native-select-option") && within(node, popup.get()))
|
|
return node;
|
|
return nullptr;
|
|
}
|
|
bool event(Rml::Event &event) {
|
|
const auto type = event.GetType();
|
|
auto *target = event.GetTargetElement();
|
|
const auto consume = [&] {
|
|
event.StopImmediatePropagation();
|
|
return true;
|
|
};
|
|
auto *select = native_select(target);
|
|
if (!suppress_right_release &&
|
|
Clock::now() - right_dismissed_at > std::chrono::milliseconds(500))
|
|
suppress_context_menu = false;
|
|
if (type == "contextmenu") {
|
|
if (open) {
|
|
close(true);
|
|
suppress_context_menu = false;
|
|
return consume();
|
|
}
|
|
if (suppress_context_menu) {
|
|
suppress_context_menu = false;
|
|
return consume();
|
|
}
|
|
}
|
|
if (type == "mouseup" && event.GetParameter<int>("button", 0) == 1 &&
|
|
suppress_right_release) {
|
|
suppress_right_release = false;
|
|
right_dismissed_at = Clock::now();
|
|
return consume();
|
|
}
|
|
if (type == "mousedown") {
|
|
if (event.GetParameter<int>("button", 0) == 1 && open) {
|
|
close(true);
|
|
suppress_right_release = suppress_context_menu = true;
|
|
right_dismissed_at = Clock::now();
|
|
return consume();
|
|
}
|
|
if (event.GetParameter<int>("button", 0) != 1)
|
|
suppress_context_menu = false;
|
|
if (auto *choice = open ? row(target) : nullptr) {
|
|
const int index = choice->GetAttribute<int>("data-index", -1);
|
|
if (index >= 0 && index < int(options.size()) &&
|
|
!options[size_t(index)].disabled) {
|
|
cursor = index;
|
|
mark_cursor(true);
|
|
}
|
|
return consume();
|
|
}
|
|
if (supported(select) && event.GetParameter<int>("button", 0) == 0) {
|
|
if (open && anchor == select)
|
|
close(true);
|
|
else
|
|
show(*select, false);
|
|
return consume();
|
|
}
|
|
if (open && !within(target, popup.get()))
|
|
close(false);
|
|
} else if (type == "click") {
|
|
if (auto *choice = open ? row(target) : nullptr) {
|
|
commit(choice->GetAttribute<int>("data-index", -1));
|
|
return consume();
|
|
}
|
|
if (supported(select))
|
|
return consume(); // Never let the native list open.
|
|
} else if (type == "textinput" && open) {
|
|
typeahead_event(event);
|
|
return consume();
|
|
} else if (type == "keydown") {
|
|
// A keyboard context-menu request starts a new gesture.
|
|
if (!suppress_right_release)
|
|
suppress_context_menu = false;
|
|
const auto key = Rml::Input::KeyIdentifier(
|
|
event.GetParameter<int>("key_identifier", 0));
|
|
if (open) {
|
|
if (key == Rml::Input::KI_TAB) {
|
|
close(true);
|
|
return false;
|
|
}
|
|
if (key == Rml::Input::KI_ESCAPE || key == Rml::Input::KI_F4) {
|
|
close(true);
|
|
return consume();
|
|
}
|
|
if (key == Rml::Input::KI_UP || key == Rml::Input::KI_DOWN) {
|
|
move(key == Rml::Input::KI_UP ? -1 : 1);
|
|
return consume();
|
|
}
|
|
if (key == Rml::Input::KI_HOME || key == Rml::Input::KI_END) {
|
|
cursor = endpoint(key == Rml::Input::KI_END);
|
|
mark_cursor(true);
|
|
return consume();
|
|
}
|
|
if (key == Rml::Input::KI_RETURN || key == Rml::Input::KI_NUMPADENTER ||
|
|
key == Rml::Input::KI_SPACE) {
|
|
commit(cursor);
|
|
return consume();
|
|
}
|
|
// Printable input is handled by textinput, including UTF-8. Consuming
|
|
// keydown prevents native widget navigation or menu-level shortcuts.
|
|
if (!event.GetParameter<int>("ctrl_key", 0) &&
|
|
!event.GetParameter<int>("alt_key", 0) &&
|
|
!event.GetParameter<int>("meta_key", 0))
|
|
return consume();
|
|
} else if (available(select) &&
|
|
(key == Rml::Input::KI_UP || key == Rml::Input::KI_DOWN ||
|
|
key == Rml::Input::KI_RETURN ||
|
|
key == Rml::Input::KI_NUMPADENTER ||
|
|
key == Rml::Input::KI_SPACE || key == Rml::Input::KI_F4)) {
|
|
show(*select, key == Rml::Input::KI_UP);
|
|
return consume();
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
void typeahead_event(Rml::Event &event) {
|
|
type(event.GetParameter<Rml::String>("text", ""));
|
|
}
|
|
};
|
|
|
|
SelectMenu::SelectMenu(Rml::Context &context, Rml::ElementDocument &document,
|
|
CheckMarkupFn check, CommitFn commit)
|
|
: impl_(std::make_unique<Impl>(context, document, std::move(check),
|
|
std::move(commit))) {}
|
|
SelectMenu::~SelectMenu() {
|
|
impl_->close(false);
|
|
impl_->remove_popup();
|
|
}
|
|
bool SelectMenu::process_event(Rml::Event &event) {
|
|
return impl_->event(event);
|
|
}
|
|
void SelectMenu::before_render() {
|
|
impl_->close(false);
|
|
impl_->remove_popup();
|
|
}
|
|
void SelectMenu::after_layout() { impl_->layout(); }
|
|
bool SelectMenu::is_open() const { return impl_->open; }
|
|
editor::Json SelectMenu::snapshot() const {
|
|
auto &menu = *impl_;
|
|
editor::Json rect = editor::Json::object();
|
|
float font = 0, scroll = 0;
|
|
if (menu.open && menu.popup) {
|
|
const auto at = menu.popup->GetAbsoluteOffset(Rml::BoxArea::Border);
|
|
const auto size = menu.popup->GetBox().GetSize(Rml::BoxArea::Border);
|
|
rect = {{"x", at.x}, {"y", at.y}, {"width", size.x}, {"height", size.y}};
|
|
font = menu.popup->GetComputedValues().font_size();
|
|
scroll = menu.popup->GetScrollTop();
|
|
}
|
|
return {{"open", menu.open},
|
|
{"id", menu.id},
|
|
{"cursor", menu.cursor},
|
|
{"selected", menu.selected},
|
|
{"option_count", menu.options.size()},
|
|
{"rect", rect},
|
|
{"font_size", font},
|
|
{"ratio", menu.context.GetDensityIndependentPixelRatio()},
|
|
{"max_height", menu.max_height},
|
|
{"scroll_top", scroll}};
|
|
}
|
|
} // namespace bmh::modern_ui
|