aboutsummaryrefslogtreecommitdiff
path: root/include/cru/ui/controls/SingleChildControl.h
blob: 684b84032408d4560ad8c316e26787f1a07361ad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#pragma once
#include "Control.h"

#include <cassert>

namespace cru::ui::controls {
template <typename TRenderObject>
class SingleChildControl : public Control {
 protected:
  SingleChildControl(std::string name) : Control(std::move(name)) {
    container_render_object_.SetAttachedControl(this);
  }

 public:
  Control* GetChild() {
    const auto& children = GetChildren();
    assert(children.empty() || children.size() == 1);
    return children.empty() ? nullptr : children.front();
  }

  void SetChild(Control* child) {
    auto old_child = GetChild();
    if (old_child == child) return;
    if (old_child) {
      RemoveChildAt(0);
    }
    if (child) {
      InsertChildAt(child, 0);
    }

    container_render_object_.SetChild(child ? child->GetRenderObject()
                                            : nullptr);
  }

  render::RenderObject* GetRenderObject() override {
    return &container_render_object_;
  }

  TRenderObject* GetContainerRenderObject() {
    return &container_render_object_;
  }

 private:
  TRenderObject container_render_object_;
};
}  // namespace cru::ui::controls