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.List;
38 import java.util.stream.Collectors;
39 import java.util.stream.Stream;
40
41 import com.explicatis.ext_token_field.ExtTokenField;
42 import com.explicatis.ext_token_field.SimpleTokenizable;
43 import com.explicatis.ext_token_field.Tokenizable;
44 import com.vaadin.shared.Registration;
45 import com.vaadin.ui.ComboBox;
46 import com.vaadin.ui.Component;
47 import com.vaadin.ui.CustomField;
48
49 import lombok.RequiredArgsConstructor;
50
51
52
53
54
55
56
57 @RequiredArgsConstructor
58 public class TokenFieldWrapper<T> extends CustomField<List<String>> {
59
60 private final TokenField tokenField = new TokenField();
61 private final ComboBox<T> comboBox;
62
63 @Override
64 public List<String> getValue() {
65 return tokenField.getValue().stream()
66 .map(Tokenizable::getStringValue)
67 .collect(Collectors.toList());
68 }
69
70
71 @Override
72 protected void doSetValue(List strings) {
73 if (strings == null) {
74 tokenField.doSetValue(new ArrayList());
75 } else {
76 tokenField.doSetValue(toTokenizables(strings.stream()));
77 }
78 }
79
80 @Override
81 protected Component initContent() {
82 comboBox.addValueChangeListener((ValueChangeListener<T>) event -> {
83 if (event.getValue() != null) {
84
85 tokenField.addTokenizable(new ToStringTokenizable(comboBox.getItemCaptionGenerator().apply(event.getValue())));
86 event.getSource().setValue(null);
87 }
88 });
89 tokenField.setTokenDragDropEnabled(true);
90 tokenField.setEnableDefaultDeleteTokenAction(true);
91 tokenField.setInputField(comboBox);
92 return tokenField;
93 }
94
95 @Override
96 public Registration addValueChangeListener(ValueChangeListener listener) {
97 tokenField.addValueChangeListener(listener);
98 return super.addValueChangeListener(listener);
99 }
100
101 @Override
102 public void setReadOnly(boolean readOnly) {
103 super.setReadOnly(readOnly);
104 tokenField.setReadOnly(readOnly);
105 }
106
107 private List<Tokenizable> toTokenizables(Stream<?> strings) {
108 return strings
109 .map(ToStringTokenizable::new)
110 .collect(Collectors.toList());
111 }
112
113 private static class ToStringTokenizable extends SimpleTokenizable {
114
115 private ToStringTokenizable(Object stringValue) {
116 super(stringValue.hashCode(), String.valueOf(stringValue));
117 }
118
119 @Override
120 public String toString() {
121 return getStringValue();
122 }
123 }
124
125 private static class TokenField extends ExtTokenField {
126
127 @Override
128 protected void doSetValue(List<Tokenizable> value) {
129 super.doSetValue(value);
130 }
131 }
132 }