From 7612ff9310e254b49c59489a82cca1c802605a58 Mon Sep 17 00:00:00 2001 From: zoy-l <409626581@qq.com> Date: Tue, 8 Mar 2022 19:47:30 +0800 Subject: [PATCH] feat(Dialog): support keyboard events (#10359) * feat(dialog): keyboard events are supported * chore: prevention interruption * chore: add the corresponding event --- src/dialog/Dialog.js | 30 ++++++++++++++++++- .../test/__snapshots__/demo.spec.js.snap | 2 +- .../test/__snapshots__/index.spec.js.snap | 8 ++--- 3 files changed, 34 insertions(+), 6 deletions(-) diff --git a/src/dialog/Dialog.js b/src/dialog/Dialog.js index 68359efac..88b9be460 100644 --- a/src/dialog/Dialog.js +++ b/src/dialog/Dialog.js @@ -1,4 +1,4 @@ -import { createNamespace, addUnit } from '../utils'; +import { createNamespace, addUnit, noop } from '../utils'; import { BORDER_TOP, BORDER_LEFT } from '../utils/constant'; import { PopupMixin } from '../mixins/popup'; import Button from '../button'; @@ -97,12 +97,37 @@ export default createComponent({ onOpened() { this.$emit('opened'); + + this.$nextTick(() => { + this.$refs.dialog?.focus(); + }); }, onClosed() { this.$emit('closed'); }, + onKeydown(event) { + if (event.key === 'Escape' || event.key === 'Enter') { + // skip keyboard events of child elements + if (event.target !== this.$refs.dialog) { + return; + } + + const onEventType = { + Enter: this.showConfirmButton + ? () => this.handleAction('confirm') + : noop, + Escape: this.showCancelButton + ? () => this.handleAction('cancel') + : noop, + }; + + onEventType[event.key](); + this.$emit('keydown', event); + } + }, + genRoundButtons() { return ( @@ -221,6 +246,9 @@ export default createComponent({ aria-labelledby={this.title || message} class={[bem([this.theme]), this.className]} style={{ width: addUnit(this.width) }} + ref="dialog" + tabIndex={0} + onKeydown={this.onKeydown} > {Title} {this.genContent(title, messageSlot)} diff --git a/src/dialog/test/__snapshots__/demo.spec.js.snap b/src/dialog/test/__snapshots__/demo.spec.js.snap index a75f024a8..f28cc820b 100644 --- a/src/dialog/test/__snapshots__/demo.spec.js.snap +++ b/src/dialog/test/__snapshots__/demo.spec.js.snap @@ -37,7 +37,7 @@ exports[`renders demo correctly 1`] = `
组件调用
-