Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add events to ClayDropdown to close on mobile and when the esq is pressed and when the iframe is clicked #959

Merged
merged 4 commits into from
May 31, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 49 additions & 4 deletions packages/clay-dropdown/src/ClayDropdownBase.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import {EventHandler} from 'metal-events';
import itemsValidator from './items_validator';
import templates from './ClayDropdownBase.soy.js';

const KEY_CODE_ESC = 27;

/**
* Implementation of the base for Metal Clay Dropdown.
* @extends ClayComponent
Expand All @@ -31,10 +33,6 @@ class ClayDropdownBase extends ClayComponent {
*/
created() {
this._eventHandler = new EventHandler();

this._eventHandler.add(
dom.on(document, 'click', this._handleDocClick.bind(this))
);
}

/**
Expand All @@ -57,6 +55,7 @@ class ClayDropdownBase extends ClayComponent {
*/
_close() {
this.expanded = false;
this._eventHandler.removeAllListeners();
}

/**
Expand Down Expand Up @@ -124,6 +123,17 @@ class ClayDropdownBase extends ClayComponent {
});
}

/**
* Handle click key code esc and close dropdown.
* @param {!Event} event
* @private
*/
_handleKeyup(event) {
if (event.keyCode === KEY_CODE_ESC) {
this._close();
}
}

/**
* Handle when the lifecycle `rendered` is called in ClayPortal.
* @protected
Expand Down Expand Up @@ -197,6 +207,41 @@ class ClayDropdownBase extends ClayComponent {
});
}

/**
* Handles blur window in order to hide menu.
* @private
*/
_handleWinBlur() {
const activeElement = document.activeElement;
if (activeElement != null && activeElement.nodeName === 'IFRAME') {
this._close();
}
}

/**
* @inheritDoc
*/
syncExpanded() {
if (this.expanded) {
this._eventHandler.add(
dom.on(
document,
'click',
this._handleDocClick.bind(this),
true
),
dom.on(document, 'keyup', this._handleKeyup.bind(this), true),
dom.on(
document,
'touchend',
this._handleDocClick.bind(this),
true
),
dom.on(window, 'blur', this._handleWinBlur.bind(this), true)
);
}
}

/**
* Toggles the dropdown, closing it when open or opening it when closed.
*/
Expand Down