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.

VRadioButtonGroup.java 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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.client.ui;
  17. import java.util.ArrayList;
  18. import java.util.HashMap;
  19. import java.util.List;
  20. import java.util.Map;
  21. import java.util.Optional;
  22. import java.util.function.Consumer;
  23. import com.google.gwt.aria.client.Roles;
  24. import com.google.gwt.dom.client.Element;
  25. import com.google.gwt.event.dom.client.ClickEvent;
  26. import com.google.gwt.event.dom.client.ClickHandler;
  27. import com.google.gwt.user.client.DOM;
  28. import com.google.gwt.user.client.ui.FocusWidget;
  29. import com.google.gwt.user.client.ui.HasEnabled;
  30. import com.google.gwt.user.client.ui.RadioButton;
  31. import com.google.gwt.user.client.ui.Widget;
  32. import com.vaadin.client.ApplicationConnection;
  33. import com.vaadin.client.BrowserInfo;
  34. import com.vaadin.client.WidgetUtil;
  35. import com.vaadin.client.widgets.FocusableFlowPanelComposite;
  36. import com.vaadin.shared.Registration;
  37. import com.vaadin.shared.data.DataCommunicatorConstants;
  38. import com.vaadin.shared.ui.ListingJsonConstants;
  39. import elemental.json.JsonObject;
  40. /**
  41. * The client-side widget for the {@code RadioButtonGroup} component.
  42. *
  43. * @author Vaadin Ltd.
  44. * @since 8.0
  45. */
  46. public class VRadioButtonGroup extends FocusableFlowPanelComposite
  47. implements Field, ClickHandler, HasEnabled {
  48. public static final String CLASSNAME = "v-select-optiongroup";
  49. public static final String CLASSNAME_OPTION = "v-select-option";
  50. private final Map<RadioButton, JsonObject> optionsToItems;
  51. private final Map<String, RadioButton> keyToOptions;
  52. /**
  53. * For internal use only. May be removed or replaced in the future.
  54. */
  55. public ApplicationConnection client;
  56. private boolean htmlContentAllowed = false;
  57. private boolean enabled;
  58. private boolean readonly;
  59. private final String groupId;
  60. private List<Consumer<JsonObject>> selectionChangeListeners;
  61. public VRadioButtonGroup() {
  62. groupId = DOM.createUniqueId();
  63. getWidget().setStyleName(CLASSNAME);
  64. optionsToItems = new HashMap<>();
  65. keyToOptions = new HashMap<>();
  66. selectionChangeListeners = new ArrayList<>();
  67. }
  68. /*
  69. * Build all the options
  70. */
  71. public void buildOptions(List<JsonObject> items) {
  72. Roles.getRadiogroupRole().set(getElement());
  73. int i = 0;
  74. int widgetsToRemove = getWidget().getWidgetCount() - items.size();
  75. if (widgetsToRemove < 0) {
  76. widgetsToRemove = 0;
  77. }
  78. List<Widget> remove = new ArrayList<>(widgetsToRemove);
  79. for (Widget widget : getWidget()) {
  80. if (i < items.size()) {
  81. updateItem((RadioButton) widget, items.get(i), false);
  82. i++;
  83. } else {
  84. remove.add(widget);
  85. }
  86. }
  87. remove.stream().forEach(this::remove);
  88. while (i < items.size()) {
  89. updateItem(new RadioButton(groupId), items.get(i), true);
  90. i++;
  91. }
  92. }
  93. /**
  94. * Returns the JsonObject used to populate the RadioButton widget that
  95. * contains given Element.
  96. *
  97. * @since 8.2
  98. * @param element
  99. * the element to search for
  100. * @return the related JsonObject; {@code null} if not found
  101. */
  102. public JsonObject getItem(Element element) {
  103. // The HTML populated in updateItem does not match RadioButton directly,
  104. // which is why tryGetItem is also attempted on the parent element
  105. return tryGetItem(element)
  106. .orElse(tryGetItem(element.getParentElement()).orElse(null));
  107. }
  108. private Optional<JsonObject> tryGetItem(Element element) {
  109. return optionsToItems.entrySet().stream()
  110. .filter(e -> e.getKey().getElement().equals(element))
  111. .map(e -> e.getValue()).findFirst();
  112. }
  113. private void remove(Widget widget) {
  114. getWidget().remove(widget);
  115. JsonObject item = optionsToItems.remove(widget);
  116. if (item != null) {
  117. String key = item.getString(DataCommunicatorConstants.KEY);
  118. keyToOptions.remove(key);
  119. }
  120. }
  121. private void updateItem(RadioButton button, JsonObject item,
  122. boolean requireInitialization) {
  123. String itemHtml = item
  124. .getString(ListingJsonConstants.JSONKEY_ITEM_VALUE);
  125. if (!isHtmlContentAllowed()) {
  126. itemHtml = WidgetUtil.escapeHTML(itemHtml);
  127. }
  128. String iconUrl = item.getString(ListingJsonConstants.JSONKEY_ITEM_ICON);
  129. if (iconUrl != null && !iconUrl.isEmpty()) {
  130. Icon icon = client.getIcon(iconUrl);
  131. itemHtml = icon.getElement().getString() + itemHtml;
  132. }
  133. button.setHTML(itemHtml);
  134. button.setValue(
  135. item.getBoolean(ListingJsonConstants.JSONKEY_ITEM_SELECTED));
  136. boolean optionEnabled = !item
  137. .getBoolean(ListingJsonConstants.JSONKEY_ITEM_DISABLED);
  138. boolean enabled = optionEnabled && !isReadonly() && isEnabled();
  139. button.setEnabled(enabled);
  140. String key = item.getString(DataCommunicatorConstants.KEY);
  141. if (requireInitialization) {
  142. getWidget().add(button);
  143. button.setStyleName("v-radiobutton");
  144. button.addStyleName(CLASSNAME_OPTION);
  145. button.addClickHandler(this);
  146. }
  147. optionsToItems.put(button, item);
  148. keyToOptions.put(key, button);
  149. }
  150. @Override
  151. public void onClick(ClickEvent event) {
  152. if (event.getSource() instanceof RadioButton) {
  153. RadioButton source = (RadioButton) event.getSource();
  154. if (!source.isEnabled()) {
  155. // Click events on the text are received even though the
  156. // radiobutton is disabled
  157. return;
  158. }
  159. if (BrowserInfo.get().isWebkit() || BrowserInfo.get().isIE11()) {
  160. // Webkit does not focus non-text input elements on click
  161. // (#11854)
  162. source.setFocus(true);
  163. }
  164. JsonObject item = optionsToItems.get(source);
  165. assert item != null;
  166. new ArrayList<>(selectionChangeListeners)
  167. .forEach(listener -> listener.accept(item));
  168. }
  169. }
  170. public void setTabIndex(int tabIndex) {
  171. for (Widget anOptionsContainer : getWidget()) {
  172. FocusWidget widget = (FocusWidget) anOptionsContainer;
  173. widget.setTabIndex(tabIndex);
  174. }
  175. }
  176. protected void updateEnabledState() {
  177. boolean radioButtonEnabled = isEnabled() && !isReadonly();
  178. // sets options enabled according to the widget's enabled,
  179. // readonly and each options own enabled
  180. for (Map.Entry<RadioButton, JsonObject> entry : optionsToItems
  181. .entrySet()) {
  182. RadioButton radioButton = entry.getKey();
  183. JsonObject value = entry.getValue();
  184. Boolean isOptionEnabled = !value
  185. .getBoolean(ListingJsonConstants.JSONKEY_ITEM_DISABLED);
  186. radioButton.setEnabled(radioButtonEnabled && isOptionEnabled);
  187. }
  188. }
  189. public boolean isHtmlContentAllowed() {
  190. return htmlContentAllowed;
  191. }
  192. public void setHtmlContentAllowed(boolean htmlContentAllowed) {
  193. this.htmlContentAllowed = htmlContentAllowed;
  194. }
  195. @Override
  196. public boolean isEnabled() {
  197. return enabled;
  198. }
  199. public boolean isReadonly() {
  200. return readonly;
  201. }
  202. public void setReadonly(boolean readonly) {
  203. if (this.readonly != readonly) {
  204. this.readonly = readonly;
  205. updateEnabledState();
  206. }
  207. }
  208. @Override
  209. public void setEnabled(boolean enabled) {
  210. if (this.enabled != enabled) {
  211. this.enabled = enabled;
  212. updateEnabledState();
  213. }
  214. }
  215. public Registration addSelectionChangeHandler(
  216. Consumer<JsonObject> selectionChanged) {
  217. selectionChangeListeners.add(selectionChanged);
  218. return (Registration) () -> selectionChangeListeners
  219. .remove(selectionChanged);
  220. }
  221. public void selectItemKey(String selectedItemKey) {
  222. if (selectedItemKey != null) {
  223. RadioButton radioButton = keyToOptions.get(selectedItemKey);
  224. if (radioButton != null) { // Items might not be loaded yet
  225. radioButton.setValue(true);
  226. }
  227. } else {
  228. keyToOptions.values().forEach(button -> button.setValue(false));
  229. }
  230. }
  231. }