1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.ui.field.factory;
35
36 import java.util.ArrayList;
37 import java.util.Collection;
38 import java.util.List;
39 import java.util.stream.Collectors;
40 import java.util.stream.Stream;
41
42 import com.explicatis.ext_token_field.ExtTokenField;
43 import com.explicatis.ext_token_field.SimpleTokenizable;
44 import com.explicatis.ext_token_field.Tokenizable;
45 import com.vaadin.shared.Registration;
46 import com.vaadin.ui.ComboBox;
47 import com.vaadin.ui.Component;
48 import com.vaadin.ui.CustomField;
49
50 import lombok.RequiredArgsConstructor;
51
52
53
54
55
56
57
58 @RequiredArgsConstructor
59 public class TokenFieldWrapper<T> extends CustomField<Collection<String>> {
60
61 private final TokenField tokenField = new TokenField();
62 private final ComboBox<T> comboBox;
63
64 @Override
65 public Collection<String> getValue() {
66 return tokenField.getValue().stream()
67 .map(Tokenizable::getStringValue)
68 .collect(Collectors.toList());
69 }
70
71
72 @Override
73 protected void doSetValue(Collection<String> strings) {
74 if (strings == null) {
75 tokenField.doSetValue(new ArrayList<>());
76 } else {
77 tokenField.doSetValue(toTokenizables(strings.stream()));
78 }
79 }
80
81 @Override
82 protected Component initContent() {
83 comboBox.addValueChangeListener((ValueChangeListener<T>) event -> {
84 if (event.getValue() != null) {
85
86 tokenField.addTokenizable(new ToStringTokenizable(comboBox.getItemCaptionGenerator().apply(event.getValue())));
87 event.getSource().setValue(null);
88 }
89 });
90 tokenField.setTokenDragDropEnabled(true);
91 tokenField.setEnableDefaultDeleteTokenAction(true);
92 tokenField.setInputField(comboBox);
93 return tokenField;
94 }
95
96 @Override
97 public Registration addValueChangeListener(ValueChangeListener listener) {
98 tokenField.addValueChangeListener(listener);
99 return super.addValueChangeListener(listener);
100 }
101
102 @Override
103 public void setReadOnly(boolean readOnly) {
104 super.setReadOnly(readOnly);
105 tokenField.setReadOnly(readOnly);
106 }
107
108 private List<Tokenizable> toTokenizables(Stream<?> strings) {
109 return strings
110 .map(ToStringTokenizable::new)
111 .collect(Collectors.toList());
112 }
113
114 private static class ToStringTokenizable extends SimpleTokenizable {
115
116 private ToStringTokenizable(Object stringValue) {
117 super(stringValue.hashCode(), String.valueOf(stringValue));
118 }
119
120 @Override
121 public String toString() {
122 return getStringValue();
123 }
124 }
125
126 private static class TokenField extends ExtTokenField {
127
128 @Override
129 protected void doSetValue(List<Tokenizable> value) {
130 super.doSetValue(value);
131 }
132 }
133 }