Skip to content

Commit a3bcce1

Browse files
authored
[web] Keep semantics editing state while the text input connection is open (flutter#195141)
Fixes flutter#194636 ## Problem On web with semantics enabled, a focused `TextField` loses its text when its semantics node leaves the tree and comes back, for example after scrolling it out of a `ListView` and back. The framework keeps the connection open, but `SemanticsTextEditingStrategy.deactivate()` called `disable()`, which cleared connection state when the DOM `<input>` was disposed. The re-created element came back empty and unstyled, and its first `selectionchange` sent `""` to the framework as an edit. ## Fix `SemanticsTextEditingStrategy` now keeps the element lifecycle separate from the connection lifecycle. `deactivate()` only detaches the `<input>` through a new `_detachElement()`, and `disable()` detaches and then clears the connection state, which is the editing state, queued style, config and callbacks. A re-created element therefore gets its text and style back from `activate()`. `activate()` also returns early when no connection is open, so a field that stays focused after `TextInput.hide` is not attached with a null config. ## Demo Before: https://flutter-demo-07-before.web.app After: https://flutter-demo-07-after.web.app In desktop Chrome, click the text field, which holds `hello`, and optionally type ` world`. Scroll the list down with the mouse wheel until the field is off-screen, then scroll back up. Before: the field is empty and the bottom bar reads `controller.text = ""`. After: the field still shows the text and the bottom bar matches.
1 parent 8a72c88 commit a3bcce1

2 files changed

Lines changed: 211 additions & 13 deletions

File tree

‎engine/src/flutter/lib/web_ui/lib/src/engine/semantics/text_field.dart‎

Lines changed: 33 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -108,44 +108,66 @@ class SemanticsTextEditingStrategy extends DefaultTextEditingStrategy {
108108
/// Attaches the DOM element owned by [textField] to the text editing
109109
/// strategy.
110110
///
111-
/// This method must be called after [enable] to name sure that [inputConfig],
112-
/// [onChange], and [onAction] are not null.
111+
/// Does nothing while no text input connection is open, that is before
112+
/// [enable] or after [disable]. A field can stay focused in the semantics
113+
/// tree after the framework closes its connection, for example after
114+
/// `TextInput.hide`, and [SemanticTextField.update] calls this on every
115+
/// semantics update while the field has focus.
113116
void activate(SemanticTextField textField) {
114-
assert(
115-
inputConfig != null && onChange != null && onAction != null,
116-
'"enable" should be called before "enableFromSemantics" and initialize input configuration',
117-
);
117+
final InputConfiguration? inputConfig = this.inputConfig;
118+
final OnChangeCallback? onChange = this.onChange;
119+
final OnActionCallback? onAction = this.onAction;
120+
if (inputConfig == null || onChange == null || onAction == null) {
121+
return;
122+
}
118123

119124
if (activeTextField == textField) {
120125
// The specified field is already active. Skip.
121126
return;
122127
} else if (activeTextField != null) {
123-
// Another text field is currently active. Deactivate it before switching.
124-
disable();
128+
// Another text field is currently active. Detach it before switching.
129+
deactivate(activeTextField!);
125130
}
126131

127132
activeTextField = textField;
128133
domElement = textField.editableElement;
129134
// Enable before syncing the style.
130135
// [DefaultTextEditingStrategy.updateElementStyle] only writes to the element
131136
// once editing is enabled, so syncing first drops the style silently.
132-
super.enable(inputConfig!, onChange: onChange!, onAction: onAction!);
137+
super.enable(inputConfig, onChange: onChange, onAction: onAction);
133138
_syncStyle();
134139
}
135140

136141
/// Detaches the DOM element owned by [textField] from this text editing
137142
/// strategy.
138143
///
139144
/// Typically at this point the element loses focus (blurs) and stops being
140-
/// used for editing.
145+
/// used for editing. This only ends the element's part in editing. The text
146+
/// input connection, and the state it owns such as the editing state and the
147+
/// style, stays until [disable], so a replacement element for the same field
148+
/// is restored by [activate]. The framework does not resend that state while
149+
/// its connection is open, for example when the focused field's semantics
150+
/// node leaves the tree for one update and comes back with a new element.
151+
/// See https://github.com/flutter/flutter/issues/194636.
141152
void deactivate(SemanticTextField textField) {
142153
if (activeTextField == textField) {
143-
disable();
154+
_detachElement();
144155
}
145156
}
146157

158+
/// Ends the text input connection, detaching the active element if any and
159+
/// dropping the state the connection owns.
147160
@override
148161
void disable() {
162+
_detachElement();
163+
lastEditingState = null;
164+
_queuedStyle = null;
165+
inputConfig = null;
166+
onChange = null;
167+
onAction = null;
168+
}
169+
170+
void _detachElement() {
149171
// We don't want to remove the DOM element because the caller is responsible
150172
// for that. However we still want to stop editing, cleanup the handlers.
151173
if (!isEnabled) {
@@ -160,7 +182,6 @@ class SemanticsTextEditingStrategy extends DefaultTextEditingStrategy {
160182
subscriptions[i].cancel();
161183
}
162184
subscriptions.clear();
163-
lastEditingState = null;
164185

165186
// The focused field is linked to the autofill form by the `form`
166187
// attribute. On blur, detach it and leave a synthetic placeholder holding
@@ -182,7 +203,6 @@ class SemanticsTextEditingStrategy extends DefaultTextEditingStrategy {
182203
EnginePlatformDispatcher.instance.viewManager.safeBlur(activeDomElement);
183204
domElement = null;
184205
activeTextField = null;
185-
_queuedStyle = null;
186206
}
187207

188208
@override

‎engine/src/flutter/lib/web_ui/test/engine/semantics/text_field_test.dart‎

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -520,6 +520,184 @@ void testMain() {
520520
}
521521
});
522522

523+
test('Restores the editing state into a re-created field while the connection is open', () {
524+
// Open the connection the way the framework does, so `isEditing` is true
525+
// while the semantics node leaves the tree and comes back.
526+
testTextEditing.acceptCommand(
527+
TextInputSetClient(clientId: 123, configuration: singlelineConfig),
528+
() {},
529+
);
530+
testTextEditing.acceptCommand(const TextInputShow(), () {});
531+
testTextEditing.acceptCommand(
532+
TextInputSetEditingState(
533+
state: EditingState(text: 'hello world', baseOffset: 11, extentOffset: 11),
534+
),
535+
() {},
536+
);
537+
538+
void applyTree(SemanticsTester tester, {required bool withTextField}) {
539+
tester.updateNode(
540+
id: 0,
541+
children: <SemanticsNodeUpdate>[
542+
if (withTextField)
543+
tester.updateNode(
544+
id: 1,
545+
flags: const ui.SemanticsFlags(
546+
isEnabled: ui.Tristate.isTrue,
547+
isTextField: true,
548+
isFocused: ui.Tristate.isTrue,
549+
),
550+
value: 'hello world',
551+
textSelectionBase: 11,
552+
textSelectionExtent: 11,
553+
rect: const ui.Rect.fromLTRB(0, 0, 50, 10),
554+
),
555+
],
556+
);
557+
tester.apply();
558+
}
559+
560+
final spy = PlatformMessagesSpy()..setUp();
561+
try {
562+
final tester = SemanticsTester(owner());
563+
applyTree(tester, withTextField: true);
564+
final firstInput = tester.getTextField(1).editableElement as DomHTMLInputElement;
565+
expect(strategy.domElement, firstInput);
566+
expect(firstInput.value, 'hello world');
567+
568+
// The focused field scrolls out of view: its node is removed and the
569+
// element is disposed, but the framework never closes the connection.
570+
applyTree(tester, withTextField: false);
571+
expect(strategy.isEnabled, isFalse);
572+
expect(testTextEditing.isEditing, isTrue);
573+
574+
// The node comes back under the same id with a brand new element.
575+
applyTree(tester, withTextField: true);
576+
final secondInput = tester.getTextField(1).editableElement as DomHTMLInputElement;
577+
expect(secondInput, isNot(same(firstInput)));
578+
expect(strategy.domElement, secondInput);
579+
expect(secondInput.value, 'hello world');
580+
expect(secondInput.selectionStart, 11);
581+
expect(secondInput.selectionEnd, 11);
582+
583+
// The browser reports a selection change for the newly focused element.
584+
// The restored state matches the element, so nothing is sent back to
585+
// the framework as an edit.
586+
domDocument.dispatchEvent(createDomEvent('Event', 'selectionchange'));
587+
final Iterable<PlatformMessage> updates = spy.messages.where(
588+
(m) =>
589+
m.channel == 'flutter/textinput' &&
590+
m.methodName == 'TextInputClient.updateEditingState',
591+
);
592+
expect(updates, isEmpty);
593+
} finally {
594+
spy.tearDown();
595+
testTextEditing.acceptCommand(const TextInputClearClient(), () {});
596+
}
597+
});
598+
599+
test('Drops the editing state when the framework closes the connection', () {
600+
testTextEditing.acceptCommand(
601+
TextInputSetClient(clientId: 123, configuration: singlelineConfig),
602+
() {},
603+
);
604+
testTextEditing.acceptCommand(const TextInputShow(), () {});
605+
testTextEditing.acceptCommand(
606+
TextInputSetEditingState(
607+
state: EditingState(text: 'hello world', baseOffset: 11, extentOffset: 11),
608+
),
609+
() {},
610+
);
611+
createTextFieldSemantics(value: 'hello world', isFocused: true);
612+
expect(strategy.lastEditingState, isNotNull);
613+
614+
testTextEditing.acceptCommand(const TextInputClearClient(), () {});
615+
expect(testTextEditing.isEditing, isFalse);
616+
expect(strategy.lastEditingState, isNull);
617+
});
618+
619+
test('Restores the style into a re-created field while the connection is open', () {
620+
testTextEditing.acceptCommand(
621+
TextInputSetClient(clientId: 123, configuration: singlelineConfig),
622+
() {},
623+
);
624+
// The framework sends the style once, when it opens the connection, and
625+
// only again if the style changes.
626+
testTextEditing.acceptCommand(
627+
TextInputSetStyle(
628+
style: EditableTextStyle(
629+
textDirection: ui.TextDirection.ltr,
630+
fontSize: 24,
631+
textAlign: ui.TextAlign.left,
632+
fontFamily: 'Arial',
633+
fontWeight: 'normal',
634+
letterSpacing: null,
635+
wordSpacing: null,
636+
lineHeight: null,
637+
),
638+
),
639+
() {},
640+
);
641+
testTextEditing.acceptCommand(const TextInputShow(), () {});
642+
643+
void applyTree(SemanticsTester tester, {required bool withTextField}) {
644+
tester.updateNode(
645+
id: 0,
646+
children: <SemanticsNodeUpdate>[
647+
if (withTextField)
648+
tester.updateNode(
649+
id: 1,
650+
flags: const ui.SemanticsFlags(
651+
isEnabled: ui.Tristate.isTrue,
652+
isTextField: true,
653+
isFocused: ui.Tristate.isTrue,
654+
),
655+
value: 'hello',
656+
rect: const ui.Rect.fromLTRB(0, 0, 50, 10),
657+
),
658+
],
659+
);
660+
tester.apply();
661+
}
662+
663+
try {
664+
final tester = SemanticsTester(owner());
665+
applyTree(tester, withTextField: true);
666+
final DomHTMLElement firstInput = tester.getTextField(1).editableElement;
667+
expect(firstInput.style.fontSize, '24px');
668+
669+
applyTree(tester, withTextField: false);
670+
applyTree(tester, withTextField: true);
671+
final DomHTMLElement secondInput = tester.getTextField(1).editableElement;
672+
expect(secondInput, isNot(same(firstInput)));
673+
expect(secondInput.style.fontSize, '24px');
674+
expect(secondInput.style.fontFamily, contains('Arial'));
675+
} finally {
676+
testTextEditing.acceptCommand(const TextInputClearClient(), () {});
677+
}
678+
});
679+
680+
test('Does not attach a focused field after the connection is closed', () {
681+
testTextEditing.acceptCommand(
682+
TextInputSetClient(clientId: 123, configuration: singlelineConfig),
683+
() {},
684+
);
685+
testTextEditing.acceptCommand(const TextInputShow(), () {});
686+
createTextFieldSemantics(value: 'hello', isFocused: true);
687+
expect(strategy.domElement, isNotNull);
688+
689+
// An app can hide the keyboard while the field keeps focus. The engine
690+
// closes the connection, but the field is still focused in the semantics
691+
// tree, so the next semantics update calls `activate` again.
692+
testTextEditing.acceptCommand(const TextInputHide(), () {});
693+
expect(testTextEditing.isEditing, isFalse);
694+
expect(strategy.domElement, isNull);
695+
696+
expect(() => createTextFieldSemantics(value: 'hello', isFocused: true), returnsNormally);
697+
expect(strategy.domElement, isNull);
698+
expect(strategy.isEnabled, isFalse);
699+
});
700+
523701
test('renders a required text field', () {
524702
createTextFieldSemantics(isRequired: true, value: 'hello');
525703
expectSemanticsTree(owner(), '''<sem><input aria-required="true" /></sem>''');

0 commit comments

Comments
 (0)