FTXUI/examples/component/button.cpp

66 lines
2.2 KiB
C++
Raw Normal View History

2023-08-19 19:56:36 +08:00
// Copyright 2020 Arthur Sonzogni. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
2021-07-10 19:20:43 +08:00
#include <memory> // for shared_ptr, __shared_ptr_access
2022-03-14 01:51:46 +08:00
#include <string> // for operator+, to_string
2020-08-26 22:26:09 +08:00
#include "ftxui/component/captured_mouse.hpp" // for ftxui
#include "ftxui/component/component.hpp" // for Button, Horizontal, Renderer
#include "ftxui/component/component_base.hpp" // for ComponentBase
2021-05-02 02:40:35 +08:00
#include "ftxui/component/screen_interactive.hpp" // for ScreenInteractive
2022-03-14 01:51:46 +08:00
#include "ftxui/dom/elements.hpp" // for separator, gauge, text, Element, operator|, vbox, border
2020-08-26 22:26:09 +08:00
using namespace ftxui;
2023-09-03 22:21:13 +08:00
// This is a helper function to create a button with a custom style.
// The style is defined by a lambda function that takes an EntryState and
// returns an Element.
// We are using `center` to center the text inside the button, then `border` to
// add a border around the button, and finally `flex` to make the button fill
// the available space.
ButtonOption ButtonStyle() {
auto option = ButtonOption::Animated();
option.transform = [](const EntryState& s) {
auto element = text(s.label);
if (s.focused) {
element |= bold;
}
return element | center | borderEmpty | flex;
};
return option;
}
int main() {
2021-05-13 17:44:47 +08:00
int value = 50;
2020-08-26 22:26:09 +08:00
2021-05-13 17:44:47 +08:00
// The tree of components. This defines how to navigate using the keyboard.
auto buttons = Container::Vertical({
2023-09-03 22:21:13 +08:00
Container::Horizontal({
Button(
"-1", [&] { value--; }, ButtonStyle()),
Button(
"+1", [&] { value++; }, ButtonStyle()),
2023-09-03 22:21:13 +08:00
}) | flex,
Container::Horizontal({
Button(
"-10", [&] { value -= 10; }, ButtonStyle()),
Button(
"+10", [&] { value += 10; }, ButtonStyle()),
2023-09-03 22:21:13 +08:00
}) | flex,
});
2020-08-26 22:26:09 +08:00
2021-05-13 17:44:47 +08:00
// Modify the way to render them on screen:
auto component = Renderer(buttons, [&] {
2021-05-10 02:32:27 +08:00
return vbox({
text("value = " + std::to_string(value)),
2021-05-10 02:32:27 +08:00
separator(),
2023-09-03 22:21:13 +08:00
buttons->Render() | flex,
}) |
flex | border;
2021-05-13 17:44:47 +08:00
});
2020-08-26 22:26:09 +08:00
2023-09-03 22:21:13 +08:00
auto screen = ScreenInteractive::Fullscreen();
2021-05-13 17:44:47 +08:00
screen.Loop(component);
2020-08-26 22:26:09 +08:00
return 0;
}