Skip to content

Commit f9e8802

Browse files
vaadin-botczp13
andauthored
fix: option key does not work in addClickShortCut() method (#16086) (#16250)
* Investigations comments to relevant parts. * formatted files with mvn formatter:format * added potential solution, need to add covering tests as well (for triggering Alt, AltGraph, both of them shall work). * removing comments, and potential solutions which will not be used anymore. * Cleaned up comments to make it cleaner (ShortcutRegistration) - Added tests in ShortcutEventTest and created a new test class for testing filterText generation ShortCutRegistrationFilterText, - Some smaller comment/typo fixes in (Shortcuts), - Changed the fix itself as the tests show it is not handling all the cases properly * mvn formatter:format executed. *fix test name typo. * assertFalse refactor went wrong (double negation), I used assertTrue and forgot to remove the !. Now it shall be good! * after manual testing the code was fixed. * fix the tests for covering the changes that happened in ShortCutRegistration. * mvn formatter:format run once again. * added JavaDoc for the test Reflection used util methods, and some small refactor to have inline variable. * mvn formatter:format run once again + some new asserts in tets as well. * cleanup the code based on Tepi's review, idea! (Thanks!) * "&&&&".split("&&", Integer.MAX_VALUE) -> this will give back ["", "", ""], but without the second parameter, it would have not found these... So with this fix, we will cover more cases. (https://stackoverflow.com/questions/18815911/string-split-and-dealing-with-duplicates) * minor cleanup (Teppo) --------- Co-authored-by: Teppo Kurki <teppo.kurki@vaadin.com> Co-authored-by: czp13 <61667986+czp13@users.noreply.github.com>
1 parent 609e66a commit f9e8802

4 files changed

Lines changed: 199 additions & 19 deletions

File tree

‎flow-server/src/main/java/com/vaadin/flow/component/ShortcutRegistration.java‎

Lines changed: 40 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -50,18 +50,18 @@ public class ShortcutRegistration implements Registration, Serializable {
5050
static final String LISTEN_ON_COMPONENTS_SHOULD_NOT_HAVE_DUPLICATE_ENTRIES = "listenOnComponents should not have duplicate entries!";
5151
static final String ELEMENT_LOCATOR_JS = //@formatter:off
5252
"const listenOn=this;" // this is the listenOn component's element
53-
+ "const delegate=%1$s;" // the output of the JsLocator
54-
+ "if (delegate) {"
55-
+ "delegate.addEventListener('keydown', function(event) {"
56-
+ "if (%2$s) {" // the filter text to match the key
57-
+ "const new_event = new event.constructor(event.type, event);"
58-
+ "listenOn.dispatchEvent(new_event);"
59-
+ "%3$s" // the new event allows default if desired
60-
+ "event.stopPropagation();}" // the new event bubbles if desired
61-
+ "});" // end matches filter
62-
+ "} else {"
63-
+ "throw \"Shortcut listenOn element not found with JS locator string '%1$s'\""
64-
+ "}";//@formatter:on
53+
+ "const delegate=%1$s;" // the output of the JsLocator
54+
+ "if (delegate) {"
55+
+ "delegate.addEventListener('keydown', function(event) {"
56+
+ "if (%2$s) {" // the filter text to match the key
57+
+ "const new_event = new event.constructor(event.type, event);"
58+
+ "listenOn.dispatchEvent(new_event);"
59+
+ "%3$s" // the new event allows default if desired
60+
+ "event.stopPropagation();}" // the new event bubbles if desired
61+
+ "});" // end matches filter
62+
+ "} else {"
63+
+ "throw \"Shortcut listenOn element not found with JS locator string '%1$s'\""
64+
+ "}";//@formatter:on
6565
private boolean allowDefaultBehavior = false;
6666
private boolean allowEventPropagation = false;
6767
static final String LISTEN_ON_INITIALIZED = "_initialized_listen_on_for_component";
@@ -748,16 +748,39 @@ private static String generateEventModifierFilter(
748748

749749
final List<Key> realMods = modifiers.stream().filter(Key::isModifier)
750750
.collect(Collectors.toList());
751-
752751
// build a filter based on all the modifier keys. if modifier is not
753752
// in the parameter collection, require it to be passive to match the
754753
// shortcut
754+
755+
/*
756+
* Due to https://github.com/vaadin/flow/issues/15906. Browsers having
757+
* different implementation for Option keys: -> Mozilla: ALT_GRAPH and
758+
* ALT both are triggered (getModifierState() return true for ALT AND
759+
* ALT_GRAPH), -> Chrome: ALT is triggered only (getModifierState()
760+
* return true for only ALT).
761+
*
762+
* So we need to check if ALT is in the modifiers list, if it is, we do
763+
* not check anymore that !ALT_GRAPH is not in filter list, because it
764+
* can be based on browser implementations.
765+
*/
766+
767+
final boolean altAdded = modifiers
768+
.contains(new HashableKey(KeyModifier.ALT));
769+
755770
return Arrays.stream(KeyModifier.values()).map(modifier -> {
771+
String modKey = modifier.getKeys().get(0);
756772
boolean modifierRequired = realMods.stream()
757-
.anyMatch(mod -> mod.matches(modifier.getKeys().get(0)));
758-
return (modifierRequired ? "" : "!") + "event.getModifierState('"
759-
+ modifier.getKeys().get(0) + "')";
760-
}).collect(Collectors.joining(" && "));
773+
.anyMatch(mod -> mod.matches(modKey));
774+
if (!modifierRequired && modifier == KeyModifier.ALT_GRAPH
775+
&& altAdded) {
776+
return null;
777+
} else {
778+
return (modifierRequired ? "" : "!")
779+
+ "event.getModifierState('" + modKey + "')";
780+
}
781+
}).filter(Objects::nonNull).filter(s -> !s.isBlank())
782+
.collect(Collectors.joining(" && "));
783+
761784
}
762785

763786
private static String generateEventKeyFilter(Key key) {

‎flow-server/src/main/java/com/vaadin/flow/component/Shortcuts.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
* <p>
2525
* Unlike the shortcut methods offered by {@link Focusable} and
2626
* {@link ClickNotifier}, these methods allow for configuring the {@code
27-
* lifecycleOwner} directly, making it possible to added the shortcut onto any
27+
* lifecycleOwner} directly, making it possible to add the shortcut onto any
2828
* component. The {@code lifecycleOwner} denotes the component to which the
2929
* shortcut is bound to. If the lifecycle owner is not attached, visible, or
3030
* enabled, the shortcut won't work, and vice-versa.
@@ -162,7 +162,7 @@ public static ShortcutRegistration addShortcutListener(
162162
*/
163163
public static Registration setShortcutListenOnElement(
164164
String elementLocatorJs, Component listenOnComponent) {
165-
// a bit wasteful to store this for each component instance but it
165+
// a bit wasteful to store this for each component instance, but it
166166
// stays in memory only as long as the component itself does
167167
ComponentUtil.setData(listenOnComponent, ELEMENT_LOCATOR_JS_KEY,
168168
elementLocatorJs);
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
package com.vaadin.flow.component;
2+
3+
import org.apache.commons.lang3.StringUtils;
4+
import org.junit.Test;
5+
6+
import java.lang.reflect.Constructor;
7+
import java.lang.reflect.InvocationTargetException;
8+
import java.lang.reflect.Method;
9+
import java.util.*;
10+
import java.util.stream.Collectors;
11+
12+
import static org.junit.Assert.assertEquals;
13+
import static org.junit.Assert.assertFalse;
14+
import static org.junit.Assert.assertTrue;
15+
16+
public class ShortCutRegistrationFilterTest {
17+
18+
/**
19+
* This method is used to test the generateEventModifierFilter method in the
20+
* ShortcutRegistration class. This method is private, so we need to use
21+
* reflection to invoke it.
22+
*
23+
* @param list
24+
* @return
25+
* @throws NoSuchMethodException
26+
* @throws InvocationTargetException
27+
* @throws IllegalAccessException
28+
*/
29+
private static String invokeGenerateEventModifierFilter(List<Key> list)
30+
throws NoSuchMethodException, InvocationTargetException,
31+
IllegalAccessException {
32+
Method privateMethod = ShortcutRegistration.class.getDeclaredMethod(
33+
"generateEventModifierFilter", Collection.class);
34+
privateMethod.setAccessible(true);
35+
// invoke the private method for testing
36+
String result = (String) privateMethod.invoke(null, list);
37+
return result;
38+
}
39+
40+
/**
41+
* This method is used to get the HashableKey object from the
42+
* ShortcutRegistration class. This is needed because the HashableKey class
43+
* is private, and we need to create an instance of it to test the
44+
* generateEventModifierFilter method.
45+
*
46+
* @param keyModifier
47+
* @return
48+
* @throws ClassNotFoundException
49+
* @throws InvocationTargetException
50+
* @throws InstantiationException
51+
* @throws IllegalAccessException
52+
*/
53+
private static Object getHashableKey(KeyModifier keyModifier)
54+
throws ClassNotFoundException, InvocationTargetException,
55+
InstantiationException, IllegalAccessException {
56+
final Class<?> nestedClass = Class.forName(
57+
"com.vaadin.flow.component.ShortcutRegistration$HashableKey");
58+
final Constructor<?> ctor = nestedClass.getDeclaredConstructors()[0];
59+
ctor.setAccessible(true);
60+
return ctor.newInstance(keyModifier);
61+
}
62+
63+
private static ArrayList<String> getModifierFilterConditions(
64+
String eventModifierFilter, int expectedFilterCount) {
65+
ArrayList<String> filterConditions = new ArrayList<>(Arrays
66+
.asList(eventModifierFilter.split(" && ", Integer.MAX_VALUE)));
67+
assertTrue(
68+
"Split filter conditions should not contain '&' character or blank strings.",
69+
filterConditions.stream()
70+
.filter(c -> c.contains("&") || StringUtils.isBlank(c))
71+
.collect(Collectors.toList()).isEmpty());
72+
assertEquals(expectedFilterCount, filterConditions.size());
73+
return filterConditions;
74+
}
75+
76+
@Test
77+
public void testGenerateEventModifierFilterWithModifierKeyAlt()
78+
throws InvocationTargetException, NoSuchMethodException,
79+
IllegalAccessException, ClassNotFoundException,
80+
InstantiationException {
81+
String result = invokeGenerateEventModifierFilter(Collections
82+
.singletonList(((Key) getHashableKey(KeyModifier.ALT))));
83+
ArrayList<String> conditions = getModifierFilterConditions(result, 4);
84+
assertTrue(conditions.contains("event.getModifierState('Alt')"));
85+
assertTrue(conditions.contains("!event.getModifierState('Control')"));
86+
assertFalse(conditions.contains("event.getModifierState('AltGraph')"));
87+
assertFalse(conditions.contains("!event.getModifierState('AltGraph')"));
88+
}
89+
90+
@Test
91+
public void testGenerateEventModifierFilterWithModifierKeyAltGr()
92+
throws InvocationTargetException, NoSuchMethodException,
93+
IllegalAccessException, ClassNotFoundException,
94+
InstantiationException {
95+
String result = invokeGenerateEventModifierFilter(Collections
96+
.singletonList(((Key) getHashableKey(KeyModifier.ALT_GRAPH))));
97+
ArrayList<String> conditions = getModifierFilterConditions(result, 5);
98+
assertTrue(conditions.contains("event.getModifierState('AltGraph')"));
99+
assertTrue(conditions.contains("!event.getModifierState('Alt')"));
100+
assertTrue(conditions.contains("!event.getModifierState('Control')"));
101+
}
102+
103+
@Test
104+
public void testGenerateEventModifierFilterWithModifierKeyAltAndAltGr()
105+
throws InvocationTargetException, NoSuchMethodException,
106+
IllegalAccessException, ClassNotFoundException,
107+
InstantiationException {
108+
String result = invokeGenerateEventModifierFilter(
109+
Arrays.asList((Key) getHashableKey(KeyModifier.ALT),
110+
(Key) getHashableKey(KeyModifier.ALT_GRAPH)));
111+
ArrayList<String> conditions = getModifierFilterConditions(result, 5);
112+
assertTrue(conditions.contains("event.getModifierState('Alt')"));
113+
assertTrue(conditions.contains("event.getModifierState('AltGraph')"));
114+
assertTrue(conditions.contains("!event.getModifierState('Control')"));
115+
}
116+
117+
@Test
118+
public void testGenerateEventModifierFilterWithModifierKeyAltGrAndCtrl()
119+
throws InvocationTargetException, NoSuchMethodException,
120+
IllegalAccessException, ClassNotFoundException,
121+
InstantiationException {
122+
String result = invokeGenerateEventModifierFilter(
123+
Arrays.asList((Key) getHashableKey(KeyModifier.ALT_GRAPH),
124+
(Key) getHashableKey(KeyModifier.CONTROL)));
125+
ArrayList<String> conditions = getModifierFilterConditions(result, 5);
126+
assertTrue(conditions.contains("event.getModifierState('AltGraph')"));
127+
assertTrue(conditions.contains("event.getModifierState('Control')"));
128+
assertTrue(conditions.contains("!event.getModifierState('Alt')"));
129+
}
130+
131+
@Test
132+
public void testGenerateEventModifierFilterWithModifierKeyAltAndCtrl()
133+
throws InvocationTargetException, NoSuchMethodException,
134+
IllegalAccessException, ClassNotFoundException,
135+
InstantiationException {
136+
String result = invokeGenerateEventModifierFilter(
137+
Arrays.asList((Key) getHashableKey(KeyModifier.ALT),
138+
(Key) getHashableKey(KeyModifier.CONTROL)));
139+
ArrayList<String> conditions = getModifierFilterConditions(result, 4);
140+
assertTrue(conditions.contains("event.getModifierState('Alt')"));
141+
assertTrue(conditions.contains("event.getModifierState('Control')"));
142+
assertFalse(conditions.contains("event.getModifierState('AltGraph')"));
143+
assertFalse(conditions.contains("!event.getModifierState('AltGraph')"));
144+
}
145+
}

‎flow-server/src/test/java/com/vaadin/flow/component/ShortcutEventTest.java‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ public class ShortcutEventTest {
1515
private ShortcutEvent eventTwoModifiers = event(Key.KEY_F, KeyModifier.ALT,
1616
KeyModifier.CONTROL);
1717

18+
private ShortcutEvent eventWithAltAndAltGr = event(Key.KEY_F,
19+
KeyModifier.ALT, KeyModifier.ALT_GRAPH);
20+
1821
@Test
1922
public void matches() {
2023
assertFalse("Null key should return false",
@@ -23,6 +26,11 @@ public void matches() {
2326
eventNoModifiers.matches(Key.KEY_F, KeyModifier.ALT));
2427
assertFalse("Missing modifier should return false",
2528
eventOneModifier.matches(Key.KEY_F));
29+
assertFalse(
30+
"Matching key and two modifiers (Alt, Alt_Gr) plus an extra one (Control), "
31+
+ "should return false",
32+
eventWithAltAndAltGr.matches(Key.KEY_F, KeyModifier.ALT,
33+
KeyModifier.ALT_GRAPH, KeyModifier.CONTROL));
2634

2735
assertTrue("Matching key should return true",
2836
eventNoModifiers.matches(Key.KEY_F));
@@ -31,6 +39,10 @@ public void matches() {
3139
assertTrue("Matching key and two modifiers should return true",
3240
eventTwoModifiers.matches(Key.KEY_F, KeyModifier.ALT,
3341
KeyModifier.CONTROL));
42+
assertTrue(
43+
"Matching key and two modifiers (Alt_Gr, Alt) should return true",
44+
eventWithAltAndAltGr.matches(Key.KEY_F, KeyModifier.ALT_GRAPH,
45+
KeyModifier.ALT));
3446
}
3547

3648
private static ShortcutEvent event(Key key, KeyModifier... modifiers) {

0 commit comments

Comments
 (0)