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 9.2KB

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