Skip to content

Commit 634b0ed

Browse files
authored
Reland "[web] Keep the keyboard up during an iOS caret drag" (#190942)
Fixes #189744 **Reland of #190014, reverted in #190926.** Cause: three of the new tests dispatch a real input.blur(), but desktop Safari uses SafariDesktopTextEditingStrategy, which does not subscribe to blur, so handleBlur never ran. Real iOS does subscribe, so the fix itself was unaffected. Delta: one test-only commit adding skip: isSafari to those three tests. No production change. **Problem** On iOS 27, long-press-dragging the selection caret in a Web TextField dismisses the keyboard mid-gesture. WebKit transiently blurs the hidden input with a null relatedTarget while the document keeps focus, then refocuses it a frame later,and the engine reacted to that blink on two listeners that each tore the input down. A plain input ignores the same blur, so the cause is Flutter's reaction, not a WebKit limitation. **Fix** On iOS both listeners now defer their teardown by 100ms and cancel it if the input refocuses, mirroring the existing #155265 deferred close. Done and tap-away never refocus so they still close, and the deferral is narrowed to the exact drag signature so every other focus transition is unaffected. **Demo** Before: https://flutter-demo-52-before.web.app/ (keyboard dismisses mid caret drag) After: https://flutter-demo-52-after.web.app/ (keyboard stays up) Repro on iOS 27 Safari: tap the field to raise the keyboard, then long-press and drag the selection caret. Before dismisses; after stays up. Done and tap-away still dismiss.
1 parent 94306f7 commit 634b0ed

4 files changed

Lines changed: 402 additions & 2 deletions

File tree

‎engine/src/flutter/lib/web_ui/lib/src/engine/platform_dispatcher/view_focus_binding.dart‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,12 @@ import 'dart:js_interop';
88
import 'package:ui/src/engine.dart';
99
import 'package:ui/ui.dart' as ui;
1010

11+
/// Overrides `domDocument.hasFocus()` in [ViewFocusBinding] for tests, so the
12+
/// iOS caret-drag deferral tests do not depend on the headless browser
13+
/// reporting the test document as focused. Mirrors
14+
/// `DefaultTextEditingStrategy.debugDocumentHasFocusOverride`.
15+
bool? debugViewFocusDocumentHasFocusOverride;
16+
1117
/// Tracks the [FlutterView]s focus changes.
1218
final class ViewFocusBinding {
1319
ViewFocusBinding(this._viewManager, this._onViewFocusChange);
@@ -20,6 +26,21 @@ final class ViewFocusBinding {
2026

2127
StreamSubscription<int>? _onViewCreatedListener;
2228

29+
/// A deferred report of a `focusout` that named no element to gain focus.
30+
///
31+
/// A native iOS caret/selection drag transiently blurs the focused input to
32+
/// <body> and WebKit refocuses it a frame later. Deferring the report lets
33+
/// that refocus cancel it, so the view is not briefly reported unfocused.
34+
/// See: https://github.com/flutter/flutter/issues/189744
35+
Timer? _pendingFocusoutTimer;
36+
37+
/// Whether the document itself still has focus.
38+
///
39+
/// Reads [debugViewFocusDocumentHasFocusOverride] when set, so tests do not
40+
/// depend on the headless browser reporting the test document as focused.
41+
/// Mirrors `DefaultTextEditingStrategy._documentHasFocus`.
42+
bool get _documentHasFocus => debugViewFocusDocumentHasFocusOverride ?? domDocument.hasFocus();
43+
2344
void init() {
2445
// We need a global listener here to know if the user was pressing "shift"
2546
// when the Flutter view receives focus, to move the Flutter focus to the
@@ -36,6 +57,7 @@ final class ViewFocusBinding {
3657
domDocument.body?.removeEventListener(_keyDown, _handleKeyDown);
3758
domDocument.body?.removeEventListener(_keyUp, _handleKeyUp);
3859
_onViewCreatedListener?.cancel();
60+
_pendingFocusoutTimer?.cancel();
3961
}
4062

4163
void changeViewFocus(int viewId, ui.ViewFocusState state) {
@@ -54,6 +76,9 @@ final class ViewFocusBinding {
5476

5577
late final DomEventListener _handleFocusin = createDomEventListener((DomEvent event) {
5678
event as DomFocusEvent;
79+
// Focus returned, so a deferred `focusout` was a transient blur; drop it.
80+
_pendingFocusoutTimer?.cancel();
81+
_pendingFocusoutTimer = null;
5782
_handleFocusChange(event.target as DomElement?);
5883
});
5984

@@ -70,7 +95,31 @@ final class ViewFocusBinding {
7095
}
7196

7297
event as DomFocusEvent;
73-
_handleFocusChange(event.relatedTarget as DomElement?);
98+
final willGainFocus = event.relatedTarget as DomElement?;
99+
final target = event.target as DomElement?;
100+
101+
// On iOS, a native caret/selection drag transiently blurs Flutter's active
102+
// text-editing element to <body> (relatedTarget == null) while the document
103+
// still has focus, and WebKit refocuses it a frame later. Reporting the view
104+
// unfocused on that blink tears the text connection down and drops the
105+
// keyboard. Defer only that precise case, re-deriving from the live focus so
106+
// an immediate refocus is a no-op ([_handleFocusin] cancels the timer).
107+
// Anything else, a non-editing element, a genuine focus loss, or the page
108+
// itself losing focus, reports immediately.
109+
// https://github.com/flutter/flutter/issues/189744
110+
if (isIosSafari &&
111+
willGainFocus == null &&
112+
_documentHasFocus &&
113+
textEditing.isActiveTextEditingElement(target)) {
114+
_pendingFocusoutTimer?.cancel();
115+
_pendingFocusoutTimer = Timer(kTransientBlurSettleDelay, () {
116+
_pendingFocusoutTimer = null;
117+
_handleFocusChange(domDocument.activeElement);
118+
});
119+
return;
120+
}
121+
122+
_handleFocusChange(willGainFocus);
74123
});
75124

76125
late final DomEventListener _handleKeyDown = createDomEventListener((DomEvent event) {

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

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import 'package:meta/meta.dart';
1212
import 'package:ui/ui.dart' as ui;
1313
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
1414

15+
import '../browser_detection.dart' show isIosSafari;
1516
import '../configuration.dart';
1617
import '../dom.dart';
1718
import '../mouse/prevent_default.dart';
@@ -50,6 +51,18 @@ bool browserHasAutofillOverlay() =>
5051
/// transparent.
5152
const String transparentTextEditingClass = 'transparentTextEditing';
5253

54+
/// How long to wait before treating a blur that named no incoming element as a
55+
/// real focus loss.
56+
///
57+
/// Several browser behaviors blur transiently and restore focus a moment later:
58+
/// backgrounding a tab fires blur before `visibilitychange`, and on iOS a
59+
/// native caret or selection drag blurs the input mid-gesture before WebKit
60+
/// refocuses it. Waiting this long lets those settle before the engine acts.
61+
///
62+
/// Shared by [DefaultTextEditingStrategy.handleBlur] and [ViewFocusBinding],
63+
/// which defer the same gesture and must not disagree about the window.
64+
const Duration kTransientBlurSettleDelay = Duration(milliseconds: 100);
65+
5366
void _emptyCallback(dynamic _) {}
5467

5568
/// These style attributes are constant throughout the life time of an input
@@ -1864,7 +1877,7 @@ abstract class DefaultTextEditingStrategy
18641877
// When a browser tab is backgrounded, the input blur arrives before
18651878
// visibilitychange. Wait briefly so tab switches can keep the text
18661879
// connection alive, while ordinary window/iframe blurs still close it.
1867-
_pendingBlurConnectionCloseTimer = Timer(const Duration(milliseconds: 100), () {
1880+
_pendingBlurConnectionCloseTimer = Timer(kTransientBlurSettleDelay, () {
18681881
_pendingBlurConnectionCloseTimer = null;
18691882
if (_documentVisibilityState == 'hidden' || _documentHasFocus) {
18701883
return;
@@ -1873,6 +1886,32 @@ abstract class DefaultTextEditingStrategy
18731886
});
18741887
return;
18751888
}
1889+
// On iOS WebKit, a native caret or selection drag transiently blurs the
1890+
// hidden input mid-gesture with `relatedTarget == null` while the document
1891+
// still has focus, and WebKit refocuses the input a frame later. Closing
1892+
// the connection on that blink drops the keyboard; a plain <input> keeps
1893+
// it. Defer the close and skip it if the input has regained focus by the
1894+
// time the timer fires. A genuine blur, the Done button or tapping away,
1895+
// does not refocus, so it still closes. [ViewFocusBinding] defers the
1896+
// matching `focusout` the same way.
1897+
// https://github.com/flutter/flutter/issues/189744
1898+
if (isIosSafari) {
1899+
_pendingBlurConnectionCloseTimer?.cancel();
1900+
_pendingBlurConnectionCloseTimer = Timer(kTransientBlurSettleDelay, () {
1901+
_pendingBlurConnectionCloseTimer = null;
1902+
if (domDocument.activeElement == activeDomElement) {
1903+
// The input refocused: this was the transient mid-gesture blur.
1904+
return;
1905+
}
1906+
if (_documentVisibilityState == 'hidden') {
1907+
// The page was backgrounded (e.g. a tab switch) after the blur was
1908+
// scheduled; keep the connection alive, matching the branch above.
1909+
return;
1910+
}
1911+
textEditing.sendTextConnectionClosedToFrameworkIfAny();
1912+
});
1913+
return;
1914+
}
18761915
textEditing.sendTextConnectionClosedToFrameworkIfAny();
18771916
} else if (_viewForElement(willGainFocusElement) == activeDomElementView) {
18781917
// If the focus stays within the same FlutterView, ensure the focus stays
@@ -2756,6 +2795,16 @@ class HybridTextEditing {
27562795
/// Also used to define if a keyboard is needed.
27572796
bool isEditing = false;
27582797

2798+
/// Whether [element] is the DOM element currently receiving text input.
2799+
///
2800+
/// [ViewFocusBinding] uses this to recognize a `focusout` that originated
2801+
/// from the active text-editing element.
2802+
///
2803+
/// Prefer this over matching on [textEditingClass]. That class is
2804+
/// not guaranteed to be applied by all strategies.
2805+
bool isActiveTextEditingElement(DomElement? element) =>
2806+
isEditing && element != null && element == strategy.domElement;
2807+
27592808
InputConfiguration? configuration;
27602809

27612810
DefaultTextEditingStrategy? debugTextEditingStrategyOverride;

‎engine/src/flutter/lib/web_ui/test/engine/platform_dispatcher/view_focus_binding_test.dart‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ void testMain() {
2424

2525
tearDown(() {
2626
EngineSemantics.instance.semanticsEnabled = false;
27+
endFakeTextEditing();
28+
debugEmulateIosSafari = false;
29+
debugViewFocusDocumentHasFocusOverride = null;
2730
});
2831

2932
test('The view is focusable and reachable by keyboard when registered', () async {
@@ -352,9 +355,152 @@ void testMain() {
352355
expect(dispatchedViewFocusEvents[0].state, ui.ViewFocusState.focused);
353356
expect(dispatchedViewFocusEvents[0].direction, ui.ViewFocusDirection.undefined);
354357
});
358+
359+
// On iOS a native caret/selection drag transiently blurs Flutter's active
360+
// text-editing element to <body> (relatedTarget == null) while the document
361+
// still has focus, and WebKit refocuses it a frame later. The view-unfocused
362+
// report is deferred so that refocus cancels it.
363+
// Regression test for https://github.com/flutter/flutter/issues/189744
364+
test('drops the deferred view-unfocused report when the editing input '
365+
'refocuses on iOS', () async {
366+
final EngineFlutterView view = createAndRegisterView(dispatcher);
367+
final DomHTMLInputElement input = createDomHTMLInputElement();
368+
view.dom.rootElement.append(input);
369+
input.focusWithoutScroll();
370+
beginFakeTextEditing(input);
371+
dispatchedViewFocusEvents.clear();
372+
373+
debugEmulateIosSafari = true;
374+
debugViewFocusDocumentHasFocusOverride = true;
375+
// The null-relatedTarget focusout schedules the deferred report; the
376+
// immediate refocus, as WebKit does mid-drag, cancels it.
377+
input.blur();
378+
input.focusWithoutScroll();
379+
await Future<void>.delayed(const Duration(milliseconds: 150));
380+
expect(dispatchedViewFocusEvents, isEmpty);
381+
});
382+
383+
// A genuine blur (Done button, tap-away) never refocuses, so the deferred
384+
// report must still fire, carrying the right view and direction.
385+
test('reports the view unfocused on iOS when the editing input does not '
386+
'refocus', () async {
387+
final EngineFlutterView view = createAndRegisterView(dispatcher);
388+
final DomHTMLInputElement input = createDomHTMLInputElement();
389+
view.dom.rootElement.append(input);
390+
input.focusWithoutScroll();
391+
beginFakeTextEditing(input);
392+
dispatchedViewFocusEvents.clear();
393+
394+
debugEmulateIosSafari = true;
395+
debugViewFocusDocumentHasFocusOverride = true;
396+
input.blur();
397+
await Future<void>.delayed(const Duration(milliseconds: 150));
398+
final Iterable<ui.ViewFocusEvent> unfocused = dispatchedViewFocusEvents.where(
399+
(ui.ViewFocusEvent e) => e.state == ui.ViewFocusState.unfocused,
400+
);
401+
expect(unfocused, hasLength(1));
402+
expect(unfocused.single.viewId, view.viewId);
403+
expect(unfocused.single.direction, ui.ViewFocusDirection.undefined);
404+
});
405+
406+
// The deferral is scoped to Flutter's text-editing element. A null-target
407+
// focusout from any other element must report immediately, so a later
408+
// refocus cannot erase a real focus loss.
409+
test('reports immediately for a non-text-editing element on iOS', () {
410+
final EngineFlutterView view = createAndRegisterView(dispatcher);
411+
final DomElement other = createDomElement('input');
412+
view.dom.rootElement.append(other);
413+
other.focusWithoutScroll();
414+
dispatchedViewFocusEvents.clear();
415+
416+
debugEmulateIosSafari = true;
417+
// Report the document as focused so the only condition failing is that
418+
// `other` is not the active editing element. Without this the test could
419+
// pass because the headless browser reported the document unfocused,
420+
// which is a different branch than the one under test.
421+
debugViewFocusDocumentHasFocusOverride = true;
422+
other.blur();
423+
// Not deferred: the unfocused event is present synchronously.
424+
expect(
425+
dispatchedViewFocusEvents.where(
426+
(ui.ViewFocusEvent e) => e.state == ui.ViewFocusState.unfocused,
427+
),
428+
hasLength(1),
429+
);
430+
});
431+
432+
// The deferral requires the document to still have focus. When focus has
433+
// left the document, such as a window, iframe, or app switch, the
434+
// null-target focusout from the editing element must report immediately so
435+
// the framework is not left believing the view is still focused.
436+
// Regression test for https://github.com/flutter/flutter/issues/189744
437+
test('reports immediately when the document is not focused on iOS', () {
438+
final EngineFlutterView view = createAndRegisterView(dispatcher);
439+
final DomHTMLInputElement input = createDomHTMLInputElement();
440+
view.dom.rootElement.append(input);
441+
input.focusWithoutScroll();
442+
beginFakeTextEditing(input);
443+
dispatchedViewFocusEvents.clear();
444+
445+
debugEmulateIosSafari = true;
446+
debugViewFocusDocumentHasFocusOverride = false;
447+
input.blur();
448+
// Not deferred: with the document unfocused the unfocused event is
449+
// present synchronously.
450+
expect(
451+
dispatchedViewFocusEvents.where(
452+
(ui.ViewFocusEvent e) => e.state == ui.ViewFocusState.unfocused,
453+
),
454+
hasLength(1),
455+
);
456+
});
457+
458+
// The deferral must key off the engine's editing state, not the
459+
// `flt-text-editing` class, which is not guaranteed to be applied by all
460+
// text editing strategies. Matching on the class would leave the deferral
461+
// dead for strategies that do not apply it.
462+
// Regression test for https://github.com/flutter/flutter/issues/189744
463+
test('defers on iOS for an editing element with no flt-text-editing class', () async {
464+
final EngineFlutterView view = createAndRegisterView(dispatcher);
465+
final DomHTMLInputElement input = createDomHTMLInputElement();
466+
view.dom.rootElement.append(input);
467+
input.focusWithoutScroll();
468+
beginFakeTextEditing(input);
469+
expect(
470+
input.classList.contains(HybridTextEditing.textEditingClass),
471+
isFalse,
472+
reason: 'the semantics path never applies this class',
473+
);
474+
dispatchedViewFocusEvents.clear();
475+
476+
debugEmulateIosSafari = true;
477+
debugViewFocusDocumentHasFocusOverride = true;
478+
input.blur();
479+
input.focusWithoutScroll();
480+
await Future<void>.delayed(const Duration(milliseconds: 150));
481+
expect(dispatchedViewFocusEvents, isEmpty);
482+
});
355483
});
356484
}
357485

486+
/// Makes [element] the engine's active text-editing element, which is what
487+
/// [HybridTextEditing.isActiveTextEditingElement] reports to [ViewFocusBinding].
488+
///
489+
/// Sets the real singleton state rather than applying
490+
/// [HybridTextEditing.textEditingClass], so these tests exercise the same signal
491+
/// production code reads. The class is not guaranteed to be applied by all text
492+
/// editing strategies, so keying tests off it would not reflect the production
493+
/// code.
494+
void beginFakeTextEditing(DomHTMLElement element) {
495+
textEditing.isEditing = true;
496+
textEditing.strategy.domElement = element;
497+
}
498+
499+
void endFakeTextEditing() {
500+
textEditing.isEditing = false;
501+
textEditing.strategy.domElement = null;
502+
}
503+
358504
EngineFlutterView createAndRegisterView(EnginePlatformDispatcher dispatcher) {
359505
final DomElement div = createDomElement('div');
360506
final view = EngineFlutterView(dispatcher, div);

0 commit comments

Comments
 (0)