Skip to content

Commit

Permalink
Close the picker on ESC #128
Browse files Browse the repository at this point in the history
  • Loading branch information
joews committed Apr 28, 2017
1 parent 2386e39 commit 0ccf0e0
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
19 changes: 15 additions & 4 deletions lib/js/__tests__/index-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,34 @@ test("opening the picker ads backdrop and picker elements to the dom", () => {

const $backdrop = $(".c-scrim");
const $picker = $(".c-datepicker");

expect($picker).not.toBeNull();
expect($backdrop).not.toBeNull();
});

test("closing the picker removes elements from the dom", async () => {
const picker = await openPicker()
const picker = await openPicker();
picker.close();
await delay(300);

const $backdrop = $(".c-scrim");
const $picker = $(".c-datepicker");

expect($picker).toBeNull();
expect($backdrop).toBeNull();
});

test.only("the picker closes when the escape key is pressed", async () => {
const picker = await openPicker();

const event = new window.KeyboardEvent('keydown', { which: 27, keyCode: 27 });
window.dispatchEvent(event);

await delay(300);
const $picker = $(".c-datepicker")
expect($picker).toBeNull();
});

test("opening the picker with a default time", async () => {
// time divides 5 minutes; set exactly
const time = "2017-02-01T17:30:00.000Z";
Expand Down Expand Up @@ -126,4 +137,4 @@ test("picker#set quanitizes to the nearest 5 minutes", async () => {
// test round up
picker.set("2017-02-01T18:35:04.941Z");
expect(picker.data().toISOString()).toEqual( "2017-02-01T18:35:00.000Z");
})
})
20 changes: 20 additions & 0 deletions lib/js/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import Events from './events';

import '../scss/material-datetime-picker.scss';

const ESC_KEY = 27;

const prefix = 'c-datepicker';
const defaults = () => ({
default: moment().startOf('hour'),
Expand Down Expand Up @@ -98,10 +100,13 @@ class DateTimePicker extends Events {
}

this.initializeRome(this.$(`.${this.options.styles.container}`), this.options.dateValidator);
this._listenForCloseEvents();

this._show();
}

close() {
this._stopListeningForCloseEvents();
this._hide();
}

Expand All @@ -127,6 +132,21 @@ class DateTimePicker extends Events {
return this;
}

_listenForCloseEvents() {
this._onWindowKeypress = (e) => {
if (e.which === ESC_KEY) {
this.close();
}
};

window.addEventListener("keydown", this._onWindowKeypress);
}

_stopListeningForCloseEvents() {
window.removeEventListener("keydown", this._onWindowKeypress);
this._closeHandler = null;
}

delegateEvents() {
this.$('.js-cancel')
.addEventListener('click', () => this.clickCancel(), false);
Expand Down

0 comments on commit 0ccf0e0

Please sign in to comment.