Insert a Link in the Editor Without Selecting Text
Environment
| Product | Progress® KendoReact Editor |
|---|---|
| Product Version | 16.2.0 |
Description
How can I insert a link in the KendoReact Editor without selecting text first? The built-in Link tool is disabled when I place the caret in the content.
This KB also answers the following questions:
- Can the Editor Link tool insert a link at the caret position?
- How do I add a link with its own text in the Editor?
- How do I create a custom Editor tool that inserts a hyperlink?
Solution
The built-in Link tool applies a link mark to the current selection. Its dialog contains the Web address, Title, and Open link in new window fields, and has no field for the link text. For this reason, the tool is disabled when the selection is empty, unless the caret is already inside a link.
To insert a link without selecting text, create a custom tool that collects the address and the link text, and inserts a text node with a link mark at the caret by dispatching a ProseMirror transaction. If text is selected, the new link replaces the selection.
The following example demonstrates the complete implementation. Click in the content without selecting text, and then click the custom Insert link at caret tool. Compare it with the built-in Link tool, which stays disabled.
The solution consists of the following steps:
-
Create a tool component that receives the Editor
viewthrough its props. Render a button, and open a dialog where users enter the web address and the link text. The following snippet shows how the button state depends on whether a text node can be inserted at the current selection.tsxconst canInsert = !!view && EditorUtils.canInsert(view.state, view.state.schema.nodes.text); -
On insert, create a text node that carries the link mark, and insert it by dispatching a transaction that calls
replaceSelectionWithwith its second argument set tofalse. By default,replaceSelectionWithreplaces the marks of the inserted node with the marks at the caret, which removes the link mark and leaves plain text. Pass the address through thesanitizeUrlfunction of@progress/kendo-react-commonto remove unsafe URL schemes. The following snippet shows the insertion.tsxconst href = sanitizeUrl(address); const { schema } = view.state; const linkMark = schema.marks.link.create({ href }); view.dispatch(view.state.tr.replaceSelectionWith(schema.text(text, [linkMark]), false).scrollIntoView()); -
Add the custom tool to the
toolsarray of the Editor.tsx<Editor tools={[[EditorTools.Link, InsertLinkAtCaret]]} />