Nui
select.hpp
Go to the documentation of this file.
1 #pragma once
2 
5 
6 // Elements
9 
10 // Attributes
14 
15 #include <vector>
16 #include <functional>
17 
18 namespace Nui::Components
19 {
20  template <template <typename...> typename ContainerT, typename ValueT>
21  struct SelectArgs
22  {
25 
27  int preSelectedIndex = -1;
28 
30  std::function<void(long long, SelectOptions<ValueT> const&)> onSelect = {};
31 
33  std::vector<Attribute> selectAttributes = {};
34  };
35 
37  template <typename ValueT, template <typename...> typename ContainerT = std::vector>
38  constexpr auto Select(SelectArgs<ContainerT, ValueT>&& args)
39  {
40  using namespace Attributes;
41  using namespace Elements;
42 
43  auto attributes = std::move(args.selectAttributes);
44  if (args.onSelect)
45  attributes.push_back(onChange = [onSelect = std::move(args.onSelect), &model = args.model](Nui::val event) {
46  const auto index = event["target"]["selectedIndex"].as<long long>();
47  onSelect(index, model.value()[index]);
48  });
49 
50  // clang-format off
51  return select{
52  std::move(attributes)
53  }(
54  args.model.map([preSelectedIndex = args.preSelectedIndex](auto i, auto const& opt) {
55  return option{
56  value = opt.value,
57  selected = (i == preSelectedIndex),
58  }(opt.label);
59  })
60  );
61  // clang-format on
62  }
63 }
Definition: observed_value.hpp:1202
Definition: dialog.hpp:11
constexpr auto Select(SelectArgs< ContainerT, ValueT > &&args)
Creates a <select><option></option>...</select> element.
Definition: select.hpp:38
emscripten::val val
Definition: val.hpp:5
Definition: select.hpp:22
std::function< void(long long, SelectOptions< ValueT > const &)> onSelect
Called when an option is selected.
Definition: select.hpp:30
Observed< ContainerT< SelectOptions< ValueT > > > & model
A list of all the options:
Definition: select.hpp:24
int preSelectedIndex
For pre selecting an element.
Definition: select.hpp:27
std::vector< Attribute > selectAttributes
Attributes to be forwarded to the select element.
Definition: select.hpp:33
Definition: select.hpp:9