aboutsummaryrefslogtreecommitdiff
path: root/src/theme_builder/components/properties/OptionalPropertyEditor.h
blob: 0f22616aa453cc56da0f1da6af2fc903af7f7261 (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#pragma once
#include "../Editor.h"
#include "cru/ui/controls/CheckBox.h"
#include "cru/ui/controls/FlexLayout.h"
#include "cru/ui/controls/TextBlock.h"

#include <optional>

namespace cru::theme_builder::components::properties {
template <typename TEditor>
class OptionalPropertyEditor : public Editor {
 public:
  using PropertyType = typename TEditor::PropertyType;

  OptionalPropertyEditor() {
    container_.AddChild(&label_);
    container_.AddChild(&check_box_);
    check_box_.SetMargin({0, 0, 10, 0});
    container_.AddChild(editor_.GetRootControl());

    editor_.ChangeEvent()->AddHandler([this](std::nullptr_t) {
      if (IsEnabled()) {
        RaiseChangeEvent();
      }
    });
  }
  ~OptionalPropertyEditor() override {}

  ui::controls::Control* GetRootControl() override { return &container_; }

  String GetLabel() const { return label_.GetText(); }
  void SetLabel(String label) { label_.SetText(std::move(label)); }

  bool IsEnabled() const { return check_box_.IsChecked(); }
  void SetEnabled(bool enabled, bool trigger_change = true) {
    check_box_.SetChecked(enabled);
    if (trigger_change) {
      RaiseChangeEvent();
    }
  }

  std::optional<PropertyType> GetValue() const {
    return IsEnabled() ? std::optional<PropertyType>(editor_.GetValue())
                       : std::nullopt;
  }

  void SetValue(std::optional<PropertyType> value, bool trigger_change = true) {
    if (value) {
      SetEnabled(true, false);
      editor_.SetValue(*value, false);
      if (trigger_change) RaiseChangeEvent();
    } else {
      SetEnabled(false, trigger_change);
    }
  }

  TEditor* GetEditor() { return &editor_; }

 private:
  ui::controls::FlexLayout container_;
  ui::controls::TextBlock label_;
  ui::controls::CheckBox check_box_;
  TEditor editor_;
};
}  // namespace cru::theme_builder::components::properties