aboutsummaryrefslogtreecommitdiffstats
path: root/server/src/main/java/com/vaadin/ui/CheckBoxGroup.java
blob: 8525dc6cbb7f13b319dfd0a3057015ef02256e52 (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
/*
 * 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.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

import com.vaadin.data.Listing;
import com.vaadin.event.selection.MultiSelectionEvent;
import com.vaadin.server.Resource;
import com.vaadin.server.ResourceReference;
import com.vaadin.server.data.DataGenerator;
import com.vaadin.server.data.DataSource;
import com.vaadin.shared.data.selection.SelectionModel;
import com.vaadin.shared.data.selection.SelectionServerRpc;
import com.vaadin.shared.ui.optiongroup.CheckBoxGroupConstants;
import com.vaadin.shared.ui.optiongroup.CheckBoxGroupState;

import elemental.json.JsonObject;

/**
 * A group of Checkboxes. Individual checkboxes are made from items supplied by
 * a {@link DataSource}. Checkboxes may have captions and icons.
 *
 * @param <T>
 *            item type
 * @author Vaadin Ltd
 * @since 8.0
 */
public class CheckBoxGroup<T> extends AbstractMultiSelect<T> {

    private final class SimpleMultiSelectModel
            implements SelectionModel.Multi<T> {

        private Set<T> selection = new LinkedHashSet<>();

        @Override
        public void select(T item) {
            // Not user originated
            select(item, false);
        }

        private void select(T item, boolean userOriginated) {
            if (selection.contains(item)) {
                return;
            }

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

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

        @Override
        public void deselect(T item) {
            // Not user originated
            deselect(item, false);
        }

        private void deselect(T item, boolean userOriginated) {
            if (!selection.contains(item)) {
                return;
            }

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

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

            updateSelection(Set::clear, false);
        }

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

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

            getDataCommunicator().reset();
        }

        @Override
        public boolean isSelected(T item) {
            return selection.contains(item);
        }
    }

    private Function<T, Resource> itemIconProvider = item -> null;

    private Function<T, String> itemCaptionProvider = String::valueOf;

    private Predicate<T> itemEnabledProvider = item -> true;

    /**
     * Constructs a new CheckBoxGroup with caption.
     *
     * @param caption
     *            caption text
     * @see Listing#setDataSource(DataSource)
     */
    public CheckBoxGroup(String caption) {
        this();
        setCaption(caption);
    }

    /**
     * Constructs a new CheckBoxGroup with caption and DataSource.
     *
     * @param caption
     *            the caption text
     * @param dataSource
     *            the data source, not null
     * @see Listing#setDataSource(DataSource)
     */
    public CheckBoxGroup(String caption, DataSource<T> dataSource) {
        this(caption);
        setDataSource(dataSource);
    }

    /**
     * Constructs a new CheckBoxGroup with caption and DataSource containing
     * given items.
     *
     * @param caption
     *            the caption text
     * @param items
     *            the data items to use, not null
     * @see Listing#setDataSource(DataSource)
     */
    public CheckBoxGroup(String caption, Collection<T> items) {
        this(caption, DataSource.create(items));
    }

    /**
     * Constructs a new CheckBoxGroup.
     *
     * @see Listing#setDataSource(DataSource)
     */
    public CheckBoxGroup() {
        setSelectionModel(new SimpleMultiSelectModel());

        registerRpc(new SelectionServerRpc() {

            @Override
            public void select(String key) {
                getItemForSelectionChange(key).ifPresent(
                        item -> getSelectionModel().select(item, true));
            }

            @Override
            public void deselect(String key) {
                getItemForSelectionChange(key).ifPresent(
                        item -> getSelectionModel().deselect(item, true));
            }

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

                return Optional.of(item);
            }

            private SimpleMultiSelectModel getSelectionModel() {
                return (SimpleMultiSelectModel) CheckBoxGroup.this
                        .getSelectionModel();
            }
        });

        addDataGenerator(new DataGenerator<T>() {
            @Override
            public void generateData(T data, JsonObject jsonObject) {
                jsonObject.put(CheckBoxGroupConstants.JSONKEY_ITEM_VALUE,
                        itemCaptionProvider.apply(data));
                Resource icon = itemIconProvider.apply(data);
                if (icon != null) {
                    String iconUrl = ResourceReference
                            .create(icon, CheckBoxGroup.this, null).getURL();
                    jsonObject.put(CheckBoxGroupConstants.JSONKEY_ITEM_ICON,
                            iconUrl);
                }
                if (!itemEnabledProvider.test(data)) {
                    jsonObject.put(CheckBoxGroupConstants.JSONKEY_ITEM_DISABLED,
                            true);
                }

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

            @Override
            public void destroyData(T data) {
            }
        });

    }

    /**
     * Sets whether html is allowed in the item captions. If set to true, the
     * captions are passed to the browser as html and the developer is
     * responsible for ensuring no harmful html is used. If set to false, the
     * content is passed to the browser as plain text.
     *
     * @param htmlContentAllowed
     *            true if the captions are used as html, false if used as plain
     *            text
     */
    public void setHtmlContentAllowed(boolean htmlContentAllowed) {
        getState().htmlContentAllowed = htmlContentAllowed;
    }

    /**
     * Checks whether captions are interpreted as html or plain text.
     *
     * @return true if the captions are used as html, false if used as plain
     *         text
     * @see #setHtmlContentAllowed(boolean)
     */
    public boolean isHtmlContentAllowed() {
        return getState(false).htmlContentAllowed;
    }

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

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

    /**
     * Returns the item icons provider.
     *
     * @return the icons provider for items
     * @see #setItemIconProvider
     */
    public Function<T, Resource> getItemIconProvider() {
        return itemIconProvider;
    }

    /**
     * Sets the item icon provider for this checkbox group. The icon provider is
     * queried for each item to optionally display an icon next to the item
     * caption. If the provider returns null for an item, no icon is displayed.
     * The default provider always returns null (no icons).
     *
     * @param itemIconProvider
     *            icons provider, not null
     */
    public void setItemIconProvider(Function<T, Resource> itemIconProvider) {
        Objects.nonNull(itemIconProvider);
        this.itemIconProvider = itemIconProvider;
    }

    /**
     * Returns the item caption provider.
     *
     * @return the captions provider
     * @see #setItemCaptionProvider
     */
    public Function<T, String> getItemCaptionProvider() {
        return itemCaptionProvider;
    }

    /**
     * Sets the item caption provider for this checkbox group. The caption
     * provider is queried for each item to optionally display an item textual
     * representation. The default provider returns
     * {@code String.valueOf(item)}.
     *
     * @param itemCaptionProvider
     *            the item caption provider, not null
     */
    public void setItemCaptionProvider(
            Function<T, String> itemCaptionProvider) {
        Objects.nonNull(itemCaptionProvider);
        this.itemCaptionProvider = itemCaptionProvider;
    }

    /**
     * Returns the item enabled predicate.
     *
     * @return the item enabled predicate
     * @see #setItemEnabledProvider
     */
    public Predicate<T> getItemEnabledProvider() {
        return itemEnabledProvider;
    }

    /**
     * Sets the item enabled predicate for this checkbox group. The predicate is
     * applied to each item to determine whether the item should be enabled
     * (true) or disabled (false). Disabled items are displayed as grayed out
     * and the user cannot select them. The default predicate always returns
     * true (all the items are enabled).
     *
     * @param itemEnabledProvider
     *            the item enable predicate, not null
     */
    public void setItemEnabledProvider(Predicate<T> itemEnabledProvider) {
        Objects.nonNull(itemEnabledProvider);
        this.itemEnabledProvider = itemEnabledProvider;
    }
}