From fcd050c01702bc39cc757c60d7b0e21608e42d52 Mon Sep 17 00:00:00 2001 From: Arthur Sonzogni Date: Tue, 13 Aug 2024 15:55:09 +0200 Subject: [PATCH] Table: support initializer list constructor. (#915) To avoid burdening the user with explicit type construction when using the library, we can use a constructor that accepts an initializer list (std::initializer_list). This allows users to pass initializer lists directly without having to wrap them in std::vector>. This resolves the ambiguous case when the inner list contains only two elements. Bug:https://github.com/ArthurSonzogni/FTXUI/issues/912 --- include/ftxui/dom/table.hpp | 1 + src/ftxui/dom/table.cpp | 16 ++++++++++++++++ src/ftxui/dom/table_test.cpp | 12 ++++++++++++ 3 files changed, 29 insertions(+) diff --git a/include/ftxui/dom/table.hpp b/include/ftxui/dom/table.hpp index 6cfc86f..5460237 100644 --- a/include/ftxui/dom/table.hpp +++ b/include/ftxui/dom/table.hpp @@ -38,6 +38,7 @@ class Table { Table(); explicit Table(std::vector>); explicit Table(std::vector>); + Table(std::initializer_list> init); TableSelection SelectAll(); TableSelection SelectCell(int column, int row); TableSelection SelectRow(int row_index); diff --git a/src/ftxui/dom/table.cpp b/src/ftxui/dom/table.cpp index eb63259..e65b2dd 100644 --- a/src/ftxui/dom/table.cpp +++ b/src/ftxui/dom/table.cpp @@ -71,6 +71,22 @@ Table::Table(std::vector> input) { Initialize(std::move(input)); } +// @brief Create a table from a list of list of string. +// @param init The input data. +// @ingroup dom +Table::Table(std::initializer_list> init) { + std::vector> input; + for (const auto& row : init) { + std::vector output_row; + output_row.reserve(row.size()); + for (const auto& cell : row) { + output_row.push_back(text(cell)); + } + input.push_back(std::move(output_row)); + } + Initialize(std::move(input)); +} + // private void Table::Initialize(std::vector> input) { input_dim_y_ = static_cast(input.size()); diff --git a/src/ftxui/dom/table_test.cpp b/src/ftxui/dom/table_test.cpp index 215f1f1..bae224b 100644 --- a/src/ftxui/dom/table_test.cpp +++ b/src/ftxui/dom/table_test.cpp @@ -733,5 +733,17 @@ TEST(TableTest, Merge) { screen.ToString()); } +TEST(TableTest, Issue912) { + Table({ + {"a"}, + }); + Table({ + {"a", "b"}, + }); + Table({ + {"a", "b", "c"}, + }); +} + } // namespace ftxui // NOLINTEND