Fix on_change() not called for Toggle.

Fix bug 35 and add some tests for the toggle component.

Bug:https://github.com/ArthurSonzogni/FTXUI/issues/35
This commit is contained in:
ArthurSonzogni 2020-08-02 22:11:05 +02:00 committed by Arthur Sonzogni
parent 8f87fc96ac
commit a4d72c4d50
2 changed files with 31 additions and 0 deletions

View File

@ -39,6 +39,10 @@ bool Toggle::OnEvent(Event event) {
selected = (selected + entries.size() - 1) % entries.size();
selected = std::max(0, std::min(int(entries.size()) - 1, selected));
if (old_selected != selected)
on_change();
return old_selected != selected;
}

View File

@ -75,3 +75,30 @@ TEST(ToggleTest, Tab) {
EXPECT_EQ(toggle.selected, 1);
toggle.OnEvent(Event::TabReverse);
}
TEST(ToggleTest, OnChange) {
Toggle toggle;
toggle.entries = {L"1", L"2", L"3"};
int counter = 0;
toggle.on_change = [&] { counter++; };
EXPECT_FALSE(toggle.OnEvent(Event::ArrowLeft)); // Reached far left.
EXPECT_EQ(counter, 0);
EXPECT_TRUE(toggle.OnEvent(Event::ArrowRight)); // [0] -> [1]
EXPECT_EQ(counter, 1);
EXPECT_TRUE(toggle.OnEvent(Event::ArrowRight)); // [1] -> [2]
EXPECT_EQ(counter, 2);
EXPECT_FALSE(toggle.OnEvent(Event::ArrowRight)); // Reached far right.
EXPECT_EQ(counter, 2);
EXPECT_TRUE(toggle.OnEvent(Event::ArrowLeft)); // [2] -> [1]
EXPECT_EQ(counter, 3);
EXPECT_TRUE(toggle.OnEvent(Event::ArrowLeft)); // [1] -> [0]
EXPECT_EQ(counter, 4);
EXPECT_FALSE(toggle.OnEvent(Event::ArrowLeft)); // Reached far left.
EXPECT_EQ(counter, 4);
}