選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

AbstractMultiSelect.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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.util.Collection;
  18. import java.util.Collections;
  19. import java.util.HashSet;
  20. import java.util.LinkedHashSet;
  21. import java.util.List;
  22. import java.util.Objects;
  23. import java.util.Optional;
  24. import java.util.Set;
  25. import java.util.stream.Collectors;
  26. import org.jsoup.nodes.Element;
  27. import com.vaadin.data.HasValue;
  28. import com.vaadin.data.SelectionModel;
  29. import com.vaadin.data.SelectionModel.Multi;
  30. import com.vaadin.data.provider.DataGenerator;
  31. import com.vaadin.event.selection.MultiSelectionEvent;
  32. import com.vaadin.event.selection.MultiSelectionListener;
  33. import com.vaadin.server.Resource;
  34. import com.vaadin.server.ResourceReference;
  35. import com.vaadin.server.SerializableConsumer;
  36. import com.vaadin.server.SerializablePredicate;
  37. import com.vaadin.shared.Registration;
  38. import com.vaadin.shared.data.selection.MultiSelectServerRpc;
  39. import com.vaadin.shared.ui.ListingJsonConstants;
  40. import com.vaadin.shared.ui.abstractmultiselect.AbstractMultiSelectState;
  41. import com.vaadin.ui.declarative.DesignContext;
  42. import com.vaadin.ui.declarative.DesignException;
  43. import elemental.json.JsonObject;
  44. /**
  45. * Base class for listing components that allow selecting multiple items.
  46. * <p>
  47. * Sends selection information individually for each item.
  48. *
  49. * @param <T>
  50. * item type
  51. * @author Vaadin Ltd
  52. * @since 8.0
  53. */
  54. public abstract class AbstractMultiSelect<T> extends AbstractListing<T>
  55. implements MultiSelect<T> {
  56. private Set<T> selection = new LinkedHashSet<>();
  57. private class MultiSelectServerRpcImpl implements MultiSelectServerRpc {
  58. @Override
  59. public void updateSelection(Set<String> selectedItemKeys,
  60. Set<String> deselectedItemKeys) {
  61. AbstractMultiSelect.this.updateSelection(
  62. getItemsForSelectionChange(selectedItemKeys),
  63. getItemsForSelectionChange(deselectedItemKeys), true);
  64. }
  65. private Set<T> getItemsForSelectionChange(Set<String> keys) {
  66. return keys.stream().map(key -> getItemForSelectionChange(key))
  67. .filter(Optional::isPresent).map(Optional::get)
  68. .collect(Collectors.toSet());
  69. }
  70. private Optional<T> getItemForSelectionChange(String key) {
  71. T item = getDataCommunicator().getKeyMapper().get(key);
  72. if (item == null || !getItemEnabledProvider().test(item)) {
  73. return Optional.empty();
  74. }
  75. return Optional.of(item);
  76. }
  77. }
  78. private class MultiSelectDataGenerator implements DataGenerator<T> {
  79. @Override
  80. public void generateData(T data, JsonObject jsonObject) {
  81. String caption = getItemCaptionGenerator().apply(data);
  82. if (caption != null) {
  83. jsonObject.put(ListingJsonConstants.JSONKEY_ITEM_VALUE,
  84. caption);
  85. } else {
  86. jsonObject.put(ListingJsonConstants.JSONKEY_ITEM_VALUE, "");
  87. }
  88. Resource icon = getItemIconGenerator().apply(data);
  89. if (icon != null) {
  90. String iconUrl = ResourceReference
  91. .create(icon, AbstractMultiSelect.this, null).getURL();
  92. jsonObject.put(ListingJsonConstants.JSONKEY_ITEM_ICON, iconUrl);
  93. }
  94. if (!getItemEnabledProvider().test(data)) {
  95. jsonObject.put(ListingJsonConstants.JSONKEY_ITEM_DISABLED,
  96. true);
  97. }
  98. if (isSelected(data)) {
  99. jsonObject.put(ListingJsonConstants.JSONKEY_ITEM_SELECTED,
  100. true);
  101. }
  102. }
  103. @Override
  104. public void destroyData(T data) {
  105. }
  106. @Override
  107. public void destroyAllData() {
  108. AbstractMultiSelect.this.deselectAll();
  109. }
  110. }
  111. /**
  112. * The item enabled status provider. It is up to the implementing class to
  113. * support this or not.
  114. */
  115. private SerializablePredicate<T> itemEnabledProvider = item -> true;
  116. /**
  117. * Creates a new multi select with an empty data provider.
  118. */
  119. protected AbstractMultiSelect() {
  120. registerRpc(new MultiSelectServerRpcImpl());
  121. // #FIXME it should be the responsibility of the SelectionModel
  122. // (AbstractSelectionModel) to add selection data for item
  123. addDataGenerator(new MultiSelectDataGenerator());
  124. }
  125. /**
  126. * Adds a selection listener that will be called when the selection is
  127. * changed either by the user or programmatically.
  128. *
  129. * @param listener
  130. * the value change listener, not {@code null}
  131. * @return a registration for the listener
  132. */
  133. @Override
  134. public Registration addSelectionListener(
  135. MultiSelectionListener<T> listener) {
  136. return addListener(MultiSelectionEvent.class, listener,
  137. MultiSelectionListener.SELECTION_CHANGE_METHOD);
  138. }
  139. @Override
  140. public ItemCaptionGenerator<T> getItemCaptionGenerator() {
  141. return super.getItemCaptionGenerator();
  142. }
  143. @Override
  144. public void setItemCaptionGenerator(
  145. ItemCaptionGenerator<T> itemCaptionGenerator) {
  146. super.setItemCaptionGenerator(itemCaptionGenerator);
  147. }
  148. /**
  149. * Returns the current value of this object which is an immutable set of the
  150. * currently selected items.
  151. * <p>
  152. * The call is delegated to {@link #getSelectedItems()}
  153. *
  154. * @return the current selection
  155. *
  156. * @see #getSelectedItems()
  157. * @see SelectionModel#getSelectedItems
  158. */
  159. @Override
  160. public Set<T> getValue() {
  161. return getSelectedItems();
  162. }
  163. /**
  164. * Sets the value of this object which is a set of items to select. If the
  165. * new value is not equal to {@code getValue()}, fires a value change event.
  166. * May throw {@code IllegalArgumentException} if the value is not
  167. * acceptable.
  168. * <p>
  169. * The method effectively selects the given items and deselects previously
  170. * selected. The call is delegated to
  171. * {@link Multi#updateSelection(Set, Set)}.
  172. *
  173. * @see Multi#updateSelection(Set, Set)
  174. *
  175. * @param value
  176. * the items to select, not {@code null}
  177. * @throws NullPointerException
  178. * if the value is invalid
  179. */
  180. @Override
  181. public void setValue(Set<T> value) {
  182. Objects.requireNonNull(value);
  183. Set<T> copy = value.stream().map(Objects::requireNonNull)
  184. .collect(Collectors.toCollection(LinkedHashSet::new));
  185. updateSelection(copy, new LinkedHashSet<>(getSelectedItems()));
  186. }
  187. /**
  188. * Adds a value change listener. The listener is called when the selection
  189. * set of this multi select is changed either by the user or
  190. * programmatically.
  191. *
  192. * @see #addSelectionListener(MultiSelectionListener)
  193. *
  194. * @param listener
  195. * the value change listener, not null
  196. * @return a registration for the listener
  197. */
  198. @Override
  199. public Registration addValueChangeListener(
  200. HasValue.ValueChangeListener<Set<T>> listener) {
  201. return addSelectionListener(event -> listener.valueChange(
  202. new ValueChangeEvent<>(this, event.getOldValue(),
  203. event.isUserOriginated())));
  204. }
  205. /**
  206. * Returns the item enabled provider for this multiselect.
  207. * <p>
  208. * <em>Implementation note:</em> Override this method and
  209. * {@link #setItemEnabledProvider(SerializablePredicate)} as {@code public}
  210. * and invoke {@code super} methods to support this feature in the
  211. * multiselect component.
  212. *
  213. * @return the item enabled provider, not {@code null}
  214. * @see #setItemEnabledProvider(SerializablePredicate)
  215. */
  216. protected SerializablePredicate<T> getItemEnabledProvider() {
  217. return itemEnabledProvider;
  218. }
  219. /**
  220. * Sets the item enabled predicate for this multiselect. The predicate is
  221. * applied to each item to determine whether the item should be enabled (
  222. * {@code true}) or disabled ({@code false}). Disabled items are displayed
  223. * as grayed out and the user cannot select them. The default predicate
  224. * always returns {@code true} (all the items are enabled).
  225. * <p>
  226. * <em>Implementation note:</em> Override this method and
  227. * {@link #getItemEnabledProvider()} as {@code public} and invoke
  228. * {@code super} methods to support this feature in the multiselect
  229. * component.
  230. *
  231. * @param itemEnabledProvider
  232. * the item enabled provider to set, not {@code null}
  233. */
  234. protected void setItemEnabledProvider(
  235. SerializablePredicate<T> itemEnabledProvider) {
  236. Objects.requireNonNull(itemEnabledProvider);
  237. this.itemEnabledProvider = itemEnabledProvider;
  238. }
  239. @Override
  240. public void setRequiredIndicatorVisible(boolean visible) {
  241. super.setRequiredIndicatorVisible(visible);
  242. }
  243. @Override
  244. public boolean isRequiredIndicatorVisible() {
  245. return super.isRequiredIndicatorVisible();
  246. }
  247. @Override
  248. protected AbstractMultiSelectState getState() {
  249. return (AbstractMultiSelectState) super.getState();
  250. }
  251. @Override
  252. protected AbstractMultiSelectState getState(boolean markAsDirty) {
  253. return (AbstractMultiSelectState) super.getState(markAsDirty);
  254. }
  255. @Override
  256. public void setReadOnly(boolean readOnly) {
  257. super.setReadOnly(readOnly);
  258. }
  259. @Override
  260. public boolean isReadOnly() {
  261. return super.isReadOnly();
  262. }
  263. @Override
  264. public void updateSelection(Set<T> addedItems, Set<T> removedItems) {
  265. updateSelection(addedItems, removedItems, false);
  266. }
  267. /**
  268. * Updates the selection by adding and removing the given items.
  269. *
  270. * @param addedItems
  271. * the items added to selection, not {@code} null
  272. * @param removedItems
  273. * the items removed from selection, not {@code} null
  274. * @param userOriginated
  275. * {@code true} if this was used originated, {@code false} if not
  276. */
  277. protected void updateSelection(Set<T> addedItems, Set<T> removedItems,
  278. boolean userOriginated) {
  279. Objects.requireNonNull(addedItems);
  280. Objects.requireNonNull(removedItems);
  281. // if there are duplicates, some item is both added & removed, just
  282. // discard that and leave things as was before
  283. addedItems.removeIf(item -> removedItems.remove(item));
  284. if (selection.containsAll(addedItems)
  285. && Collections.disjoint(selection, removedItems)) {
  286. return;
  287. }
  288. updateSelection(set -> {
  289. // order of add / remove does not matter since no duplicates
  290. set.removeAll(removedItems);
  291. set.addAll(addedItems);
  292. }, userOriginated);
  293. }
  294. @Override
  295. public Set<T> getSelectedItems() {
  296. return Collections.unmodifiableSet(new LinkedHashSet<>(selection));
  297. }
  298. @Override
  299. public void deselectAll() {
  300. if (selection.isEmpty()) {
  301. return;
  302. }
  303. updateSelection(Set::clear, false);
  304. }
  305. @Override
  306. public boolean isSelected(T item) {
  307. return selection.contains(item);
  308. }
  309. /**
  310. * Deselects the given item. If the item is not currently selected, does
  311. * nothing.
  312. *
  313. * @param item
  314. * the item to deselect, not null
  315. * @param userOriginated
  316. * {@code true} if this was used originated, {@code false} if not
  317. */
  318. protected void deselect(T item, boolean userOriginated) {
  319. if (!selection.contains(item)) {
  320. return;
  321. }
  322. updateSelection(set -> set.remove(item), userOriginated);
  323. }
  324. /**
  325. * Removes the given items. Any item that is not currently selected, is
  326. * ignored. If none of the items are selected, does nothing.
  327. *
  328. * @param items
  329. * the items to deselect, not {@code null}
  330. * @param userOriginated
  331. * {@code true} if this was used originated, {@code false} if not
  332. */
  333. protected void deselect(Set<T> items, boolean userOriginated) {
  334. Objects.requireNonNull(items);
  335. if (items.stream().noneMatch(i -> isSelected(i))) {
  336. return;
  337. }
  338. updateSelection(set -> set.removeAll(items), userOriginated);
  339. }
  340. /**
  341. * Selects the given item. Depending on the implementation, may cause other
  342. * items to be deselected. If the item is already selected, does nothing.
  343. *
  344. * @param item
  345. * the item to select, not null
  346. * @param userOriginated
  347. * {@code true} if this was used originated, {@code false} if not
  348. */
  349. protected void select(T item, boolean userOriginated) {
  350. if (selection.contains(item)) {
  351. return;
  352. }
  353. updateSelection(set -> set.add(item), userOriginated);
  354. }
  355. @Override
  356. protected Collection<String> getCustomAttributes() {
  357. Collection<String> attributes = super.getCustomAttributes();
  358. // "value" is not an attribute for the component. "selected" attribute
  359. // is used in "option"'s tag to mark selection which implies value for
  360. // multiselect component
  361. attributes.add("value");
  362. return attributes;
  363. }
  364. @Override
  365. protected Element writeItem(Element design, T item, DesignContext context) {
  366. Element element = super.writeItem(design, item, context);
  367. if (isSelected(item)) {
  368. element.attr("selected", "");
  369. }
  370. return element;
  371. }
  372. @Override
  373. protected void readItems(Element design, DesignContext context) {
  374. Set<T> selected = new HashSet<>();
  375. List<T> items = design.children().stream()
  376. .map(child -> readItem(child, selected, context))
  377. .collect(Collectors.toList());
  378. deselectAll();
  379. if (!items.isEmpty()) {
  380. setItems(items);
  381. }
  382. selected.forEach(this::select);
  383. }
  384. /**
  385. * Reads an Item from a design and inserts it into the data source.
  386. * Hierarchical select components should override this method to recursively
  387. * recursively read any child items as well.
  388. *
  389. * @param child
  390. * a child element representing the item
  391. * @param selected
  392. * A set accumulating selected items. If the item that is read is
  393. * marked as selected, its item id should be added to this set.
  394. * @param context
  395. * the DesignContext instance used in parsing
  396. * @return the item id of the new item
  397. *
  398. * @throws DesignException
  399. * if the tag name of the {@code child} element is not
  400. * {@code option}.
  401. */
  402. protected T readItem(Element child, Set<T> selected,
  403. DesignContext context) {
  404. T item = readItem(child, context);
  405. if (child.hasAttr("selected")) {
  406. selected.add(item);
  407. }
  408. return item;
  409. }
  410. private void updateSelection(SerializableConsumer<Set<T>> handler,
  411. boolean userOriginated) {
  412. LinkedHashSet<T> oldSelection = new LinkedHashSet<>(selection);
  413. handler.accept(selection);
  414. fireEvent(new MultiSelectionEvent<>(AbstractMultiSelect.this,
  415. oldSelection, userOriginated));
  416. getDataCommunicator().reset();
  417. }
  418. }