Skip to content

Commit

Permalink
Fix inputs with the autofocus attribute (ampproject#11908)
Browse files Browse the repository at this point in the history
* Fix inputs with the autofocus attribute

* Use whenNextVisible instead
  • Loading branch information
cvializ authored and neko-fire committed Nov 17, 2017
1 parent 6e97ccb commit 96597c0
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
15 changes: 14 additions & 1 deletion extensions/amp-form/0.1/amp-form.js
Expand Up @@ -19,7 +19,10 @@ import {FormEvents} from './form-events';
import {installFormProxy} from './form-proxy';
import {triggerAnalyticsEvent} from '../../../src/analytics';
import {createCustomEvent} from '../../../src/event-helper';
import {iterateCursor} from '../../../src/dom';
import {
iterateCursor,
tryFocus,
} from '../../../src/dom';
import {
formOrNullForElement,
setFormForElement,
Expand Down Expand Up @@ -139,6 +142,9 @@ export class AmpForm {
/** @const @private {!../../../src/service/resources-impl.Resources} */
this.resources_ = Services.resourcesForDoc(this.form_);

/** @const @private */
this.viewer_ = Services.viewerForDoc(this.form_);

/** @const @private {string} */
this.method_ = (this.form_.getAttribute('method') || 'GET').toUpperCase();

Expand Down Expand Up @@ -251,6 +257,13 @@ export class AmpForm {

/** @private */
installEventHandlers_() {
this.viewer_.whenNextVisible().then(() => {
const autofocus = this.form_.querySelector('[autofocus]');
if (autofocus) {
tryFocus(autofocus);
}
});

this.form_.addEventListener(
'submit', this.handleSubmitEvent_.bind(this), true);

Expand Down
22 changes: 22 additions & 0 deletions extensions/amp-form/0.1/test/test-amp-form.js
Expand Up @@ -161,6 +161,28 @@ describes.repeated('', {
document.body.removeChild(form);
});

it('should autofocus elements with the autofocus attribute', () => {
const form = getForm();
document.body.appendChild(form);
form.addEventListener = sandbox.spy();
form.setAttribute('action-xhr', 'https://example.com');
const button1 = form.querySelector('input');
button1.setAttribute('autofocus', '');
new AmpForm(form);

const viewer = Services.viewerForDoc(form.ownerDocument);
let resolve_ = null;
sandbox.stub(viewer, 'whenNextVisible').returns(new Promise(resolve => {
resolve_ = resolve;
}));

expect(document.activeElement).to.not.equal(button1);
resolve_();
return viewer.whenNextVisible().then(() => {
expect(document.activeElement).to.equal(button1);
});
});

it('should install proxy', () => {
const form = getForm();
document.body.appendChild(form);
Expand Down

0 comments on commit 96597c0

Please sign in to comment.