1 /*
2  * ButtonClickManager.java
3  *
4  * Copyright (C) 2021 by RStudio, PBC
5  *
6  * Unless you have received this program directly from RStudio pursuant
7  * to the terms of a commercial license agreement with RStudio, then
8  * this program is licensed to you under the terms of version 3 of the
9  * GNU Affero General Public License. This program is distributed WITHOUT
10  * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
11  * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
12  * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
13  *
14  */
15 package org.rstudio.core.client.widget.events;
16 
17 import com.google.gwt.dom.client.Document;
18 import com.google.gwt.dom.client.NativeEvent;
19 import com.google.gwt.event.dom.client.ClickEvent;
20 import com.google.gwt.event.dom.client.ClickHandler;
21 import com.google.gwt.event.dom.client.DomEvent;
22 import com.google.gwt.event.dom.client.KeyCodes;
23 import com.google.gwt.event.dom.client.KeyDownEvent;
24 import com.google.gwt.event.shared.HandlerManager;
25 import com.google.gwt.event.shared.HasHandlers;
26 import com.google.gwt.user.client.ui.Widget;
27 
28 /**
29  * Helper for extending UI elements that activate via click to also
30  * activate via spacebar.
31  */
32 public class ButtonClickManager extends HandlerManager implements HasHandlers
33 {
ButtonClickManager(Widget widget, ClickHandler clickHandler)34    public ButtonClickManager(Widget widget, ClickHandler clickHandler)
35    {
36       super(null);
37       widget.addDomHandler(clickHandler, ClickEvent.getType());
38       addHandler(ClickEvent.getType(), clickHandler);
39       widget.addDomHandler(event -> {
40             if (event.getNativeKeyCode() == KeyCodes.KEY_SPACE)
41             {
42                event.stopPropagation();
43                event.preventDefault();
44                click();
45             }
46          }, KeyDownEvent.getType());
47    }
48 
click()49    private void click()
50    {
51       NativeEvent clickEvent = Document.get().createClickEvent(
52             1, 0, 0, 0, 0, false, false, false, false);
53       DomEvent.fireNativeEvent(clickEvent, this);
54    }
55 }
56