Skip to content

Commit 0720760

Browse files
committed
fix: support adding additional items through setValue
If additional items are allowed, non-existing items are always tracked as additional items. If additional items are not allowed, then setPresentationValue sanitizes the input by ignoring such items. Close #36
1 parent f0953bd commit 0720760

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

src/main/java/com/flowingcode/vaadin/addons/chipfield/ChipField.java

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
import java.util.ArrayList;
2323
import java.util.Arrays;
24+
import java.util.Iterator;
2425
import java.util.List;
2526
import java.util.Optional;
2627
import java.util.concurrent.atomic.AtomicInteger;
@@ -173,9 +174,44 @@ protected void onAttach(AttachEvent attachEvent) {
173174
configure();
174175
}
175176

177+
@Override
178+
public List<T> getValue() {
179+
return new ArrayList<>(super.getValue());
180+
}
181+
176182
@Override
177183
protected void setPresentationValue(List<T> newPresentationValue) {
178-
setClientChipWithoutEvent(newPresentationValue.stream().map(itemLabelGenerator).toArray(String[]::new));
184+
List<String> labels = new ArrayList<>();
185+
186+
if (isAllowAdditionalItems()) {
187+
for (T item : newPresentationValue) {
188+
String label = itemLabelGenerator.apply(item);
189+
if (!findItemByLabel(label).isPresent()) {
190+
addSelectedItemInternal(item, false);
191+
additionalItems.add(item);
192+
}
193+
labels.add(label);
194+
}
195+
} else {
196+
boolean hasChanges = false;
197+
newPresentationValue = new ArrayList<>(newPresentationValue);
198+
Iterator<T> it = newPresentationValue.iterator();
199+
while (it.hasNext()) {
200+
T item = it.next();
201+
String label = itemLabelGenerator.apply(item);
202+
if (findItemByLabel(label).isPresent()) {
203+
labels.add(label);
204+
} else {
205+
it.remove();
206+
hasChanges = true;
207+
}
208+
}
209+
if (hasChanges) {
210+
setModelValue(newPresentationValue, false);
211+
}
212+
}
213+
214+
setClientChipWithoutEvent(labels.toArray(new String[labels.size()]));
179215
}
180216

181217
private Optional<T> findItemByLabel(String label) {
@@ -349,8 +385,8 @@ public void removeSelectedItem(T itemToRemove) {
349385
private void removeSelectedItem(T itemToRemove, boolean fromClient) {
350386
List<T> value = new ArrayList<>(getValue());
351387
if (value.remove(itemToRemove)) {
352-
setModelValue(value, fromClient);
353388
additionalItems.retainAll(value);
389+
setModelValue(value, fromClient);
354390
if (!fromClient) {
355391
setPresentationValue(value);
356392
fireEvent(new ChipRemovedEvent<>(this, fromClient, itemLabelGenerator.apply(itemToRemove)));

0 commit comments

Comments
 (0)