Skip to content

Commit 72d62c2

Browse files
authored
fix: sync property change properly using debouncer (#17971)
* fix: sync property change properly using debouncer Fixes `Element#addPropertyChangeListener(String, String, PropertyChangeListener)` using `debounce(int)` to synchronize changed property value to the server even when explicitly firing more than one event in a row, while still being inside the debounce timeout time window. Previously, following events caused the first property change command to never run because the first command was cancelled in favor for the new command. New command is always a NO_OP due to the property not being changed again in this use case (#17931, it was detected as changed already for the first command). This change has effect only when using TRAILING debounce phase (default). Fixes: #17931 * Keeping intermediate phase working the same it was * Fixed formatting * Added test for multiple events and value changes ---------
1 parent a959c6c commit 72d62c2

6 files changed

Lines changed: 174 additions & 50 deletions

File tree

‎flow-client/src/main/java/com/vaadin/client/flow/binding/Debouncer.java‎

Lines changed: 74 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import com.vaadin.client.flow.collection.JsMap;
2424
import com.vaadin.client.flow.collection.JsMap.ForEachCallback;
2525
import com.vaadin.client.flow.collection.JsSet;
26+
import com.vaadin.client.flow.nodefeature.MapProperty;
2627
import com.vaadin.flow.shared.JsonConstants;
2728

2829
import elemental.dom.Node;
@@ -47,8 +48,11 @@ public class Debouncer {
4748
private Timer idleTimer;
4849
private Timer intermediateTimer;
4950

50-
private Consumer<String> bufferedCommand;
51+
private Consumer<String> bufferedSendCommand;
52+
private JsMap<String, Runnable> bufferedCommands;
53+
private JsMap<String, Runnable> previousBufferedNonExecutedCommands;
5154
private Consumer<String> potentialTrailingWithBothTrailingAndIntermediate;
55+
private JsMap<String, Runnable> potentialTrailingWithBothTrailingAndIntermediateBufferedCommands;
5256

5357
private Debouncer(Node element, String identifier, double timeout) {
5458
this.element = element;
@@ -65,10 +69,15 @@ private Debouncer(Node element, String identifier, double timeout) {
6569
* @param command
6670
* a consumer that will may be asynchronously invoked with a
6771
* phase code if an associated phase is triggered
72+
* @param commands
73+
* individual commands executed just before the given send
74+
* command
75+
*
6876
* @return <code>true</code> if the event should be processed as-is without
6977
* delaying
7078
*/
71-
public boolean trigger(JsSet<String> phases, Consumer<String> command) {
79+
public boolean trigger(JsSet<String> phases, Consumer<String> command,
80+
JsMap<String, Runnable> commands) {
7281
// If "leading" events are requested and no timers created yet,
7382
// this is considered the leading event that is triggered immediately
7483
// and there is no need to save it
@@ -79,8 +88,15 @@ public boolean trigger(JsSet<String> phases, Consumer<String> command) {
7988
&& (phases.has(JsonConstants.EVENT_PHASE_TRAILING) || phases
8089
.has(JsonConstants.EVENT_PHASE_INTERMEDIATE))) {
8190
// last command is saved for timers unless this is a "leading" event
82-
bufferedCommand = command;
91+
bufferedSendCommand = command;
92+
bufferedCommands = commands;
93+
if (!phases.has(JsonConstants.EVENT_PHASE_INTERMEDIATE)
94+
&& (idleTimer == null
95+
|| previousBufferedNonExecutedCommands == null)) {
96+
previousBufferedNonExecutedCommands = commands;
97+
}
8398
potentialTrailingWithBothTrailingAndIntermediate = null;
99+
potentialTrailingWithBothTrailingAndIntermediateBufferedCommands = null;
84100
}
85101
// idleTimer is used for trailing/leading, should always be there?
86102
if (phases.has(JsonConstants.EVENT_PHASE_LEADING)
@@ -89,10 +105,13 @@ public boolean trigger(JsSet<String> phases, Consumer<String> command) {
89105
idleTimer = new Timer() {
90106
@Override
91107
public void run() {
92-
if (bufferedCommand != null) {
93-
bufferedCommand
94-
.accept(JsonConstants.EVENT_PHASE_TRAILING);
95-
bufferedCommand = null;
108+
if (bufferedSendCommand != null) {
109+
runCommands(JsonConstants.EVENT_PHASE_TRAILING,
110+
bufferedSendCommand, bufferedCommands,
111+
previousBufferedNonExecutedCommands);
112+
bufferedSendCommand = null;
113+
bufferedCommands = null;
114+
previousBufferedNonExecutedCommands = null;
96115
} else if (potentialTrailingWithBothTrailingAndIntermediate != null) {
97116
/*
98117
* This happens if both trailing & intermediate are
@@ -103,10 +122,12 @@ public void run() {
103122
* ugly but maybe handy for some people in some
104123
* situations.
105124
*/
106-
potentialTrailingWithBothTrailingAndIntermediate
107-
.accept(JsonConstants.EVENT_PHASE_TRAILING);
125+
runCommands(JsonConstants.EVENT_PHASE_TRAILING,
126+
potentialTrailingWithBothTrailingAndIntermediate,
127+
potentialTrailingWithBothTrailingAndIntermediateBufferedCommands,
128+
null);
108129
}
109-
unregister(); // unregister to releease memory
130+
unregister(); // unregister to release memory
110131
}
111132
};
112133
}
@@ -119,13 +140,15 @@ public void run() {
119140
intermediateTimer = new Timer() {
120141
@Override
121142
public void run() {
122-
if (bufferedCommand != null) {
123-
bufferedCommand
124-
.accept(JsonConstants.EVENT_PHASE_INTERMEDIATE);
143+
if (bufferedSendCommand != null) {
144+
runCommands(JsonConstants.EVENT_PHASE_INTERMEDIATE,
145+
bufferedSendCommand, bufferedCommands, null);
125146
if (phases.has(JsonConstants.EVENT_PHASE_TRAILING)) {
126-
potentialTrailingWithBothTrailingAndIntermediate = bufferedCommand;
147+
potentialTrailingWithBothTrailingAndIntermediate = bufferedSendCommand;
148+
potentialTrailingWithBothTrailingAndIntermediateBufferedCommands = bufferedCommands;
127149
}
128-
bufferedCommand = null;
150+
bufferedSendCommand = null;
151+
bufferedCommands = null;
129152
} else {
130153
// no new last command during the period, stop timer
131154
// and unregister to avoid memory leaks
@@ -138,6 +161,30 @@ public void run() {
138161
return triggerImmediately;
139162
}
140163

164+
private static void runCommands(String phase, Consumer<String> sendCommand,
165+
JsMap<String, Runnable> commands,
166+
JsMap<String, Runnable> previousCommands) {
167+
if (JsonConstants.EVENT_PHASE_TRAILING.equals(phase)) {
168+
commands.forEach((command, property) -> {
169+
if (command == MapProperty.NO_OP
170+
&& hasPreviousCommand(previousCommands, property)) {
171+
previousCommands.get(property).run();
172+
} else {
173+
command.run();
174+
}
175+
});
176+
} else {
177+
commands.mapValues().forEach(Runnable::run);
178+
}
179+
sendCommand.accept(phase);
180+
}
181+
182+
private static boolean hasPreviousCommand(
183+
JsMap<String, Runnable> previousCommands, String property) {
184+
return previousCommands != null && property != null
185+
&& previousCommands.has(property);
186+
}
187+
141188
private void unregister() {
142189
if (intermediateTimer != null) {
143190
intermediateTimer.cancel();
@@ -223,11 +270,12 @@ public void accept(JsMap<String, JsMap<Double, Debouncer>> jsmap,
223270
jsmap.mapValues().forEach(value -> {
224271
value.mapValues().forEach(debouncer -> {
225272
if (debouncer.idleTimer != null) {
226-
if (debouncer.bufferedCommand != null) {
273+
if (debouncer.bufferedSendCommand != null) {
227274
// if there is trailing timer, consider as extra
228275
// trailing event
229-
debouncer.bufferedCommand.accept(
230-
JsonConstants.EVENT_PHASE_TRAILING);
276+
runCommands(JsonConstants.EVENT_PHASE_TRAILING,
277+
debouncer.bufferedSendCommand,
278+
debouncer.bufferedCommands, null);
231279
} else {
232280
// "Debouncer was in queue, but no command.
233281
// Likely a leading only subscription."
@@ -237,18 +285,21 @@ public void accept(JsMap<String, JsMap<Double, Debouncer>> jsmap,
237285
// Because of an other triggered event, this now
238286
// comes bit early, but most likely this is better
239287
// than in wrong order
240-
debouncer.bufferedCommand.accept(
241-
JsonConstants.EVENT_PHASE_INTERMEDIATE);
288+
runCommands(JsonConstants.EVENT_PHASE_INTERMEDIATE,
289+
debouncer.bufferedSendCommand,
290+
debouncer.bufferedCommands, null);
242291
// Restart intermediate timer so that there won't
243292
// be triggering more than one event "quicker than
244293
// orderd" in the orginal schedule.
245294
debouncer.intermediateTimer
246295
.scheduleRepeating((int) debouncer.timeout);
247296
}
248-
if (debouncer.bufferedCommand != null) {
249-
executedCommands.add(debouncer.bufferedCommand);
297+
if (debouncer.bufferedSendCommand != null) {
298+
executedCommands.add(debouncer.bufferedSendCommand);
250299
// clean so that idle timer can't fire it again
251-
debouncer.bufferedCommand = null;
300+
debouncer.bufferedSendCommand = null;
301+
debouncer.bufferedCommands = null;
302+
debouncer.previousBufferedNonExecutedCommands = null;
252303
}
253304
});
254305
});

‎flow-client/src/main/java/com/vaadin/client/flow/binding/SimpleElementBindingStrategy.java‎

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
*/
1616
package com.vaadin.client.flow.binding;
1717

18+
import java.util.function.BiConsumer;
1819
import java.util.function.Consumer;
1920
import java.util.function.Supplier;
2021

@@ -1299,18 +1300,16 @@ private void handleDomEvent(Event event, BindingContext context) {
12991300
}
13001301
}
13011302

1302-
JsArray<Runnable> commands = JsCollections.array();
1303-
synchronizeProperties.forEach(
1304-
name -> commands.push(getSyncPropertyCommand(name, context)));
1303+
JsMap<String, Runnable> commands = JsCollections.map();
1304+
synchronizeProperties.forEach(name -> commands.set(name,
1305+
getSyncPropertyCommand(name, context)));
13051306

13061307
Consumer<String> sendCommand = debouncePhase -> {
1307-
commands.forEach(Runnable::run);
1308-
13091308
sendEventToServer(node, type, eventData, debouncePhase);
13101309
};
13111310

13121311
boolean sendNow = resolveFilters(element, type, expressionSettings,
1313-
eventData, sendCommand);
1312+
eventData, sendCommand, commands);
13141313

13151314
if (sendNow) {
13161315
// Send if there were not filters or at least one matched
@@ -1326,6 +1325,7 @@ private void handleDomEvent(Event event, BindingContext context) {
13261325
}
13271326

13281327
if (!commandAlreadyExecuted) {
1328+
commands.mapValues().forEach(Runnable::run);
13291329
sendCommand.accept(null);
13301330
}
13311331
}
@@ -1356,7 +1356,7 @@ private static void sendEventToServer(StateNode node, String type,
13561356

13571357
private static boolean resolveFilters(Node element, String eventType,
13581358
JsonObject expressionSettings, JsonObject eventData,
1359-
Consumer<String> sendCommand) {
1359+
Consumer<String> sendCommand, JsMap<String, Runnable> commands) {
13601360

13611361
boolean noFilters = true;
13621362
boolean atLeastOneFilterMatched = false;
@@ -1378,7 +1378,7 @@ private static boolean resolveFilters(Node element, String eventType,
13781378

13791379
// Count as a match only if at least one debounce is eager
13801380
filterMatched = resolveDebounces(element, debouncerId,
1381-
(JsonArray) settings, sendCommand);
1381+
(JsonArray) settings, sendCommand, commands);
13821382
}
13831383

13841384
atLeastOneFilterMatched |= filterMatched;
@@ -1388,7 +1388,8 @@ private static boolean resolveFilters(Node element, String eventType,
13881388
}
13891389

13901390
private static boolean resolveDebounces(Node element, String debouncerId,
1391-
JsonArray debounceList, Consumer<String> command) {
1391+
JsonArray debounceList, Consumer<String> sendCommand,
1392+
JsMap<String, Runnable> commands) {
13921393
boolean atLeastOneEager = false;
13931394

13941395
for (int i = 0; i < debounceList.length(); i++) {
@@ -1408,7 +1409,7 @@ private static boolean resolveDebounces(Node element, String debouncerId,
14081409
}
14091410

14101411
boolean eager = Debouncer.getOrCreate(element, debouncerId, timeout)
1411-
.trigger(phases, command);
1412+
.trigger(phases, sendCommand, commands);
14121413

14131414
atLeastOneEager |= eager;
14141415
}

‎flow-client/src/main/java/com/vaadin/client/flow/nodefeature/MapProperty.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public class MapProperty implements ReactiveValue {
4343
*/
4444
private boolean isServerUpdate;
4545

46-
private static final Runnable NO_OP = () -> {
46+
public static final Runnable NO_OP = () -> {
4747
};
4848

4949
private final ReactiveEventRouter<MapPropertyChangeListener, MapPropertyChangeEvent> eventRouter = new ReactiveEventRouter<MapPropertyChangeListener, MapPropertyChangeEvent>(

‎flow-client/src/test-gwt/java/com/vaadin/client/flow/GwtPropertyElementBinderTest.java‎

Lines changed: 30 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -198,13 +198,19 @@ public void testFlushPendingChangesOnDomEvent() {
198198
Binder.bind(node, element);
199199

200200
AtomicInteger commandExecution = new AtomicInteger();
201+
JsMap<String, Runnable> commands = JsCollections.map();
202+
commands.set("prop", () -> {
203+
commandExecution.incrementAndGet();
204+
});
205+
206+
AtomicInteger sendCommandExecution = new AtomicInteger();
201207
Debouncer debouncer = Debouncer.getOrCreate(element, "on-value:false",
202208
300);
203209
debouncer.trigger(JsCollections.<String> set()
204210
.add(JsonConstants.EVENT_PHASE_TRAILING), phase -> {
205211
Console.log("PHASE:" + phase);
206-
commandExecution.incrementAndGet();
207-
});
212+
sendCommandExecution.incrementAndGet();
213+
}, commands);
208214

209215
String constantPoolKey = "expressionsKey";
210216
JsonObject expressions = Json.createObject();
@@ -219,13 +225,15 @@ public void testFlushPendingChangesOnDomEvent() {
219225

220226
dispatchEvent("event1");
221227

222-
// Note for future heroes: if this assert fails, you'll get very
228+
// Note for future heroes: if this assert fails, you'll get very
223229
// cryptic class cast exception.
224230
assertEquals("Changes should have not been flushed", 0,
231+
sendCommandExecution.get());
232+
assertEquals("Command should have not been run", 0,
225233
commandExecution.get());
226234

227235
waitForDebouncerToCleanUp();
228-
236+
229237
}
230238

231239
public void testDoNotFlushPendingChangesOnPropertySynchronization() {
@@ -235,13 +243,19 @@ public void testDoNotFlushPendingChangesOnPropertySynchronization() {
235243
Binder.bind(node, element);
236244

237245
AtomicInteger commandExecution = new AtomicInteger();
246+
JsMap<String, Runnable> commands = JsCollections.map();
247+
commands.set("prop", () -> {
248+
commandExecution.incrementAndGet();
249+
});
250+
251+
AtomicInteger sendCommandExecution = new AtomicInteger();
238252
Debouncer debouncer = Debouncer.getOrCreate(element, "on-value:false",
239253
300);
240254
debouncer.trigger(JsCollections.<String> set()
241255
.add(JsonConstants.EVENT_PHASE_TRAILING), phase -> {
242256
Console.log("PHASE:" + phase);
243-
commandExecution.incrementAndGet();
244-
});
257+
sendCommandExecution.incrementAndGet();
258+
}, commands);
245259

246260
String constantPoolKey = "expressionsKey";
247261
JsonObject expressions = Json.createObject();
@@ -254,20 +268,21 @@ public void testDoNotFlushPendingChangesOnPropertySynchronization() {
254268

255269
dispatchEvent("event1");
256270

257-
// Note for future heroes: if this assert fails, you'll get very
271+
// Note for future heroes: if this assert fails, you'll get very
258272
// cryptic class cast exception.
259273
assertEquals("Changes should have been flushed", 1,
260-
commandExecution.get());
261-
274+
sendCommandExecution.get());
275+
assertEquals("Command should have been run", 1, commandExecution.get());
276+
262277
waitForDebouncerToCleanUp();
263278

264279
}
265-
280+
266281
/**
267-
* Waits a while to so that cached Debouncers are cleared by timer for a stable
268-
* startup situation for next tests. If there are existing debouncers, you
269-
* will apparently get very weird looking class cast exceptions because of GWT bugs
270-
* and our hacky workarounds.
282+
* Waits a while to so that cached Debouncers are cleared by timer for a
283+
* stable startup situation for next tests. If there are existing
284+
* debouncers, you will apparently get very weird looking class cast
285+
* exceptions because of GWT bugs and our hacky workarounds.
271286
*/
272287
private void waitForDebouncerToCleanUp() {
273288
new Timer() {
@@ -278,7 +293,7 @@ public void run() {
278293
}.schedule(900);
279294
// Wait for debouncer to be unregistered
280295
delayTestFinish(1000);
281-
296+
282297
}
283298

284299
protected StateNode createNode() {

0 commit comments

Comments
 (0)