Skip to content

Commit 659d955

Browse files
[CP-beta][web] ClickDebouncer workaround for iOS Safari click behavior (#173072)
This pull request is created by [automatic cherry pick workflow](https://github.com/flutter/flutter/blob/main/docs/releases/Flutter-Cherrypick-Process.md#automatically-creates-a-cherry-pick-request) ### Issue Link: What is the link to the issue this cherry-pick is addressing? flutter/flutter#172180 ### Changelog Description: Fix a bug that causes the web engine to double report taps on dropdown menu items on iOS Safari. ### Impact Description: It breaks Flutter Web apps that use dropdown menus with semantics enabled on iOS Safari. ### Workaround: Is there a workaround for this issue? No. ### Risk: What is the risk level of this cherry-pick? ### Test Coverage: Are you confident that your fix is well-tested by automated tests? ### Validation Steps: What are the steps to validate that this fix works? Follow repro steps in flutter/flutter#172180
1 parent 26b84dd commit 659d955

2 files changed

Lines changed: 136 additions & 28 deletions

File tree

‎engine/src/flutter/lib/web_ui/lib/src/engine/pointer_binding.dart‎

Lines changed: 62 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ class PointerBinding {
167167
typedef QueuedEvent = ({DomEvent event, Duration timeStamp, List<ui.PointerData> data});
168168

169169
@visibleForTesting
170-
typedef DebounceState = ({DomElement target, Timer timer, List<QueuedEvent> queue});
170+
typedef DebounceState = ({DomEventTarget target, Timer timer, List<QueuedEvent> queue});
171171

172172
/// Disambiguates taps and clicks that are produced both by the framework from
173173
/// `pointerdown`/`pointerup` events and those detected as DOM "click" events by
@@ -221,7 +221,8 @@ class ClickDebouncer {
221221
/// This value is normally false, and it flips to true when the first
222222
/// pointerdown is observed that lands on a tappable semantics node, denoted
223223
/// by the presence of the `flt-tappable` attribute.
224-
bool get isDebouncing => _state != null;
224+
bool get isDebouncing => _isDebouncing;
225+
bool _isDebouncing = false;
225226

226227
/// Processes a pointer event.
227228
///
@@ -245,7 +246,7 @@ class ClickDebouncer {
245246
if (isDebouncing) {
246247
_debounce(event, data);
247248
} else if (event.type == 'pointerdown') {
248-
_startDebouncing(event, data);
249+
_maybeStartDebouncing(event, data);
249250
} else {
250251
if (event.type == 'pointerup') {
251252
// Record the last pointerup event even if not debouncing. This is
@@ -313,43 +314,74 @@ class ClickDebouncer {
313314
reset();
314315
}
315316

316-
void _startDebouncing(DomEvent event, List<ui.PointerData> data) {
317-
assert(_state == null, 'Cannot start debouncing. Already debouncing.');
317+
/// Starts debouncing pointer events if the [event] is a `pointerdown` on a
318+
/// tappable element.
319+
///
320+
/// To work around an issue in iOS Safari, the debouncing does not start
321+
/// immediately, but at the end of the event loop.
322+
///
323+
/// See also:
324+
///
325+
/// * [_doStartDebouncing], which actually starts the debouncing.
326+
void _maybeStartDebouncing(DomEvent event, List<ui.PointerData> data) {
327+
assert(!isDebouncing, 'Cannot start debouncing. Already debouncing.');
318328
assert(event.type == 'pointerdown', 'Click debouncing must begin with a pointerdown');
319329

320330
final DomEventTarget? target = event.target;
321331
if (target.isA<DomElement>() && (target! as DomElement).hasAttribute('flt-tappable')) {
322-
_state = (
323-
target: target as DomElement,
324-
// The 200ms duration was chosen empirically by testing tapping, mouse
325-
// clicking, trackpad tapping and clicking, as well as the following
326-
// screen readers: TalkBack on Android, VoiceOver on macOS, Narrator/
327-
// NVDA/JAWS on Windows. 200ms seemed to hit the sweet spot by
328-
// satisfying the following:
329-
// * It was short enough that delaying the `pointerdown` still allowed
330-
// drag gestures to begin reasonably soon (e.g. scrolling).
331-
// * It was long enough to register taps and clicks.
332-
// * It was successful at detecting taps generated by all tested
333-
// screen readers.
334-
timer: Timer(const Duration(milliseconds: 200), _onTimerExpired),
335-
queue: <QueuedEvent>[
336-
(
337-
event: event,
338-
timeStamp: _BaseAdapter._eventTimeStampToDuration(event.timeStamp!),
339-
data: data,
340-
),
341-
],
342-
);
332+
// In some cases, iOS Safari tracks timers that are initiated from within a `pointerdown`
333+
// event, and waits until those timers go off before sending the `click` event.
334+
//
335+
// This iOS Safari behavior breaks the `ClickDebouncer` because it creates a 200ms timer. To
336+
// work around it, the `ClickDebouncer` should start debouncing after the end of the event
337+
// loop.
338+
//
339+
// See: https://github.com/flutter/flutter/issues/172180
340+
_isDebouncing = true;
341+
Timer.run(() => _doStartDebouncing(event, data));
343342
} else {
344343
// The event landed on an non-tappable target. Assume this won't lead to
345344
// double clicks and forward the event to the framework.
346345
_sendToFramework(event, data);
347346
}
348347
}
349348

349+
/// The core logic for starting to debounce pointer events.
350+
///
351+
/// This method is called asynchronously from [_maybeStartDebouncing].
352+
void _doStartDebouncing(DomEvent event, List<ui.PointerData> data) {
353+
// It's possible that debouncing was cancelled between the pointerdown event and the execution
354+
// of this method.
355+
if (!isDebouncing) {
356+
return;
357+
}
358+
359+
_state = (
360+
target: event.target!,
361+
// The 200ms duration was chosen empirically by testing tapping, mouse
362+
// clicking, trackpad tapping and clicking, as well as the following
363+
// screen readers: TalkBack on Android, VoiceOver on macOS, Narrator/
364+
// NVDA/JAWS on Windows. 200ms seemed to hit the sweet spot by
365+
// satisfying the following:
366+
// * It was short enough that delaying the `pointerdown` still allowed
367+
// drag gestures to begin reasonably soon (e.g. scrolling).
368+
// * It was long enough to register taps and clicks.
369+
// * It was successful at detecting taps generated by all tested
370+
// screen readers.
371+
timer: Timer(const Duration(milliseconds: 200), _onTimerExpired),
372+
queue: <QueuedEvent>[
373+
(
374+
event: event,
375+
timeStamp: _BaseAdapter._eventTimeStampToDuration(event.timeStamp!),
376+
data: data,
377+
),
378+
],
379+
);
380+
}
381+
350382
void _debounce(DomEvent event, List<ui.PointerData> data) {
351383
assert(
352-
_state != null,
384+
isDebouncing,
353385
'Cannot debounce event. Debouncing state not established by _startDebouncing.',
354386
);
355387

@@ -394,7 +426,7 @@ class ClickDebouncer {
394426
}
395427

396428
void _flush() {
397-
assert(_state != null);
429+
assert(isDebouncing);
398430

399431
final DebounceState state = _state!;
400432
state.timer.cancel();
@@ -409,6 +441,7 @@ class ClickDebouncer {
409441

410442
_sendToFramework(null, aggregateData);
411443
_state = null;
444+
_isDebouncing = false;
412445
}
413446

414447
void _sendToFramework(DomEvent? event, List<ui.PointerData> data) {
@@ -428,6 +461,7 @@ class ClickDebouncer {
428461
void reset() {
429462
_state?.timer.cancel();
430463
_state = null;
464+
_isDebouncing = false;
431465
_lastSentPointerUpTimeStamp = null;
432466
}
433467
}

‎engine/src/flutter/lib/web_ui/test/engine/pointer_binding_test.dart‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2580,6 +2580,10 @@ void _testClickDebouncer({required PointerBinding Function() getBinding}) {
25802580
late _PointerEventContext context;
25812581
late PointerBinding binding;
25822582

2583+
Future<void> nextEventLoop() {
2584+
return Future.delayed(Duration.zero);
2585+
}
2586+
25832587
void testWithSemantics(
25842588
String description,
25852589
Future<void> Function() body, {
@@ -2635,6 +2639,7 @@ void _testClickDebouncer({required PointerBinding Function() getBinding}) {
26352639
view.dom.semanticsHost.appendChild(testElement);
26362640

26372641
testElement.dispatchEvent(context.primaryDown());
2642+
await nextEventLoop();
26382643
testElement.dispatchEvent(context.primaryUp());
26392644
expect(PointerBinding.clickDebouncer.isDebouncing, false);
26402645

@@ -2646,6 +2651,71 @@ void _testClickDebouncer({required PointerBinding Function() getBinding}) {
26462651
expect(semanticsActions, isEmpty);
26472652
});
26482653

2654+
testWithSemantics('Does not start debouncing if reset before scheduled execution', () async {
2655+
expect(EnginePlatformDispatcher.instance.semanticsEnabled, isTrue);
2656+
expect(PointerBinding.clickDebouncer.isDebouncing, isFalse);
2657+
expect(PointerBinding.clickDebouncer.debugState, isNull);
2658+
2659+
final DomElement testElement = createDomElement('flt-semantics');
2660+
testElement.setAttribute('flt-tappable', '');
2661+
view.dom.semanticsHost.appendChild(testElement);
2662+
2663+
// 1. Trigger _maybeStartDebouncing, which sets _isDebouncing = true and schedules _doStartDebouncing.
2664+
testElement.dispatchEvent(context.primaryDown());
2665+
2666+
// At this point, _isDebouncing is true, but _doStartDebouncing (which sets _state and creates the Timer)
2667+
// has not yet executed because it was scheduled with Timer.run().
2668+
expect(PointerBinding.clickDebouncer.isDebouncing, isTrue);
2669+
expect(PointerBinding.clickDebouncer.debugState, isNull); // _state is still null
2670+
2671+
// 2. Simulate a scenario where reset() is called before _doStartDebouncing gets a chance to run.
2672+
// This could happen due to a hot restart or other lifecycle events.
2673+
PointerBinding.clickDebouncer.reset();
2674+
2675+
// After reset(), _isDebouncing should be false and _state should still be null.
2676+
expect(PointerBinding.clickDebouncer.isDebouncing, isFalse);
2677+
expect(PointerBinding.clickDebouncer.debugState, isNull);
2678+
2679+
// 3. Allow the scheduled _doStartDebouncing to run. With the fix, it should now check
2680+
// `!isDebouncing` and return early.
2681+
await nextEventLoop();
2682+
2683+
// Verify that _doStartDebouncing did not proceed to set _state or create a Timer.
2684+
expect(PointerBinding.clickDebouncer.isDebouncing, isFalse);
2685+
expect(PointerBinding.clickDebouncer.debugState, isNull);
2686+
2687+
// Ensure no events were sent to the framework as debouncing was effectively cancelled.
2688+
expect(pointerPackets, isEmpty);
2689+
expect(semanticsActions, isEmpty);
2690+
});
2691+
2692+
testWithSemantics('Starts debouncing after event loop', () async {
2693+
expect(EnginePlatformDispatcher.instance.semanticsEnabled, isTrue);
2694+
expect(PointerBinding.clickDebouncer.isDebouncing, isFalse);
2695+
2696+
final DomElement testElement = createDomElement('flt-semantics');
2697+
testElement.setAttribute('flt-tappable', '');
2698+
view.dom.semanticsHost.appendChild(testElement);
2699+
2700+
testElement.dispatchEvent(context.primaryDown());
2701+
// ClickDebouncer does not start debouncing right away.
2702+
expect(PointerBinding.clickDebouncer.isDebouncing, isTrue);
2703+
expect(PointerBinding.clickDebouncer.debugState, isNull);
2704+
// Instead, it waits until the end of the event loop.
2705+
await nextEventLoop();
2706+
expect(PointerBinding.clickDebouncer.isDebouncing, isTrue);
2707+
expect(PointerBinding.clickDebouncer.debugState, isNotNull);
2708+
2709+
final DomEvent click = createDomMouseEvent('click', <Object?, Object?>{
2710+
'clientX': testElement.getBoundingClientRect().x,
2711+
'clientY': testElement.getBoundingClientRect().y,
2712+
});
2713+
2714+
PointerBinding.clickDebouncer.onClick(click, view.viewId, 42, true);
2715+
expect(pointerPackets, isEmpty);
2716+
expect(semanticsActions, <CapturedSemanticsEvent>[(type: ui.SemanticsAction.tap, nodeId: 42)]);
2717+
});
2718+
26492719
testWithSemantics('Accumulates pointer events starting from pointerdown', () async {
26502720
expect(EnginePlatformDispatcher.instance.semanticsEnabled, true);
26512721
expect(PointerBinding.clickDebouncer.isDebouncing, false);
@@ -2661,6 +2731,7 @@ void _testClickDebouncer({required PointerBinding Function() getBinding}) {
26612731
true,
26622732
);
26632733

2734+
await nextEventLoop();
26642735
testElement.dispatchEvent(context.primaryUp());
26652736
expect(
26662737
reason: 'Should still be debouncing after pointerup',
@@ -2709,6 +2780,7 @@ void _testClickDebouncer({required PointerBinding Function() getBinding}) {
27092780
true,
27102781
);
27112782

2783+
await nextEventLoop();
27122784
final DomElement newTarget = createDomElement('flt-semantics');
27132785
newTarget.setAttribute('flt-tappable', '');
27142786
view.dom.semanticsHost.appendChild(newTarget);
@@ -2759,6 +2831,7 @@ void _testClickDebouncer({required PointerBinding Function() getBinding}) {
27592831
testElement.dispatchEvent(context.primaryDown());
27602832
expect(PointerBinding.clickDebouncer.isDebouncing, true);
27612833

2834+
await nextEventLoop();
27622835
final DomEvent click = createDomMouseEvent('click', <Object?, Object?>{
27632836
'clientX': testElement.getBoundingClientRect().x,
27642837
'clientY': testElement.getBoundingClientRect().y,
@@ -2778,6 +2851,7 @@ void _testClickDebouncer({required PointerBinding Function() getBinding}) {
27782851
testElement.dispatchEvent(context.primaryDown());
27792852
expect(PointerBinding.clickDebouncer.isDebouncing, true);
27802853

2854+
await nextEventLoop();
27812855
final DomEvent click = createDomMouseEvent('click', <Object?, Object?>{
27822856
'clientX': testElement.getBoundingClientRect().x,
27832857
'clientY': testElement.getBoundingClientRect().y,

0 commit comments

Comments
 (0)