From ab280503cb489c95f849695966ae659e3f46e51d Mon Sep 17 00:00:00 2001 From: Artur Arseniev Date: Sat, 17 Feb 2024 10:31:49 +0400 Subject: [PATCH] Add `onPaste` and `onKeydown` options to RTE module. --- src/rich_text_editor/config/config.ts | 28 ++++++++++++++++++++ src/rich_text_editor/model/RichTextEditor.ts | 17 +++++++++++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/rich_text_editor/config/config.ts b/src/rich_text_editor/config/config.ts index 4e885aad5..62bac7e6b 100644 --- a/src/rich_text_editor/config/config.ts +++ b/src/rich_text_editor/config/config.ts @@ -1,3 +1,6 @@ +import Editor from '../../editor'; +import RichTextEditor from '../model/RichTextEditor'; + export interface CustomRTE { /** * If true, the returned HTML content will be parsed into Components, allowing @@ -45,6 +48,31 @@ export interface RichTextEditorConfig { * @default ['bold', 'italic', 'underline', 'strikethrough', 'link', 'wrap'] */ actions?: string[]; + + /** + * Custom on paste logic for the built-in RTE. + * @example + * onPaste: ({ ev, rte }) => { + * ev.preventDefault(); + * const { clipboardData } = ev; + * const text = clipboardData.getData('text'); + * rte.exec('insertHTML', `[ ${text} ]`); + * } + */ + onPaste?: (data: { ev: ClipboardEvent; editor: Editor; rte: RichTextEditor }) => void; + + /** + * Custom on keydown logic for the built-in RTE. + * @example + * onKeydown: ({ ev, rte }) => { + * if (ev.key === 'Enter') { + * ev.preventDefault(); + * rte.exec('insertHTML', `
-- custom line break --
`); + * } + * } + */ + onKeydown?: (data: { ev: KeyboardEvent; editor: Editor; rte: RichTextEditor }) => void; + /** * Avoid rendering the default RTE UI. * @default false diff --git a/src/rich_text_editor/model/RichTextEditor.ts b/src/rich_text_editor/model/RichTextEditor.ts index 678a4bff4..51c3e3a15 100644 --- a/src/rich_text_editor/model/RichTextEditor.ts +++ b/src/rich_text_editor/model/RichTextEditor.ts @@ -296,6 +296,13 @@ export default class RichTextEditor { } __onKeydown(ev: KeyboardEvent) { + const { em } = this; + const { onKeydown } = em.RichTextEditor.getConfig(); + + if (onKeydown) { + return onKeydown({ ev, rte: this, editor: em.getEditor() }); + } + const { doc } = this; const cmdList = ['insertOrderedList', 'insertUnorderedList']; @@ -306,10 +313,18 @@ export default class RichTextEditor { } __onPaste(ev: ClipboardEvent) { + const { em } = this; + const { onPaste } = em.RichTextEditor.getConfig(); + + if (onPaste) { + return onPaste({ ev, rte: this, editor: em.getEditor() }); + } + const clipboardData = ev.clipboardData!; const text = clipboardData.getData('text'); const textHtml = clipboardData.getData('text/html'); - // Replace \n with
in case of plain text + + // Replace \n with
in case of a plain text if (text && !textHtml) { ev.preventDefault(); const html = text.replace(/(?:\r\n|\r|\n)/g, '
');