Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/components/RichTextArea/LinkPlugin/LinkPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import Link from './Link/Link'
import linkStrategy from './linkStrategy'

import createLinkEntity from './utils/createLink'
import handlePastedText from './utils/handlePaste'

/**
* Creates link plugin
Expand All @@ -20,6 +21,7 @@ export default function createLinkPlugin() {
component: Link,
}
],
onChange: createLinkEntity
onChange: createLinkEntity,
handlePastedText
}
}
81 changes: 81 additions & 0 deletions src/components/RichTextArea/LinkPlugin/utils/handlePaste.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { EditorState, Modifier } from 'draft-js'

import newLinkifyIt from 'linkify-it'
import tlds from 'tlds'

const linkifyIt = newLinkifyIt()
linkifyIt.tlds(tlds)

/**
* Handle pasted text
* @param {string} text - pasted text
* @param {string} _html - pasted html
* @param {Object} editorState - current editor state
* @param {Object} extras - Extra object passed by draft-js-link-editor.
* @param {function} extras.setEditorState - function to set new editor state.
*/
export default function handlePastedText(
text,
_html,
editorState,
{ setEditorState }
) {
if (!text) {
return false
}

// parse all the links in the pasted text
const links = linkifyIt.match(text)
if (!links) {
return false
}

const contentState = editorState.getCurrentContent()
const selectionState = editorState.getSelection()
const cursorPosition = selectionState.getStartOffset()

let currentContentState = Modifier.insertText(
contentState,
selectionState,
text
)

links.forEach(({ index, lastIndex, url }) => {
const linkText = text.slice(index, lastIndex)

// Create link entity
currentContentState = currentContentState.createEntity('LINK', 'MUTABLE', {
url,
text: null
})
const entityKey = currentContentState.getLastCreatedEntityKey()

// Select the current link text and replace with link entity
const linkTextSelection = selectionState.merge({
anchorOffset: index + cursorPosition,
focusOffset: lastIndex + cursorPosition,
isBackward: false
})
currentContentState = Modifier.replaceText(
currentContentState,
linkTextSelection,
linkText,
null,
entityKey
)
})

// Move cursor to the end of the pasted text
const newSelectionState = selectionState.merge({
anchorOffset: cursorPosition + text.length,
focusOffset: cursorPosition + text.length,
isBackward: false
})
const newEditorState = EditorState.forceSelection(
EditorState.push(editorState, currentContentState, 'insert-characters'),
newSelectionState
)

setEditorState(newEditorState)
return 'handled'
}