Files
FTXUI/src/ftxui/component/button.cpp

84 lines
2.3 KiB
C++
Raw Normal View History

2021-05-01 20:40:35 +02:00
#include <functional> // for function
#include <memory> // for shared_ptr
2020-08-26 16:26:09 +02:00
2021-05-01 20:40:35 +02:00
#include "ftxui/component/button.hpp"
#include "ftxui/component/captured_mouse.hpp" // for CapturedMouse
#include "ftxui/component/event.hpp" // for Event, Event::Return
#include "ftxui/component/mouse.hpp" // for Mouse, Mouse::Left, Mouse::Pressed
#include "ftxui/component/screen_interactive.hpp" // for ScreenInteractive
2020-08-26 16:26:09 +02:00
namespace ftxui {
2021-05-09 20:32:27 +02:00
/// @brief Draw a button. Execute a function when clicked.
/// @param label The label of the button.
/// @param on_click The action to execute when clicked.
/// @ingroup component
/// @see ButtonBase
///
/// ### Example
///
/// ```cpp
/// auto screen = ScreenInteractive::FitComponent();
/// std::wstring label = L"Click to quit";
/// Component button = Button(&label, screen.ExitLoopClosure());
/// screen.Loop(button)
/// ```
///
/// ### Output
///
/// ```bash
/// ┌─────────────┐
/// │Click to quit│
/// └─────────────┘
/// ```
Component Button(ConstStringRef label,
std::function<void()> on_click,
2021-07-07 22:23:07 +02:00
ConstRef<ButtonOption> option) {
return Make<ButtonBase>(label, std::move(on_click), std::move(option));
2021-05-09 20:32:27 +02:00
}
// static
ButtonBase* ButtonBase::From(Component component) {
return static_cast<ButtonBase*>(component.get());
}
ButtonBase::ButtonBase(ConstStringRef label,
std::function<void()> on_click,
2021-07-07 22:23:07 +02:00
ConstRef<ButtonOption> option)
: label_(label), on_click_(on_click), option_(std::move(option)) {}
2021-05-09 20:32:27 +02:00
Element ButtonBase::Render() {
auto style = Focused() ? inverted : nothing;
2021-07-07 22:23:07 +02:00
auto my_border = option_->border ? border : nothing;
return text(*label_) | my_border | style | reflect(box_);
2020-08-26 16:26:09 +02:00
}
2021-05-09 20:32:27 +02:00
bool ButtonBase::OnEvent(Event event) {
2021-04-25 15:22:38 +02:00
if (event.is_mouse() && box_.Contain(event.mouse().x, event.mouse().y)) {
2021-05-01 20:40:35 +02:00
if (!CaptureMouse(event))
return false;
2021-04-25 15:22:38 +02:00
TakeFocus();
if (event.mouse().button == Mouse::Left &&
event.mouse().motion == Mouse::Pressed) {
2021-05-09 20:32:27 +02:00
on_click_();
return true;
}
return false;
}
2020-08-26 16:26:09 +02:00
if (event == Event::Return) {
2021-05-09 20:32:27 +02:00
on_click_();
2020-08-26 16:26:09 +02:00
return true;
}
return false;
}
} // namespace ftxui
// 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.