diff --git a/app/assets/javascripts/discourse/app/components/d-button.js b/app/assets/javascripts/discourse/app/components/d-button.js index a5848515f43..874d023eeed 100644 --- a/app/assets/javascripts/discourse/app/components/d-button.js +++ b/app/assets/javascripts/discourse/app/components/d-button.js @@ -109,10 +109,24 @@ export default Component.extend({ if (this.onKeyDown) { e.stopPropagation(); this.onKeyDown(e); + } else if (e.key === "Enter") { + this._triggerAction(e); + return false; } }, click(event) { + this._triggerAction(event); + return false; + }, + + mouseDown(event) { + if (this.preventFocus) { + event.preventDefault(); + } + }, + + _triggerAction(event) { let { action } = this; if (action) { @@ -141,13 +155,5 @@ export default Component.extend({ event.preventDefault(); event.stopPropagation(); - - return false; - }, - - mouseDown(event) { - if (this.preventFocus) { - event.preventDefault(); - } }, }); diff --git a/app/assets/javascripts/discourse/tests/integration/components/d-button-test.js b/app/assets/javascripts/discourse/tests/integration/components/d-button-test.js index 2e02bafa2e3..9be51b35101 100644 --- a/app/assets/javascripts/discourse/tests/integration/components/d-button-test.js +++ b/app/assets/javascripts/discourse/tests/integration/components/d-button-test.js @@ -7,6 +7,7 @@ import { query, queryAll, } from "discourse/tests/helpers/qunit-helpers"; +import { triggerKeyEvent } from "@ember/test-helpers"; import I18n from "I18n"; import hbs from "htmlbars-inline-precompile"; @@ -219,4 +220,49 @@ discourseModule("Integration | Component | d-button", function (hooks) { ); }, }); + + componentTest("onKeyDown callback", { + template: hbs`{{d-button action=action onKeyDown=onKeyDown}}`, + + beforeEach() { + this.set("foo", null); + this.set("onKeyDown", () => { + this.set("foo", "bar"); + }); + this.set("action", () => { + this.set("foo", "baz"); + }); + }, + + async test(assert) { + await triggerKeyEvent(".btn", "keydown", 32); + + assert.strictEqual(this.foo, "bar"); + + await triggerKeyEvent(".btn", "keydown", 13); + + assert.strictEqual(this.foo, "bar"); + }, + }); + + componentTest("press Enter", { + template: hbs`{{d-button action=action}}`, + + beforeEach() { + this.set("foo", null); + this.set("action", () => { + this.set("foo", "bar"); + }); + }, + + async test(assert) { + await triggerKeyEvent(".btn", "keydown", 32); + + assert.strictEqual(this.foo, null); + + await triggerKeyEvent(".btn", "keydown", 13); + + assert.strictEqual(this.foo, "bar"); + }, + }); });