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

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