Adding Custom Plugin that Inserts Hard Break on Enter in the Editor
Environment
| Product | Progress® Kendo UI® for Angular Editor |
Description
How to add a custom plugin to the Editor component that will insert a hard break when pressing the Enter key, while preserving the default list behavior when the cursor is inside list items?
This Knowledge Base article also answers the following questions:
- How can I create a custom plugin for the Kendo UI for Angular Editor component to insert a hard break on
Enterkey press? - How do I ensure that the custom plugin does not interfere with the default behavior of list items when the cursor is inside a list in the Editor component?
- How can I integrate the custom plugin into the Editor component to enhance its functionality while maintaining compatibility with existing features?
Solution
To learn how to add custom plugins to the Editor component, refer to the Custom Plugins article.
-
Create a custom plugin by using the keymap function. Bind the
Enterkey press event to the plugin, overriding the default behavior and enabling it to replace the current selection with ahard_breaknode.typescriptlet shiftEnter: Plugin = keymap({ Enter: (state, dispatch) => { // Plugin logic here } }); -
Check if the cursor is inside a list item by traversing the selection depth. If the cursor is within a list item or list node, return
falseto preserve the default list behavior (creating a new list item onEnter). This check prevents the hard break from interfering with list functionality.typescriptconst { $from } = state.selection; for (let d = $from.depth; d > 0; d--) { const node = $from.node(d); if ( node.type.name === 'list_item' || node.type.name === 'listItem' || node.type.name === 'bullet_list' || node.type.name === 'ordered_list' ) { return false; } } -
Replace the selection with a
hard_breaknode and modify the selection position to ensure the cursor stays in the correct place. Create a new transaction (tr) and set the selection's anchor position tonewPos.typescriptconst tr = state.tr.replaceSelectionWith( state.schema.node('hard_break') ); const newPos = tr.selection.anchor; tr.setSelection(TextSelection.create(tr.doc, newPos)); if (dispatch) dispatch(tr); return true; -
Associate the newly created custom plugin with the Editor component by utilizing the
pluginsproperty.typescriptpublic myPlugins(defaultPlugins: Plugin[]): Plugin[] { let shiftEnter: Plugin = keymap({ /* ... */ }); return [shiftEnter, ...defaultPlugins]; }
The following example demonstrates how to add a custom plugin that will insert a hard break on Enter key press.