Single Select
A single select component asks a user to choose one item from a list. It is similar to a simple drop-down list. The following listing shows an example:
@Component
public class ComponentCommands {
private final Terminal terminal;
private final ResourceLoader resourceLoader;
private final TemplateExecutor templateExecutor;
public ComponentCommands(Terminal terminal, ResourceLoader resourceLoader,
TemplateExecutor templateExecutor) {
this.terminal = terminal;
this.resourceLoader = resourceLoader;
this.templateExecutor = templateExecutor;
}
@Command(name = "component single", description = "Single selector", group = "Components")
public String singleSelector() {
SelectorItem<String> i1 = SelectorItem.of("key1", "value1");
SelectorItem<String> i2 = SelectorItem.of("key2", "value2");
List<SelectorItem<String>> items = Arrays.asList(i1, i2);
SingleItemSelector<String, SelectorItem<String>> component = new SingleItemSelector<>(terminal, items,
"testSimple", null);
component.setResourceLoader(resourceLoader);
component.setTemplateExecutor(templateExecutor);
SingleItemSelectorContext<String, SelectorItem<String>> context = component
.run(SingleItemSelectorContext.empty());
String result = context.getResultItem().flatMap(si -> Optional.ofNullable(si.getItem())).get();
return "Got value " + result;
}
}
The following screencast shows typical output for a single select component:
The context object is SingleItemSelectorContext. The following table describes its context variables:
| Key | Description |
|---|---|
|
The returned value when the component exits. |
|
The visible items, where rows contain maps of name and selected items. |
|
The parent context variables (see SelectorComponentContext Template Variables). |
You can pre-select an item by defining it to get exposed. This is
useful if you know the default and lets the user merely press Enter to make a choice.
The following listing sets a default:
SelectorItem<String> i1 = SelectorItem.of("key1", "value1");
SelectorItem<String> i2 = SelectorItem.of("key2", "value2");
List<SelectorItem<String>> items = Arrays.asList(i1, i2);
SingleItemSelector<String, SelectorItem<String>> component = new SingleItemSelector<>(terminal, items,
"testSimple", null);
component.setDefaultExpose(i2);