You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AbstractMultiSelect.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.ui;
  17. import java.lang.reflect.Method;
  18. import java.util.Collections;
  19. import java.util.LinkedHashSet;
  20. import java.util.Objects;
  21. import java.util.Optional;
  22. import java.util.Set;
  23. import java.util.function.Consumer;
  24. import java.util.function.Predicate;
  25. import java.util.stream.Collectors;
  26. import com.vaadin.data.HasValue;
  27. import com.vaadin.event.selection.MultiSelectionEvent;
  28. import com.vaadin.event.selection.MultiSelectionListener;
  29. import com.vaadin.server.Resource;
  30. import com.vaadin.server.ResourceReference;
  31. import com.vaadin.server.SerializablePredicate;
  32. import com.vaadin.server.data.DataGenerator;
  33. import com.vaadin.shared.Registration;
  34. import com.vaadin.shared.data.selection.MultiSelectServerRpc;
  35. import com.vaadin.shared.data.selection.SelectionModel;
  36. import com.vaadin.shared.data.selection.SelectionModel.Multi;
  37. import com.vaadin.shared.ui.ListingJsonConstants;
  38. import com.vaadin.util.ReflectTools;
  39. import elemental.json.JsonObject;
  40. /**
  41. * Base class for listing components that allow selecting multiple items.
  42. * <p>
  43. * Sends selection information individually for each item.
  44. *
  45. * @param <T>
  46. * item type
  47. * @author Vaadin Ltd
  48. * @since 8.0
  49. */
  50. public abstract class AbstractMultiSelect<T>
  51. extends AbstractListing<T, Multi<T>> implements HasValue<Set<T>> {
  52. /**
  53. * Simple implementation of multiselectmodel.
  54. */
  55. protected class SimpleMultiSelectModel implements SelectionModel.Multi<T> {
  56. private Set<T> selection = new LinkedHashSet<>();
  57. @Override
  58. public void select(T item) {
  59. // Not user originated
  60. select(item, false);
  61. }
  62. /**
  63. * Selects the given item. Depending on the implementation, may cause
  64. * other items to be deselected. If the item is already selected, does
  65. * nothing.
  66. *
  67. * @param item
  68. * the item to select, not null
  69. * @param userOriginated
  70. * {@code true} if this was used originated, {@code false} if
  71. * not
  72. */
  73. protected void select(T item, boolean userOriginated) {
  74. if (selection.contains(item)) {
  75. return;
  76. }
  77. updateSelection(set -> set.add(item), userOriginated);
  78. }
  79. @Override
  80. public void updateSelection(Set<T> addedItems, Set<T> removedItems) {
  81. updateSelection(addedItems, removedItems, false);
  82. }
  83. /**
  84. * Updates the selection by adding and removing the given items.
  85. *
  86. * @param addedItems
  87. * the items added to selection, not {@code} null
  88. * @param removedItems
  89. * the items removed from selection, not {@code} null
  90. * @param userOriginated
  91. * {@code true} if this was used originated, {@code false} if
  92. * not
  93. */
  94. protected void updateSelection(Set<T> addedItems, Set<T> removedItems,
  95. boolean userOriginated) {
  96. Objects.requireNonNull(addedItems);
  97. Objects.requireNonNull(removedItems);
  98. // if there are duplicates, some item is both added & removed, just
  99. // discard that and leave things as was before
  100. addedItems.removeIf(item -> removedItems.remove(item));
  101. if (selection.containsAll(addedItems)
  102. && Collections.disjoint(selection, removedItems)) {
  103. return;
  104. }
  105. updateSelection(set -> {
  106. // order of add / remove does not matter since no duplicates
  107. set.removeAll(removedItems);
  108. set.addAll(addedItems);
  109. }, userOriginated);
  110. }
  111. @Override
  112. public Set<T> getSelectedItems() {
  113. return Collections.unmodifiableSet(new LinkedHashSet<>(selection));
  114. }
  115. @Override
  116. public void deselect(T item) {
  117. // Not user originated
  118. deselect(item, false);
  119. }
  120. /**
  121. * Deselects the given item. If the item is not currently selected, does
  122. * nothing.
  123. *
  124. * @param item
  125. * the item to deselect, not null
  126. * @param userOriginated
  127. * {@code true} if this was used originated, {@code false} if
  128. * not
  129. */
  130. protected void deselect(T item, boolean userOriginated) {
  131. if (!selection.contains(item)) {
  132. return;
  133. }
  134. updateSelection(set -> set.remove(item), userOriginated);
  135. }
  136. /**
  137. * Removes the given items. Any item that is not currently selected, is
  138. * ignored. If none of the items are selected, does nothing.
  139. *
  140. * @param items
  141. * the items to deselect, not {@code null}
  142. * @param userOriginated
  143. * {@code true} if this was used originated, {@code false} if
  144. * not
  145. */
  146. protected void deselect(Set<T> items, boolean userOriginated) {
  147. Objects.requireNonNull(items);
  148. if (items.stream().noneMatch(i -> isSelected(i))) {
  149. return;
  150. }
  151. updateSelection(set -> set.removeAll(items), userOriginated);
  152. }
  153. @Override
  154. public void deselectAll() {
  155. if (selection.isEmpty()) {
  156. return;
  157. }
  158. updateSelection(Set::clear, false);
  159. }
  160. private void updateSelection(Consumer<Set<T>> handler,
  161. boolean userOriginated) {
  162. LinkedHashSet<T> oldSelection = new LinkedHashSet<>(selection);
  163. handler.accept(selection);
  164. LinkedHashSet<T> newSelection = new LinkedHashSet<>(selection);
  165. fireEvent(new MultiSelectionEvent<>(AbstractMultiSelect.this,
  166. oldSelection, newSelection, userOriginated));
  167. getDataCommunicator().reset();
  168. }
  169. @Override
  170. public boolean isSelected(T item) {
  171. return selection.contains(item);
  172. }
  173. }
  174. private class MultiSelectServerRpcImpl implements MultiSelectServerRpc {
  175. @Override
  176. public void updateSelection(Set<String> selectedItemKeys,
  177. Set<String> deselectedItemKeys) {
  178. getSelectionModel().updateSelection(
  179. getItemsForSelectionChange(selectedItemKeys),
  180. getItemsForSelectionChange(deselectedItemKeys), true);
  181. }
  182. private Set<T> getItemsForSelectionChange(Set<String> keys) {
  183. return keys.stream().map(key -> getItemForSelectionChange(key))
  184. .filter(Optional::isPresent).map(Optional::get)
  185. .collect(Collectors.toSet());
  186. }
  187. private Optional<T> getItemForSelectionChange(String key) {
  188. T item = getDataCommunicator().getKeyMapper().get(key);
  189. if (item == null || !getItemEnabledProvider().test(item)) {
  190. return Optional.empty();
  191. }
  192. return Optional.of(item);
  193. }
  194. private SimpleMultiSelectModel getSelectionModel() {
  195. return (SimpleMultiSelectModel) AbstractMultiSelect.this
  196. .getSelectionModel();
  197. }
  198. }
  199. private class MultiSelectDataGenerator implements DataGenerator<T> {
  200. @Override
  201. public void generateData(T data, JsonObject jsonObject) {
  202. String caption = getItemCaptionGenerator().apply(data);
  203. if (caption != null) {
  204. jsonObject.put(ListingJsonConstants.JSONKEY_ITEM_VALUE,
  205. caption);
  206. } else {
  207. jsonObject.put(ListingJsonConstants.JSONKEY_ITEM_VALUE, "");
  208. }
  209. Resource icon = getItemIconGenerator().apply(data);
  210. if (icon != null) {
  211. String iconUrl = ResourceReference
  212. .create(icon, AbstractMultiSelect.this, null).getURL();
  213. jsonObject.put(ListingJsonConstants.JSONKEY_ITEM_ICON, iconUrl);
  214. }
  215. if (!getItemEnabledProvider().test(data)) {
  216. jsonObject.put(ListingJsonConstants.JSONKEY_ITEM_DISABLED,
  217. true);
  218. }
  219. if (getSelectionModel().isSelected(data)) {
  220. jsonObject.put(ListingJsonConstants.JSONKEY_ITEM_SELECTED,
  221. true);
  222. }
  223. }
  224. @Override
  225. public void destroyData(T data) {
  226. }
  227. }
  228. @Deprecated
  229. private static final Method SELECTION_CHANGE_METHOD = ReflectTools
  230. .findMethod(MultiSelectionListener.class, "accept",
  231. MultiSelectionEvent.class);
  232. /**
  233. * The item icon caption provider.
  234. */
  235. private ItemCaptionGenerator<T> itemCaptionGenerator = String::valueOf;
  236. /**
  237. * The item icon provider. It is up to the implementing class to support
  238. * this or not.
  239. */
  240. private IconGenerator<T> itemIconGenerator = item -> null;
  241. /**
  242. * The item enabled status provider. It is up to the implementing class to
  243. * support this or not.
  244. */
  245. private SerializablePredicate<T> itemEnabledProvider = item -> true;
  246. /**
  247. * Creates a new multi select with an empty data source.
  248. */
  249. protected AbstractMultiSelect() {
  250. setSelectionModel(new SimpleMultiSelectModel());
  251. registerRpc(new MultiSelectServerRpcImpl());
  252. // #FIXME it should be the responsibility of the SelectionModel
  253. // (AbstractSelectionModel) to add selection data for item
  254. addDataGenerator(new MultiSelectDataGenerator());
  255. }
  256. /**
  257. * Adds a selection listener that will be called when the selection is
  258. * changed either by the user or programmatically.
  259. *
  260. * @param listener
  261. * the value change listener, not {@code null}
  262. * @return a registration for the listener
  263. */
  264. public Registration addSelectionListener(
  265. MultiSelectionListener<T> listener) {
  266. addListener(MultiSelectionEvent.class, listener,
  267. SELECTION_CHANGE_METHOD);
  268. return () -> removeListener(MultiSelectionEvent.class, listener);
  269. }
  270. /**
  271. * Gets the item caption generator that is used to produce the strings shown
  272. * in the select for each item.
  273. *
  274. * @return the item caption generator used, not {@code null}
  275. * @see #setItemCaptionGenerator(ItemCaptionGenerator)
  276. */
  277. public ItemCaptionGenerator<T> getItemCaptionGenerator() {
  278. return itemCaptionGenerator;
  279. }
  280. /**
  281. * Sets the item caption generator that is used to produce the strings shown
  282. * in the select for each item. By default, {@link String#valueOf(Object)}
  283. * is used.
  284. *
  285. * @param itemCaptionGenerator
  286. * the item caption generator to use, not {@code null}
  287. */
  288. public void setItemCaptionGenerator(
  289. ItemCaptionGenerator<T> itemCaptionGenerator) {
  290. Objects.requireNonNull(itemCaptionGenerator);
  291. this.itemCaptionGenerator = itemCaptionGenerator;
  292. getDataCommunicator().reset();
  293. }
  294. /**
  295. * Returns the current value of this object which is an immutable set of the
  296. * currently selected items.
  297. * <p>
  298. * The call is delegated to {@link #getSelectedItems()}
  299. *
  300. * @return the current selection
  301. *
  302. * @see #getSelectedItems()
  303. * @see SelectionModel#getSelectedItems
  304. */
  305. @Override
  306. public Set<T> getValue() {
  307. return getSelectedItems();
  308. }
  309. /**
  310. * Sets the value of this object which is a set of items to select. If the
  311. * new value is not equal to {@code getValue()}, fires a value change event.
  312. * May throw {@code IllegalArgumentException} if the value is not
  313. * acceptable.
  314. * <p>
  315. * The method effectively selects the given items and deselects previously
  316. * selected. The call is delegated to
  317. * {@link Multi#updateSelection(Set, Set)}.
  318. *
  319. * @see Multi#updateSelection(Set, Set)
  320. *
  321. * @param value
  322. * the items to select, not {@code null}
  323. * @throws IllegalArgumentException
  324. * if the value is invalid
  325. */
  326. @Override
  327. public void setValue(Set<T> value) {
  328. Objects.requireNonNull(value);
  329. Set<T> copy = value.stream().map(Objects::requireNonNull)
  330. .collect(Collectors.toCollection(LinkedHashSet::new));
  331. getSelectionModel().updateSelection(copy,
  332. new LinkedHashSet<>(getSelectionModel().getSelectedItems()));
  333. }
  334. @Override
  335. public Set<T> getEmptyValue() {
  336. return Collections.emptySet();
  337. }
  338. /**
  339. * Adds a value change listener. The listener is called when the selection
  340. * set of this multi select is changed either by the user or
  341. * programmatically.
  342. *
  343. * @see #addSelectionListener(MultiSelectionListener)
  344. *
  345. * @param listener
  346. * the value change listener, not null
  347. * @return a registration for the listener
  348. */
  349. @Override
  350. public Registration addValueChangeListener(
  351. HasValue.ValueChangeListener<? super Set<T>> listener) {
  352. return addSelectionListener(
  353. event -> listener.accept(new ValueChange<>(event.getConnector(),
  354. event.getValue(), event.isUserOriginated())));
  355. }
  356. /**
  357. * Returns the item icon generator for this multiselect.
  358. * <p>
  359. * <em>Implementation note:</em> Override this method and
  360. * {@link #setItemIconGenerator(IconGenerator)} as {@code public} and invoke
  361. * {@code super} methods to support this feature in the multiselect
  362. * component.
  363. *
  364. * @return the item icon generator, not {@code null}
  365. * @see #setItemIconGenerator(IconGenerator)
  366. */
  367. protected IconGenerator<T> getItemIconGenerator() {
  368. return itemIconGenerator;
  369. }
  370. /**
  371. * Sets the item icon generator for this multiselect. The icon generator is
  372. * queried for each item to optionally display an icon next to the item
  373. * caption. If the generator returns null for an item, no icon is displayed.
  374. * The default provider always returns null (no icons).
  375. * <p>
  376. * <em>Implementation note:</em> Override this method and
  377. * {@link #getItemIconGenerator()} as {@code public} and invoke
  378. * {@code super} methods to support this feature in the multiselect
  379. * component.
  380. *
  381. * @param itemIconGenerator
  382. * the item icon generator to set, not {@code null}
  383. */
  384. protected void setItemIconGenerator(IconGenerator<T> itemIconGenerator) {
  385. Objects.requireNonNull(itemIconGenerator);
  386. this.itemIconGenerator = itemIconGenerator;
  387. }
  388. /**
  389. * Returns the item enabled provider for this multiselect.
  390. * <p>
  391. * <em>Implementation note:</em> Override this method and
  392. * {@link #setItemEnabledProvider(SerializablePredicate)} as {@code public}
  393. * and invoke {@code super} methods to support this feature in the
  394. * multiselect component.
  395. *
  396. * @return the item enabled provider, not {@code null}
  397. * @see #setItemEnabledProvider(Predicate)
  398. */
  399. protected SerializablePredicate<T> getItemEnabledProvider() {
  400. return itemEnabledProvider;
  401. }
  402. /**
  403. * Sets the item enabled predicate for this multiselect. The predicate is
  404. * applied to each item to determine whether the item should be enabled (
  405. * {@code true}) or disabled ({@code false}). Disabled items are displayed
  406. * as grayed out and the user cannot select them. The default predicate
  407. * always returns {@code true} (all the items are enabled).
  408. * <p>
  409. * <em>Implementation note:</em> Override this method and
  410. * {@link #getItemEnabledProvider()} as {@code public} and invoke
  411. * {@code super} methods to support this feature in the multiselect
  412. * component.
  413. *
  414. * @param itemEnabledProvider
  415. * the item enabled provider to set, not {@code null}
  416. */
  417. protected void setItemEnabledProvider(
  418. SerializablePredicate<T> itemEnabledProvider) {
  419. Objects.requireNonNull(itemEnabledProvider);
  420. this.itemEnabledProvider = itemEnabledProvider;
  421. }
  422. }