FTXUI/src/ftxui/component/checkbox.cpp

89 lines
2.3 KiB
C++
Raw Normal View History

2021-05-02 02:40:35 +08:00
#include <functional> // for function
#include <memory> // for shared_ptr
2020-03-23 05:32:44 +08:00
2021-05-02 02:40:35 +08:00
#include "ftxui/component/captured_mouse.hpp" // for CapturedMouse
#include "ftxui/component/checkbox.hpp"
#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
2019-01-13 05:25:49 +08:00
namespace ftxui {
2021-05-10 02:32:27 +08:00
/// @brief Draw checkable element.
/// @param label The label of the checkbox.
/// @param checked Whether the checkbox is checked or not.
/// @ingroup component
/// @see CheckboxBase
///
/// ### Example
///
/// ```cpp
/// auto screen = ScreenInteractive::FitComponent();
/// std::wstring label = L"Make a sandwidth";
/// bool checked = false;
/// Component checkbox = Checkbox(&label, &checked);
/// screen.Loop(checkbox)
/// ```
///
/// ### Output
///
/// ```bash
/// ☐ Make a sandwitch
/// ```
Component Checkbox(const std::wstring* label, bool* checked) {
return Make<CheckboxBase>(label, checked);
}
// static
CheckboxBase* From(Component component) {
return static_cast<CheckboxBase*>(component.get());
}
CheckboxBase::CheckboxBase(const std::wstring* label, bool* state)
: label_(label), state_(state) {}
Element CheckboxBase::Render() {
2019-01-20 05:06:05 +08:00
bool is_focused = Focused();
auto style = is_focused ? focused_style : unfocused_style;
2021-05-10 02:32:27 +08:00
auto focus_management = is_focused ? focus : *state_ ? select : nothing;
return hbox(text(*state_ ? checked : unchecked),
text(*label_) | style | focus_management) |
reflect(box_);
2019-01-13 05:25:49 +08:00
}
2021-05-10 02:32:27 +08:00
bool CheckboxBase::OnEvent(Event event) {
if (event.is_mouse())
return OnMouseEvent(event);
2019-01-13 05:25:49 +08:00
if (event == Event::Character(' ') || event == Event::Return) {
2021-05-10 02:32:27 +08:00
*state_ = !*state_;
2019-01-13 05:25:49 +08:00
on_change();
return true;
}
2020-03-23 05:32:44 +08:00
return false;
2019-01-13 05:25:49 +08:00
}
2021-05-10 02:32:27 +08:00
bool CheckboxBase::OnMouseEvent(Event event) {
if (!CaptureMouse(event))
return false;
2021-04-25 21:22:38 +08:00
if (!box_.Contain(event.mouse().x, event.mouse().y))
return false;
2021-04-25 21:22:38 +08:00
TakeFocus();
2021-04-25 21:22:38 +08:00
if (event.mouse().button == Mouse::Left &&
event.mouse().motion == Mouse::Pressed) {
2021-05-10 02:32:27 +08:00
*state_ = !*state_;
on_change();
return true;
}
return false;
}
2019-01-13 05:25:49 +08:00
} // 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.