diff --git a/src/ftxui/component/toggle.cpp b/src/ftxui/component/toggle.cpp index 8403777..16311d0 100644 --- a/src/ftxui/component/toggle.cpp +++ b/src/ftxui/component/toggle.cpp @@ -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; } diff --git a/src/ftxui/component/toggle_test.cpp b/src/ftxui/component/toggle_test.cpp index c9692d1..190cc66 100644 --- a/src/ftxui/component/toggle_test.cpp +++ b/src/ftxui/component/toggle_test.cpp @@ -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); +}