[web] Save the autofill information (flutter/engine#20256)

* changes for autofill. Commit save=false works. added submit button. set form actions

* save the forms on the dom

* fix tests. fix input element location. fix single element forms

* fix failing ios test. add more unit test methods for submitting the form

* address reviewer comments

* remove only the forms from the map

* remove debug line

* fix issues with login info saving. format file

* fix textarea id. fix unit tests methods

* remove debug line

* fixes flickering in safari. remove an unnecessary secind append in firefox

* address reviewer comments

* address reviewer comments
This commit is contained in:
nturgut
2020-08-07 13:28:50 -07:00
committed by GitHub
parent fbefaefe5b
commit 4425a3b157
3 changed files with 479 additions and 56 deletions

View File

@@ -6,7 +6,7 @@
part of engine;
/// Make the content editable span visible to facilitate debugging.
const bool _debugVisibleTextEditing = false;
bool _debugVisibleTextEditing = false;
/// The `keyCode` of the "Enter" key.
const int _kReturnKeyCode = 13;
@@ -55,7 +55,8 @@ void _setStaticStyleAttributes(html.HtmlElement domElement) {
/// element.
///
/// They are assigned once during the creation of the DOM element.
void _hideAutofillElements(html.HtmlElement domElement) {
void _hideAutofillElements(html.HtmlElement domElement,
{bool isOffScreen = false}) {
final html.CssStyleDeclaration elementStyle = domElement.style;
elementStyle
..whiteSpace = 'pre-wrap'
@@ -73,6 +74,12 @@ void _hideAutofillElements(html.HtmlElement domElement) {
..textShadow = 'transparent'
..transformOrigin = '0 0 0';
if (isOffScreen) {
elementStyle
..top = '-9999px'
..left = '-9999px';
}
/// This property makes the input's blinking cursor transparent.
elementStyle.setProperty('caret-color', 'transparent');
}
@@ -82,14 +89,27 @@ void _hideAutofillElements(html.HtmlElement domElement) {
/// These values are to be used when autofill is enabled and there is a group of
/// text fields with more than one text field.
class EngineAutofillForm {
EngineAutofillForm({this.formElement, this.elements, this.items});
EngineAutofillForm(
{required this.formElement,
this.elements,
this.items,
this.formIdentifier = ''});
final html.FormElement? formElement;
final html.FormElement formElement;
final Map<String, html.HtmlElement>? elements;
final Map<String, AutofillInfo>? items;
/// Identifier for the form.
///
/// It is constructed by concatenating unique ids of input elements on the
/// form.
///
/// It is used for storing the form until submission.
/// See [formsOnTheDom].
final String formIdentifier;
static EngineAutofillForm? fromFrameworkMessage(
Map<String, dynamic>? focusedElementAutofill,
List<dynamic>? fields,
@@ -109,9 +129,22 @@ class EngineAutofillForm {
// Validation is in the framework side.
formElement.noValidate = true;
formElement.method = 'post';
formElement.action = '#';
formElement.addEventListener('submit', (e) {
e.preventDefault();
});
_hideAutofillElements(formElement);
// We keep the ids in a list then sort them later, in case the text fields'
// locations are re-ordered on the framework side.
final List<String> ids = List.empty(growable: true);
// The focused text editing element will not be created here.
final AutofillInfo focusedElement =
AutofillInfo.fromFrameworkMessage(focusedElementAutofill);
if (fields != null) {
for (Map<String, dynamic> field in fields.cast<Map<String, dynamic>>()) {
final Map<String, dynamic> autofillInfo = field['autofill'];
@@ -120,9 +153,8 @@ class EngineAutofillForm {
textCapitalization: TextCapitalizationConfig.fromInputConfiguration(
field['textCapitalization']));
// The focused text editing element will not be created here.
final AutofillInfo focusedElement =
AutofillInfo.fromFrameworkMessage(focusedElementAutofill);
ids.add(autofill.uniqueIdentifier);
if (autofill.uniqueIdentifier != focusedElement.uniqueIdentifier) {
EngineInputType engineInputType =
EngineInputType.fromName(field['inputType']['name']);
@@ -137,22 +169,57 @@ class EngineAutofillForm {
formElement.append(htmlElement);
}
}
} else {
// There is one input element in the form.
ids.add(focusedElement.uniqueIdentifier);
}
ids.sort();
final StringBuffer idBuffer = StringBuffer();
// Add a seperator between element identifiers.
for (final String id in ids) {
if (idBuffer.length > 0) {
idBuffer.write('*');
}
idBuffer.write(id);
}
final String formIdentifier = idBuffer.toString();
// If a form with the same Autofill elements is already on the dom, remove
// it from DOM.
if (formsOnTheDom[formIdentifier] != null) {
final html.FormElement form =
formsOnTheDom[formIdentifier] as html.FormElement;
form.remove();
}
// In order to submit the form when Framework sends a `TextInput.commit`
// message, we add a submit button to the form.
final html.InputElement submitButton = html.InputElement();
_hideAutofillElements(submitButton, isOffScreen: true);
submitButton.className = 'submitBtn';
submitButton.type = 'submit';
formElement.append(submitButton);
return EngineAutofillForm(
formElement: formElement,
elements: elements,
items: items,
formIdentifier: formIdentifier,
);
}
void placeForm(html.HtmlElement mainTextEditingElement) {
formElement!.append(mainTextEditingElement);
domRenderer.glassPaneElement!.append(formElement!);
formElement.append(mainTextEditingElement);
domRenderer.glassPaneElement!.append(formElement);
}
void removeForm() {
formElement!.remove();
void storeForm() {
formsOnTheDom[formIdentifier] = this.formElement;
_hideAutofillElements(formElement, isOffScreen: true);
}
/// Listens to `onInput` event on the form fields.
@@ -226,9 +293,11 @@ class AutofillInfo {
/// The current text and selection state of a text field.
final EditingState editingState;
/// Unique value set by the developer.
/// Unique value set by the developer or generated by the framework.
///
/// Used as id of the text field.
///
/// An example an id generated by the framework: `EditableText-285283643`.
final String uniqueIdentifier;
/// Information on how should autofilled text capitalized.
@@ -272,20 +341,17 @@ class AutofillInfo {
if (domElement is html.InputElement) {
html.InputElement element = domElement;
element.name = hint;
element.id = uniqueIdentifier;
element.id = hint;
element.autocomplete = hint;
// Do not change the element type for the focused element.
if (focusedElement == false) {
if (hint.contains('password')) {
element.type = 'password';
} else {
element.type = 'text';
}
if (hint.contains('password')) {
element.type = 'password';
} else {
element.type = 'text';
}
} else if (domElement is html.TextAreaElement) {
html.TextAreaElement element = domElement;
element.name = hint;
element.id = uniqueIdentifier;
element.id = hint;
element.setAttribute('autocomplete', hint);
}
}
@@ -543,7 +609,7 @@ class GloballyPositionedTextEditingStrategy extends DefaultTextEditingStrategy {
_geometry?.applyToDomElement(focusedFormElement!);
placeForm();
// On Chrome, when a form is focused, it opens an autofill menu
// immeddiately.
// immediately.
// Flutter framework sends `setEditableSizeAndTransform` for informing
// the engine about the location of the text field. This call will
// arrive after `show` call.
@@ -558,6 +624,53 @@ class GloballyPositionedTextEditingStrategy extends DefaultTextEditingStrategy {
}
}
/// A [TextEditingStrategy] for Safari Desktop Browser.
///
/// It places its [domElement] assuming no prior transform or sizing is applied
/// to it.
///
/// In case of an autofill enabled form, it does not append the form element
/// to the DOM, until the geometry information is updated.
///
/// This implementation is used by text editables when semantics is not
/// enabled. With semantics enabled the placement is provided by the semantics
/// tree.
class SafariDesktopTextEditingStrategy extends DefaultTextEditingStrategy {
SafariDesktopTextEditingStrategy(HybridTextEditing owner) : super(owner);
/// Appending an element on the DOM for Safari Desktop Browser.
///
/// This method is only called when geometry information is updated by
/// 'TextInput.setEditableSizeAndTransform' message.
///
/// This method is similar to the [GloballyPositionedTextEditingStrategy].
/// The only part different: this method does not call `super.placeElement()`,
/// which in current state calls `domElement.focus()`.
///
/// Making an extra `focus` request causes flickering in Safari.
@override
void placeElement() {
_geometry?.applyToDomElement(domElement);
if (hasAutofillGroup) {
placeForm();
// On Safari Desktop, when a form is focused, it opens an autofill menu
// immediately.
// Flutter framework sends `setEditableSizeAndTransform` for informing
// the engine about the location of the text field. This call will
// arrive after `show` call. Therefore form is placed, when
// `setEditableSizeAndTransform` method is called and focus called on the
// form only after placing it to the correct position and only once after
// that. Calling focus multiple times causes flickering.
focusedFormElement!.focus();
}
}
@override
void initializeElementPlacement() {
domElement.focus();
}
}
/// Class implementing the default editing strategies for text editing.
///
/// This class uses a DOM element to provide text editing capabilities.
@@ -611,6 +724,10 @@ abstract class DefaultTextEditingStrategy implements TextEditingStrategy {
bool get hasAutofillGroup => _inputConfiguration.autofillGroup != null;
/// Whether the focused input element is part of a form.
bool get appendedToForm => _appendedToForm;
bool _appendedToForm = false;
html.FormElement? get focusedFormElement =>
_inputConfiguration.autofillGroup?.formElement;
@@ -636,12 +753,14 @@ abstract class DefaultTextEditingStrategy implements TextEditingStrategy {
_setStaticStyleAttributes(domElement);
_style?.applyToDomElement(domElement);
if (!hasAutofillGroup) {
// If there is an Autofill Group the `FormElement`, it will be appended to the
// DOM later, when the first location information arrived.
// Otherwise, on Blink based Desktop browsers, the autofill menu appears
// on top left of the screen.
domRenderer.glassPaneElement!.append(domElement);
_appendedToForm = false;
}
initializeElementPlacement();
@@ -709,9 +828,19 @@ abstract class DefaultTextEditingStrategy implements TextEditingStrategy {
_subscriptions[i].cancel();
}
_subscriptions.clear();
domElement.remove();
// If focused element is a part of a form, it needs to stay on the DOM
// until the autofill context of the form is finalized.
// More details on `TextInput.finishAutofillContext` call.
if (_appendedToForm &&
_inputConfiguration.autofillGroup?.formElement != null) {
// Subscriptions are removed, listeners won't be triggered.
domElement.blur();
_hideAutofillElements(domElement, isOffScreen: true);
_inputConfiguration.autofillGroup?.storeForm();
} else {
domElement.remove();
}
_domElement = null;
_inputConfiguration.autofillGroup?.removeForm();
}
@mustCallSuper
@@ -730,6 +859,7 @@ abstract class DefaultTextEditingStrategy implements TextEditingStrategy {
void placeForm() {
_inputConfiguration.autofillGroup!.placeForm(domElement);
_appendedToForm = true;
}
void _handleChange(html.Event event) {
@@ -857,8 +987,6 @@ class IOSTextEditingStrategy extends GloballyPositionedTextEditingStrategy {
inputConfig.inputType.configureInputMode(domElement);
if (hasAutofillGroup) {
placeForm();
} else {
domRenderer.glassPaneElement!.append(domElement);
}
inputConfig.textCapitalization.setAutocapitalizeAttribute(domElement);
}
@@ -1045,8 +1173,6 @@ class FirefoxTextEditingStrategy extends GloballyPositionedTextEditingStrategy {
onChange: onChange, onAction: onAction);
if (hasAutofillGroup) {
placeForm();
} else {
domRenderer.glassPaneElement!.append(domElement);
}
}
@@ -1156,8 +1282,14 @@ class TextEditingChannel {
break;
case 'TextInput.finishAutofillContext':
// TODO(nurhan): Handle saving autofill information on web.
// https://github.com/flutter/flutter/issues/59378
final bool saveForm = call.arguments as bool;
// Close the text editing connection. Form is finalizing.
implementation.sendTextConnectionClosedToFrameworkIfAny();
if (saveForm) {
saveForms();
}
// Clean the forms from DOM after submitting them.
cleanForms();
break;
default:
@@ -1167,6 +1299,30 @@ class TextEditingChannel {
window._replyToPlatformMessage(callback, codec.encodeSuccessEnvelope(true));
}
/// Used for submitting the forms attached on the DOM.
///
/// Browser will save the information entered to the form.
///
/// Called when the form is finalized with save option `true`.
/// See: https://github.com/flutter/flutter/blob/bf9f3a3dcfea3022f9cf2dfc3ab10b120b48b19d/packages/flutter/lib/src/services/text_input.dart#L1277
void saveForms() {
formsOnTheDom.forEach((String identifier, html.FormElement form) {
final html.InputElement submitBtn =
form.getElementsByClassName('submitBtn').first as html.InputElement;
submitBtn.click();
});
}
/// Used for removing the forms on the DOM.
///
/// Called when the form is finalized.
void cleanForms() {
for (html.FormElement form in formsOnTheDom.values) {
form.remove();
}
formsOnTheDom.clear();
}
/// Sends the 'TextInputClient.updateEditingState' message to the framework.
void updateEditingState(int? clientId, EditingState? editingState) {
if (window._onPlatformMessage != null) {
@@ -1219,6 +1375,15 @@ class TextEditingChannel {
/// Text editing singleton.
final HybridTextEditing textEditing = HybridTextEditing();
/// Map for storing forms left attached on the DOM.
///
/// Used for keeping the form elements on the DOM until user confirms to
/// save or cancel them.
///
/// See: https://github.com/flutter/flutter/blob/bf9f3a3dcfea3022f9cf2dfc3ab10b120b48b19d/packages/flutter/lib/src/services/text_input.dart#L1277
final Map<String, html.FormElement> formsOnTheDom =
Map<String, html.FormElement>();
/// Should be used as a singleton to provide support for text editing in
/// Flutter Web.
///
@@ -1236,6 +1401,8 @@ class HybridTextEditing {
if (browserEngine == BrowserEngine.webkit &&
operatingSystem == OperatingSystem.iOs) {
this._defaultEditingElement = IOSTextEditingStrategy(this);
} else if (browserEngine == BrowserEngine.webkit) {
this._defaultEditingElement = SafariDesktopTextEditingStrategy(this);
} else if (browserEngine == BrowserEngine.blink &&
operatingSystem == OperatingSystem.android) {
this._defaultEditingElement = AndroidTextEditingStrategy(this);

View File

@@ -123,14 +123,19 @@ class EngineWindow extends ui.Window {
height = html.window.innerHeight! * devicePixelRatio;
width = html.window.innerWidth! * devicePixelRatio;
}
// First confirm both heught and width is effected.
if (_physicalSize!.height != height && _physicalSize!.width != width) {
// If prior to rotation height is bigger than width it should be the
// opposite after the rotation and vice versa.
if ((_physicalSize!.height > _physicalSize!.width && height < width) ||
(_physicalSize!.width > _physicalSize!.height && width < height)) {
// Rotation detected
return true;
// This method compares the new dimensions with the previous ones.
// Return false if the previous dimensions are not set.
if(_physicalSize != null) {
// First confirm both height and width are effected.
if (_physicalSize!.height != height && _physicalSize!.width != width) {
// If prior to rotation height is bigger than width it should be the
// opposite after the rotation and vice versa.
if ((_physicalSize!.height > _physicalSize!.width && height < width) ||
(_physicalSize!.width > _physicalSize!.height && width < height)) {
// Rotation detected
return true;
}
}
}
return false;

View File

@@ -3,6 +3,7 @@
// found in the LICENSE file.
// @dart = 2.6
import 'dart:async';
import 'dart:html';
import 'dart:js_util' as js_util;
import 'dart:typed_data';
@@ -719,6 +720,204 @@ void main() {
skip: (browserEngine == BrowserEngine.webkit ||
browserEngine == BrowserEngine.edge));
test('finishAutofillContext closes connection no autofill element',
() async {
final MethodCall setClient = MethodCall(
'TextInput.setClient', <dynamic>[123, flutterSinglelineConfig]);
sendFrameworkMessage(codec.encodeMethodCall(setClient));
const MethodCall setEditingState =
MethodCall('TextInput.setEditingState', <String, dynamic>{
'text': 'abcd',
'selectionBase': 2,
'selectionExtent': 3,
});
sendFrameworkMessage(codec.encodeMethodCall(setEditingState));
// Editing shouldn't have started yet.
expect(document.activeElement, document.body);
const MethodCall show = MethodCall('TextInput.show');
sendFrameworkMessage(codec.encodeMethodCall(show));
checkInputEditingState(
textEditing.editingElement.domElement, 'abcd', 2, 3);
const MethodCall finishAutofillContext =
MethodCall('TextInput.finishAutofillContext', false);
sendFrameworkMessage(codec.encodeMethodCall(finishAutofillContext));
expect(spy.messages, hasLength(1));
expect(spy.messages[0].channel, 'flutter/textinput');
expect(spy.messages[0].methodName, 'TextInputClient.onConnectionClosed');
expect(
spy.messages[0].methodArguments,
<dynamic>[
123, // Client ID
],
);
spy.messages.clear();
// Input element is removed from DOM.
expect(document.getElementsByTagName('input'), hasLength(0));
},
// TODO(nurhan): https://github.com/flutter/flutter/issues/50590
// TODO(nurhan): https://github.com/flutter/flutter/issues/50769
skip: (browserEngine == BrowserEngine.webkit ||
browserEngine == BrowserEngine.edge));
test('finishAutofillContext removes form from DOM', () async {
// Create a configuration with an AutofillGroup of four text fields.
final Map<String, dynamic> flutterMultiAutofillElementConfig =
createFlutterConfig('text',
autofillHint: 'username',
autofillHintsForFields: [
'username',
'email',
'name',
'telephoneNumber'
]);
final MethodCall setClient = MethodCall('TextInput.setClient',
<dynamic>[123, flutterMultiAutofillElementConfig]);
sendFrameworkMessage(codec.encodeMethodCall(setClient));
const MethodCall setEditingState1 =
MethodCall('TextInput.setEditingState', <String, dynamic>{
'text': 'abcd',
'selectionBase': 2,
'selectionExtent': 3,
});
sendFrameworkMessage(codec.encodeMethodCall(setEditingState1));
const MethodCall show = MethodCall('TextInput.show');
sendFrameworkMessage(codec.encodeMethodCall(show));
// Form is added to DOM.
expect(document.getElementsByTagName('form'), isNotEmpty);
const MethodCall clearClient = MethodCall('TextInput.clearClient');
sendFrameworkMessage(codec.encodeMethodCall(clearClient));
// Confirm that [HybridTextEditing] didn't send any messages.
expect(spy.messages, isEmpty);
// Form stays on the DOM until autofill context is finalized.
expect(document.getElementsByTagName('form'), isNotEmpty);
expect(formsOnTheDom, hasLength(1));
const MethodCall finishAutofillContext =
MethodCall('TextInput.finishAutofillContext', false);
sendFrameworkMessage(codec.encodeMethodCall(finishAutofillContext));
// Form element is removed from DOM.
expect(document.getElementsByTagName('form'), hasLength(0));
expect(formsOnTheDom, hasLength(0));
},
// TODO(nurhan): https://github.com/flutter/flutter/issues/50590
// TODO(nurhan): https://github.com/flutter/flutter/issues/50769
skip: (browserEngine == BrowserEngine.webkit ||
browserEngine == BrowserEngine.edge));
test('finishAutofillContext with save submits forms', () async {
// Create a configuration with an AutofillGroup of four text fields.
final Map<String, dynamic> flutterMultiAutofillElementConfig =
createFlutterConfig('text',
autofillHint: 'username',
autofillHintsForFields: [
'username',
'email',
'name',
'telephoneNumber'
]);
final MethodCall setClient = MethodCall('TextInput.setClient',
<dynamic>[123, flutterMultiAutofillElementConfig]);
sendFrameworkMessage(codec.encodeMethodCall(setClient));
const MethodCall setEditingState1 =
MethodCall('TextInput.setEditingState', <String, dynamic>{
'text': 'abcd',
'selectionBase': 2,
'selectionExtent': 3,
});
sendFrameworkMessage(codec.encodeMethodCall(setEditingState1));
const MethodCall show = MethodCall('TextInput.show');
sendFrameworkMessage(codec.encodeMethodCall(show));
// Form is added to DOM.
expect(document.getElementsByTagName('form'), isNotEmpty);
FormElement formElement = document.getElementsByTagName('form')[0];
final Completer<bool> submittedForm = Completer<bool>();
formElement.addEventListener(
'submit', (event) => submittedForm.complete(true));
const MethodCall clearClient = MethodCall('TextInput.clearClient');
sendFrameworkMessage(codec.encodeMethodCall(clearClient));
const MethodCall finishAutofillContext =
MethodCall('TextInput.finishAutofillContext', true);
sendFrameworkMessage(codec.encodeMethodCall(finishAutofillContext));
// `submit` action is called on form.
await expectLater(await submittedForm.future, true);
},
// TODO(nurhan): https://github.com/flutter/flutter/issues/50590
// TODO(nurhan): https://github.com/flutter/flutter/issues/50769
skip: (browserEngine == BrowserEngine.webkit ||
browserEngine == BrowserEngine.edge));
test('forms submits for focused input', () async {
// Create a configuration with an AutofillGroup of four text fields.
final Map<String, dynamic> flutterMultiAutofillElementConfig =
createFlutterConfig('text',
autofillHint: 'username',
autofillHintsForFields: [
'username',
'email',
'name',
'telephoneNumber'
]);
final MethodCall setClient = MethodCall('TextInput.setClient',
<dynamic>[123, flutterMultiAutofillElementConfig]);
sendFrameworkMessage(codec.encodeMethodCall(setClient));
const MethodCall setEditingState1 =
MethodCall('TextInput.setEditingState', <String, dynamic>{
'text': 'abcd',
'selectionBase': 2,
'selectionExtent': 3,
});
sendFrameworkMessage(codec.encodeMethodCall(setEditingState1));
const MethodCall show = MethodCall('TextInput.show');
sendFrameworkMessage(codec.encodeMethodCall(show));
// Form is added to DOM.
expect(document.getElementsByTagName('form'), isNotEmpty);
FormElement formElement = document.getElementsByTagName('form')[0];
final Completer<bool> submittedForm = Completer<bool>();
formElement.addEventListener(
'submit', (event) => submittedForm.complete(true));
// Clear client is not called. The used requested context to be finalized.
const MethodCall finishAutofillContext =
MethodCall('TextInput.finishAutofillContext', true);
sendFrameworkMessage(codec.encodeMethodCall(finishAutofillContext));
// Connection is closed by the engine.
expect(spy.messages, hasLength(1));
expect(spy.messages[0].channel, 'flutter/textinput');
expect(spy.messages[0].methodName, 'TextInputClient.onConnectionClosed');
// `submit` action is called on form.
await expectLater(await submittedForm.future, true);
// Form element is removed from DOM.
expect(document.getElementsByTagName('form'), hasLength(0));
expect(formsOnTheDom, hasLength(0));
},
// TODO(nurhan): https://github.com/flutter/flutter/issues/50590
// TODO(nurhan): https://github.com/flutter/flutter/issues/50769
skip: (browserEngine == BrowserEngine.webkit ||
browserEngine == BrowserEngine.edge));
test('setClient, setEditingState, show, setClient', () {
final MethodCall setClient = MethodCall(
'TextInput.setClient', <dynamic>[123, flutterSinglelineConfig]);
@@ -816,14 +1015,17 @@ void main() {
textEditing.editingElement.domElement, 'abcd', 2, 3);
final FormElement formElement = document.getElementsByTagName('form')[0];
expect(formElement.childNodes, hasLength(1));
// The form has one input element and one submit button.
expect(formElement.childNodes, hasLength(2));
const MethodCall clearClient = MethodCall('TextInput.clearClient');
sendFrameworkMessage(codec.encodeMethodCall(clearClient));
// Confirm that [HybridTextEditing] didn't send any messages.
expect(spy.messages, isEmpty);
expect(document.getElementsByTagName('form'), isEmpty);
// Form stays on the DOM until autofill context is finalized.
expect(document.getElementsByTagName('form'), isNotEmpty);
expect(formsOnTheDom, hasLength(1));
});
test(
@@ -859,14 +1061,17 @@ void main() {
textEditing.editingElement.domElement, 'abcd', 2, 3);
final FormElement formElement = document.getElementsByTagName('form')[0];
expect(formElement.childNodes, hasLength(4));
// The form has 4 input elements and one submit button.
expect(formElement.childNodes, hasLength(5));
const MethodCall clearClient = MethodCall('TextInput.clearClient');
sendFrameworkMessage(codec.encodeMethodCall(clearClient));
// Confirm that [HybridTextEditing] didn't send any messages.
expect(spy.messages, isEmpty);
expect(document.getElementsByTagName('form'), isEmpty);
// Form stays on the DOM until autofill context is finalized.
expect(document.getElementsByTagName('form'), isNotEmpty);
expect(formsOnTheDom, hasLength(1));
});
test('No capitilization: setClient, setEditingState, show', () {
@@ -1228,7 +1433,8 @@ void main() {
textEditing.editingElement.domElement, 'abcd', 2, 3);
final FormElement formElement = document.getElementsByTagName('form')[0];
expect(formElement.childNodes, hasLength(4));
// The form has 4 input elements and one submit button.
expect(formElement.childNodes, hasLength(5));
// Autofill one of the form elements.
InputElement element = formElement.childNodes.first;
@@ -1450,13 +1656,17 @@ void main() {
// And default behavior of keyboard event shouldn't have been prevented.
expect(event.defaultPrevented, isFalse);
});
tearDown(() {
clearForms();
});
});
group('EngineAutofillForm', () {
test('validate multi element form', () {
final List<dynamic> fields = createFieldValues(
['username', 'password', 'newPassword'],
['field1', 'fields2', 'field3']);
['field1', 'field2', 'field3']);
final EngineAutofillForm autofillForm =
EngineAutofillForm.fromFrameworkMessage(
createAutofillInfo('username', 'field1'), fields);
@@ -1467,14 +1677,18 @@ void main() {
expect(autofillForm.items, hasLength(2));
expect(autofillForm.formElement, isNotNull);
expect(autofillForm.formIdentifier, 'field1*field2*field3');
final FormElement form = autofillForm.formElement;
expect(form.childNodes, hasLength(2));
// Note that we also add a submit button. Therefore the form element has
// 3 child nodes.
expect(form.childNodes, hasLength(3));
final InputElement firstElement = form.childNodes.first;
// Autofill value is applied to the element.
expect(firstElement.name,
BrowserAutofillHints.instance.flutterToEngine('password'));
expect(firstElement.id, 'fields2');
expect(firstElement.id, BrowserAutofillHints.instance.flutterToEngine('password'));
expect(firstElement.type, 'password');
if (browserEngine == BrowserEngine.firefox) {
expect(firstElement.name,
@@ -1495,7 +1709,21 @@ void main() {
expect(css.backgroundColor, 'transparent');
});
test('place remove form', () {
test('validate multi element form ids sorted for form id', () {
final List<dynamic> fields = createFieldValues(
['username', 'password', 'newPassword'],
['zzyyxx', 'aabbcc', 'jjkkll']);
final EngineAutofillForm autofillForm =
EngineAutofillForm.fromFrameworkMessage(
createAutofillInfo('username', 'field1'), fields);
expect(autofillForm.formIdentifier, 'aabbcc*jjkkll*zzyyxx');
});
test('place and store form', () {
expect(document.getElementsByTagName('form'), isEmpty);
final List<dynamic> fields = createFieldValues(
['username', 'password', 'newPassword'],
['field1', 'fields2', 'field3']);
@@ -1506,16 +1734,18 @@ void main() {
final InputElement testInputElement = InputElement();
autofillForm.placeForm(testInputElement);
// The focused element is appended to the form,
// The focused element is appended to the form, form also has the button
// so in total it shoould have 4 elements.
final FormElement form = autofillForm.formElement;
expect(form.childNodes, hasLength(3));
expect(form.childNodes, hasLength(4));
final FormElement formOnDom = document.getElementsByTagName('form')[0];
// Form is attached to the DOM.
expect(form, equals(formOnDom));
autofillForm.removeForm();
expect(document.getElementsByTagName('form'), isEmpty);
autofillForm.storeForm();
expect(document.getElementsByTagName('form'), isNotEmpty);
expect(formsOnTheDom, hasLength(1));
});
test('Validate single element form', () {
@@ -1531,7 +1761,13 @@ void main() {
expect(autofillForm.formElement, isNotNull);
final FormElement form = autofillForm.formElement;
expect(form.childNodes, isEmpty);
// Submit button is added to the form.
expect(form.childNodes, isNotEmpty);
final InputElement inputElement = form.childNodes.first;
expect(inputElement.type, 'submit');
// The submit button should have class `submitBtn`.
expect(inputElement.className, 'submitBtn');
});
test('Return null if no focused element', () {
@@ -1541,6 +1777,10 @@ void main() {
expect(autofillForm, isNull);
});
tearDown(() {
clearForms();
});
});
group('AutofillInfo', () {
@@ -1570,7 +1810,8 @@ void main() {
// browsers.
expect(testInputElement.name,
BrowserAutofillHints.instance.flutterToEngine(testHint));
expect(testInputElement.id, testId);
expect(testInputElement.id,
BrowserAutofillHints.instance.flutterToEngine(testHint));
expect(testInputElement.type, 'text');
if (browserEngine == BrowserEngine.firefox) {
expect(testInputElement.name,
@@ -1592,7 +1833,8 @@ void main() {
// browsers.
expect(testInputElement.name,
BrowserAutofillHints.instance.flutterToEngine(testHint));
expect(testInputElement.id, testId);
expect(testInputElement.id,
BrowserAutofillHints.instance.flutterToEngine(testHint));
expect(testInputElement.getAttribute('autocomplete'),
BrowserAutofillHints.instance.flutterToEngine(testHint));
});
@@ -1608,7 +1850,8 @@ void main() {
// browsers.
expect(testInputElement.name,
BrowserAutofillHints.instance.flutterToEngine(testPasswordHint));
expect(testInputElement.id, testId);
expect(testInputElement.id,
BrowserAutofillHints.instance.flutterToEngine(testPasswordHint));
expect(testInputElement.type, 'password');
expect(testInputElement.getAttribute('autocomplete'),
BrowserAutofillHints.instance.flutterToEngine(testPasswordHint));
@@ -1756,7 +1999,7 @@ MethodCall configureSetSizeAndTransformMethodCall(
/// Will disable editing element which will also clean the backup DOM
/// element from the page.
void cleanTextEditingElement() {
if (editingElement.isEnabled) {
if (editingElement != null && editingElement.isEnabled) {
// Clean up all the DOM elements and event listeners.
editingElement.disable();
}
@@ -1867,3 +2110,11 @@ Map<String, dynamic> createOneFieldValue(String hint, String uniqueId) =>
'textCapitalization': 'TextCapitalization.none',
'autofill': createAutofillInfo(hint, uniqueId)
};
/// In order to not leak test state, clean up the forms from dom if any remains.
void clearForms() {
while (document.getElementsByTagName('form').length > 0) {
document.getElementsByTagName('form').last.remove();
}
formsOnTheDom.clear();
}