ZenitUI
Retained-mode C++20 UI framework
Loading...
Searching...
No Matches
Button.hpp
Go to the documentation of this file.
1#pragma once
2
12
13#include "Common.hpp"
14#include "Layout.hpp"
15#include "Text.hpp"
16#include "Layouts.hpp"
17
18namespace ZenitUI::UI
19{
23
31 class Button : public TLayout<Button, Panel>
32 {
33 public:
39 Button(std::function<void()> cb)
40 {
41 onClick = std::move(cb);
42 setInteractive(true);
43 setFocusable(true);
44 setKeyboardActivates(true);
45 setStyleTag("Button");
46 getInlineDefaults().alignItems = Align::Center;
47 getInlineDefaults().cursor = CursorShape::Pointer;
48 }
49
51 std::string text() const
52 {
53 auto t = labelChild();
54 return t ? t->getText() : std::string{};
55 }
56
60 void setText(const std::string &s)
61 {
62 if (auto t = labelChild())
63 {
64 t->setText(s);
65 return;
66 }
67 auto lbl = Label(s)->cls("btn-text");
68 label_ = lbl;
69 addChild(std::move(lbl));
70 }
71
72 private:
73 std::shared_ptr<Text> labelChild() const
74 {
75 if (auto cached = label_.lock())
76 {
77 if (cached->getParent().get() == this)
78 return cached;
79 label_.reset();
80 }
81 for (const auto &c : children)
82 {
83 if (auto t = std::dynamic_pointer_cast<Text>(c))
84 {
85 label_ = t;
86 return t;
87 }
88 }
89 return nullptr;
90 }
91
92 mutable std::weak_ptr<Text> label_;
93 };
94
98 inline std::shared_ptr<Button> Btn(std::string text, std::function<void()> cb = nullptr)
99 {
100 auto b = Button::create(std::move(cb));
101 b->setText(text);
102 return b;
103 }
104
105} // namespace ZenitUI::UI
Centralized standard library includes used throughout ZenitUI.
The node class: tree structure, layout pass, style resolution, input dispatch, render orchestration,...
Basic layout containers: VStack, HStack, Panel.
A read-only text node backed by UIContext::textEngine.
TLayout(Args &&...args)
Definition Layout.hpp:1401
static std::shared_ptr< Button > create(Args &&...args)
Definition Layout.hpp:1410
Button(std::function< void()> cb)
Construct a button with the given click handler.
Definition Button.hpp:39
void setText(const std::string &s)
Update the label text, creating a "btn-text" Text child if none exists.
Definition Button.hpp:60
std::string text() const
Return the current label text, or "" if no Text child exists.
Definition Button.hpp:51
@ Center
Center within the available space.
Definition CoreTypes.hpp:455
@ Pointer
Pointing hand (buttons, links, interactive controls).
Definition UIEnums.hpp:64
std::shared_ptr< Text > Label(std::string t)
Convenience factory: a Text node.
Definition Text.hpp:88
std::shared_ptr< Button > Btn(std::string text, std::function< void()> cb=nullptr)
Convenience factory: a Button with a Text label and a click handler.
Definition Button.hpp:98