Deduplicate logic in ComponentBase members (#162)

- Invoke DetachAllChildren from ~ComponentBase
- Define Focused using Active
- Compact TakeFocus loop code
- const-correctness for Parent, Active and Focused
This commit is contained in:
Tushar Maheshwari 2021-07-21 04:07:44 +05:30 committed by GitHub
parent 09805e5e86
commit 7f95d59954
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 20 deletions

View File

@ -26,7 +26,7 @@ class ComponentBase {
virtual ~ComponentBase();
// Component hierarchy:
ComponentBase* Parent();
ComponentBase* Parent() const;
Component& ChildAt(size_t i);
size_t ChildCount() const;
void Add(Component children);
@ -52,9 +52,9 @@ class ComponentBase {
virtual Component ActiveChild();
// Whether this is the active child of its parent.
bool Active();
bool Active() const;
// Whether all the ancestors are active.
bool Focused();
bool Focused() const;
// Make the |child| to be the "active" one.
virtual void SetActiveChild(ComponentBase* child);
@ -66,7 +66,7 @@ class ComponentBase {
protected:
CapturedMouse CaptureMouse(const Event& event);
std::vector<Component> children_;
Components children_;
private:
ComponentBase* parent_ = nullptr;

View File

@ -18,15 +18,14 @@ class CaptureMouseImpl : public CapturedMouseInterface {};
} // namespace
ComponentBase::~ComponentBase() {
while (children_.size() != 0)
children_.back()->Detach();
DetachAllChildren();
}
/// @brief Return the parent ComponentBase, or nul if any.
/// @see Detach
/// @see Parent
/// @ingroup component
ComponentBase* ComponentBase::Parent() {
ComponentBase* ComponentBase::Parent() const {
return parent_;
}
@ -109,7 +108,7 @@ Component ComponentBase::ActiveChild() {
/// @brief Returns if the element if the currently active child of its parent.
/// @ingroup component
bool ComponentBase::Active() {
bool ComponentBase::Active() const {
return !parent_ || parent_->ActiveChild().get() == this;
}
@ -117,16 +116,12 @@ bool ComponentBase::Active() {
/// True when the ComponentBase is focused by the user. An element is Focused
/// when it is with all its ancestors the ActiveChild() of their parents.
/// @ingroup component
bool ComponentBase::Focused() {
ComponentBase* current = this;
for (;;) {
ComponentBase* parent = current->parent_;
if (!parent)
return true;
if (parent->ActiveChild().get() != current)
return false;
current = parent;
bool ComponentBase::Focused() const {
auto current = this;
while (current && current->Active()) {
current = current->parent_;
}
return !current;
}
/// @brief Make the |child| to be the "active" one.
@ -145,11 +140,9 @@ void ComponentBase::SetActiveChild(Component child) {
/// @ingroup component
void ComponentBase::TakeFocus() {
ComponentBase* child = this;
ComponentBase* parent = parent_;
while (parent) {
while (ComponentBase* parent = child->parent_) {
parent->SetActiveChild(child);
child = parent;
parent = parent->parent_;
}
}