diff --git a/lib/js/__tests__/index-test.js b/lib/js/__tests__/index-test.js index 76d66b6..3e4d0f7 100644 --- a/lib/js/__tests__/index-test.js +++ b/lib/js/__tests__/index-test.js @@ -16,16 +16,16 @@ 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"); @@ -33,6 +33,17 @@ test("closing the picker removes elements from the dom", async () => { 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"; @@ -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"); -}) \ No newline at end of file +}) diff --git a/lib/js/index.js b/lib/js/index.js index bc4d794..07fc2e3 100644 --- a/lib/js/index.js +++ b/lib/js/index.js @@ -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'), @@ -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(); } @@ -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);