aboutsummaryrefslogtreecommitdiffstats
path: root/server/src/main/java/com/vaadin/ui/AbstractMultiSelect.java
blob: 93b0b35403469e1f32e7b86ef05c4c925a23cd2a (plain)
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
/*
 * Copyright 2000-2016 Vaadin Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.vaadin.ui;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.jsoup.nodes.Element;

import com.vaadin.data.HasValue;
import com.vaadin.data.SelectionModel;
import com.vaadin.data.SelectionModel.Multi;
import com.vaadin.data.provider.DataGenerator;
import com.vaadin.data.provider.DataProvider;
import com.vaadin.event.selection.MultiSelectionEvent;
import com.vaadin.event.selection.MultiSelectionListener;
import com.vaadin.server.Resource;
import com.vaadin.server.ResourceReference;
import com.vaadin.server.SerializableConsumer;
import com.vaadin.server.SerializablePredicate;
import com.vaadin.shared.Registration;
import com.vaadin.shared.data.selection.MultiSelectServerRpc;
import com.vaadin.shared.ui.ListingJsonConstants;
import com.vaadin.shared.ui.abstractmultiselect.AbstractMultiSelectState;
import com.vaadin.ui.declarative.DesignContext;
import com.vaadin.ui.declarative.DesignException;

import elemental.json.JsonObject;

/**
 * Base class for listing components that allow selecting multiple items.
 * <p>
 * Sends selection information individually for each item.
 *
 * @param <T>
 *            item type
 * @author Vaadin Ltd
 * @since 8.0
 */
public abstract class AbstractMultiSelect<T> extends AbstractListing<T>
        implements MultiSelect<T> {

    private List<T> selection = new ArrayList<>();

    private class MultiSelectServerRpcImpl implements MultiSelectServerRpc {
        @Override
        public void updateSelection(Set<String> selectedItemKeys,
                Set<String> deselectedItemKeys) {
            AbstractMultiSelect.this.updateSelection(
                    getItemsForSelectionChange(selectedItemKeys),
                    getItemsForSelectionChange(deselectedItemKeys), true);
        }

        private Set<T> getItemsForSelectionChange(Set<String> keys) {
            return keys.stream().map(key -> getItemForSelectionChange(key))
                    .filter(Optional::isPresent).map(Optional::get)
                    .collect(Collectors.toSet());
        }

        private Optional<T> getItemForSelectionChange(String key) {
            T item = getDataCommunicator().getKeyMapper().get(key);
            if (item == null || !getItemEnabledProvider().test(item)) {
                return Optional.empty();
            }

            return Optional.of(item);
        }

    }

    private final class MultiSelectDataGenerator implements DataGenerator<T> {
        @Override
        public void generateData(T data, JsonObject jsonObject) {
            String caption = getItemCaptionGenerator().apply(data);
            if (caption != null) {
                jsonObject.put(ListingJsonConstants.JSONKEY_ITEM_VALUE,
                        caption);
            } else {
                jsonObject.put(ListingJsonConstants.JSONKEY_ITEM_VALUE, "");
            }
            Resource icon = getItemIconGenerator().apply(data);
            if (icon != null) {
                String iconUrl = ResourceReference
                        .create(icon, AbstractMultiSelect.this, null).getURL();
                jsonObject.put(ListingJsonConstants.JSONKEY_ITEM_ICON, iconUrl);
            }
            if (!getItemEnabledProvider().test(data)) {
                jsonObject.put(ListingJsonConstants.JSONKEY_ITEM_DISABLED,
                        true);
            }

            if (isSelected(data)) {
                jsonObject.put(ListingJsonConstants.JSONKEY_ITEM_SELECTED,
                        true);
            }
        }

        @Override
        public void destroyData(T data) {
        }

        @Override
        public void destroyAllData() {
            AbstractMultiSelect.this.deselectAll();
        }

        @Override
        public void refreshData(T item) {
            refreshSelectedItem(item);
        }
    }

    /**
     * The item enabled status provider. It is up to the implementing class to
     * support this or not.
     */
    private SerializablePredicate<T> itemEnabledProvider = item -> true;

    /**
     * Creates a new multi select with an empty data provider.
     */
    protected AbstractMultiSelect() {
        registerRpc(new MultiSelectServerRpcImpl());

        // #FIXME it should be the responsibility of the SelectionModel
        // (AbstractSelectionModel) to add selection data for item
        addDataGenerator(new MultiSelectDataGenerator());
    }

    /**
     * Adds a selection listener that will be called when the selection is
     * changed either by the user or programmatically.
     *
     * @param listener
     *            the value change listener, not {@code null}
     * @return a registration for the listener
     */
    @Override
    public Registration addSelectionListener(
            MultiSelectionListener<T> listener) {
        return addListener(MultiSelectionEvent.class, listener,
                MultiSelectionListener.SELECTION_CHANGE_METHOD);
    }

    @Override
    public ItemCaptionGenerator<T> getItemCaptionGenerator() {
        return super.getItemCaptionGenerator();
    }

    @Override
    public void setItemCaptionGenerator(
            ItemCaptionGenerator<T> itemCaptionGenerator) {
        super.setItemCaptionGenerator(itemCaptionGenerator);
    }

    /**
     * Returns the current value of this object which is an immutable set of the
     * currently selected items.
     * <p>
     * The call is delegated to {@link #getSelectedItems()}
     *
     * @return the current selection
     *
     * @see #getSelectedItems()
     * @see SelectionModel#getSelectedItems
     */
    @Override
    public Set<T> getValue() {
        return getSelectedItems();
    }

    /**
     * Sets the value of this object which is a set of items to select. If the
     * new value is not equal to {@code getValue()}, fires a value change event.
     * May throw {@code IllegalArgumentException} if the value is not
     * acceptable.
     * <p>
     * The method effectively selects the given items and deselects previously
     * selected. The call is delegated to
     * {@link Multi#updateSelection(Set, Set)}.
     *
     * @see Multi#updateSelection(Set, Set)
     *
     * @param value
     *            the items to select, not {@code null}
     * @throws NullPointerException
     *             if the value is invalid
     */
    @Override
    public void setValue(Set<T> value) {
        Objects.requireNonNull(value);
        Set<T> copy = value.stream().map(Objects::requireNonNull)
                .collect(Collectors.toCollection(LinkedHashSet::new));

        updateSelection(copy, new LinkedHashSet<>(getSelectedItems()));
    }

    /**
     * Adds a value change listener. The listener is called when the selection
     * set of this multi select is changed either by the user or
     * programmatically.
     *
     * @see #addSelectionListener(MultiSelectionListener)
     *
     * @param listener
     *            the value change listener, not null
     * @return a registration for the listener
     */
    @Override
    public Registration addValueChangeListener(
            HasValue.ValueChangeListener<Set<T>> listener) {
        return addSelectionListener(
                event -> listener.valueChange(new ValueChangeEvent<>(this,
                        event.getOldValue(), event.isUserOriginated())));
    }

    /**
     * Returns the item enabled provider for this multiselect.
     * <p>
     * <em>Implementation note:</em> Override this method and
     * {@link #setItemEnabledProvider(SerializablePredicate)} as {@code public}
     * and invoke {@code super} methods to support this feature in the
     * multiselect component.
     *
     * @return the item enabled provider, not {@code null}
     * @see #setItemEnabledProvider(SerializablePredicate)
     */
    protected SerializablePredicate<T> getItemEnabledProvider() {
        return itemEnabledProvider;
    }

    /**
     * Sets the item enabled predicate for this multiselect. The predicate is
     * applied to each item to determine whether the item should be enabled (
     * {@code true}) or disabled ({@code false}). Disabled items are displayed
     * as grayed out and the user cannot select them. The default predicate
     * always returns {@code true} (all the items are enabled).
     * <p>
     * <em>Implementation note:</em> Override this method and
     * {@link #getItemEnabledProvider()} as {@code public} and invoke
     * {@code super} methods to support this feature in the multiselect
     * component.
     *
     * @param itemEnabledProvider
     *            the item enabled provider to set, not {@code null}
     */
    protected void setItemEnabledProvider(
            SerializablePredicate<T> itemEnabledProvider) {
        Objects.requireNonNull(itemEnabledProvider);
        this.itemEnabledProvider = itemEnabledProvider;
    }

    @Override
    public void setRequiredIndicatorVisible(boolean visible) {
        super.setRequiredIndicatorVisible(visible);
    }

    @Override
    public boolean isRequiredIndicatorVisible() {
        return super.isRequiredIndicatorVisible();
    }

    @Override
    protected AbstractMultiSelectState getState() {
        return (AbstractMultiSelectState) super.getState();
    }

    @Override
    protected AbstractMultiSelectState getState(boolean markAsDirty) {
        return (AbstractMultiSelectState) super.getState(markAsDirty);
    }

    @Override
    public void setReadOnly(boolean readOnly) {
        super.setReadOnly(readOnly);
    }

    @Override
    public boolean isReadOnly() {
        return super.isReadOnly();
    }

    @Override
    public void updateSelection(Set<T> addedItems, Set<T> removedItems) {
        updateSelection(addedItems, removedItems, false);
    }

    /**
     * Updates the selection by adding and removing the given items.
     *
     * @param addedItems
     *            the items added to selection, not {@code} null
     * @param removedItems
     *            the items removed from selection, not {@code} null
     * @param userOriginated
     *            {@code true} if this was used originated, {@code false} if not
     */
    protected void updateSelection(Set<T> addedItems, Set<T> removedItems,
            boolean userOriginated) {
        Objects.requireNonNull(addedItems);
        Objects.requireNonNull(removedItems);

        // if there are duplicates, some item is both added & removed, just
        // discard that and leave things as was before
        addedItems.removeIf(item -> removedItems.remove(item));

        if (selection.containsAll(addedItems)
                && Collections.disjoint(selection, removedItems)) {
            return;
        }

        updateSelection(set -> {
            // order of add / remove does not matter since no duplicates
            set.removeAll(removedItems);
            set.addAll(addedItems);
        }, userOriginated);
    }

    @Override
    public Set<T> getSelectedItems() {
        return Collections.unmodifiableSet(new LinkedHashSet<>(selection));
    }

    @Override
    public void deselectAll() {
        if (selection.isEmpty()) {
            return;
        }

        updateSelection(Collection::clear, false);
    }

    @Override
    public boolean isSelected(T item) {
        DataProvider<T, ?> dataProvider = internalGetDataProvider();
        Object id = dataProvider.getId(item);
        return selection.stream().map(dataProvider::getId).anyMatch(id::equals);

    }

    /**
     * Deselects the given item. If the item is not currently selected, does
     * nothing.
     *
     * @param item
     *            the item to deselect, not null
     * @param userOriginated
     *            {@code true} if this was used originated, {@code false} if not
     */
    protected void deselect(T item, boolean userOriginated) {
        if (!selection.contains(item)) {
            return;
        }

        updateSelection(set -> set.remove(item), userOriginated);
    }

    /**
     * Removes the given items. Any item that is not currently selected, is
     * ignored. If none of the items are selected, does nothing.
     *
     * @param items
     *            the items to deselect, not {@code null}
     * @param userOriginated
     *            {@code true} if this was used originated, {@code false} if not
     */
    protected void deselect(Set<T> items, boolean userOriginated) {
        Objects.requireNonNull(items);
        if (items.stream().noneMatch(i -> isSelected(i))) {
            return;
        }

        updateSelection(set -> set.removeAll(items), userOriginated);
    }

    /**
     * Selects the given item. Depending on the implementation, may cause other
     * items to be deselected. If the item is already selected, does nothing.
     *
     * @param item
     *            the item to select, not null
     * @param userOriginated
     *            {@code true} if this was used originated, {@code false} if not
     */
    protected void select(T item, boolean userOriginated) {
        if (selection.contains(item)) {
            return;
        }

        updateSelection(set -> set.add(item), userOriginated);
    }

    @Override
    protected Collection<String> getCustomAttributes() {
        Collection<String> attributes = super.getCustomAttributes();
        // "value" is not an attribute for the component. "selected" attribute
        // is used in "option"'s tag to mark selection which implies value for
        // multiselect component
        attributes.add("value");
        return attributes;
    }

    @Override
    protected Element writeItem(Element design, T item, DesignContext context) {
        Element element = super.writeItem(design, item, context);

        if (isSelected(item)) {
            element.attr("selected", "");
        }

        return element;
    }

    @Override
    protected void readItems(Element design, DesignContext context) {
        Set<T> selected = new HashSet<>();
        List<T> items = design.children().stream()
                .map(child -> readItem(child, selected, context))
                .collect(Collectors.toList());
        deselectAll();
        if (!items.isEmpty()) {
            setItems(items);
        }
        selected.forEach(this::select);
    }

    /**
     * Reads an Item from a design and inserts it into the data source.
     * Hierarchical select components should override this method to recursively
     * recursively read any child items as well.
     *
     * @param child
     *            a child element representing the item
     * @param selected
     *            A set accumulating selected items. If the item that is read is
     *            marked as selected, its item id should be added to this set.
     * @param context
     *            the DesignContext instance used in parsing
     * @return the item id of the new item
     *
     * @throws DesignException
     *             if the tag name of the {@code child} element is not
     *             {@code option}.
     */
    protected T readItem(Element child, Set<T> selected,
            DesignContext context) {
        T item = readItem(child, context);

        if (child.hasAttr("selected")) {
            selected.add(item);
        }

        return item;
    }

    private void updateSelection(SerializableConsumer<Collection<T>> handler,
            boolean userOriginated) {
        LinkedHashSet<T> oldSelection = new LinkedHashSet<>(selection);
        handler.accept(selection);

        fireEvent(new MultiSelectionEvent<>(AbstractMultiSelect.this,
                oldSelection, userOriginated));

        getDataCommunicator().reset();
    }

    private final void refreshSelectedItem(T item) {
        DataProvider<T, ?> dataProvider = internalGetDataProvider();
        Object id = dataProvider.getId(item);
        for (int i = 0; i < selection.size(); ++i) {
            if (id.equals(dataProvider.getId(selection.get(i)))) {
                selection.set(i, item);
                return;
            }
        }
    }
}