Forked from jackcallister/linkifyEditorState.js
Last active
December 5, 2017 13:04
-
-
Save danii1/ce569f1bc121398f6f2751a62320fe2f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { EditorState, Modifier, Entity, SelectionState } from 'draft-js' | |
import linkifyIt from 'linkify-it' | |
import tlds from 'tlds' | |
const linkify = linkifyIt() | |
linkify.tlds(tlds) | |
const linkifyEditorState = (editorState) => { | |
const contentState = editorState.getCurrentContent() | |
const blocks = contentState.getBlockMap() | |
let newContentState = contentState | |
blocks.forEach((block) => { | |
const plainText = block.getText() | |
const addEntityToLink = ({ index: start, lastIndex: end, schema, url }) => { | |
const existingEntityKey = block.getEntityAt(start) | |
if (existingEntityKey) { | |
// avoid manipulation in case the link already has an entity | |
const entity = Entity.get(existingEntityKey) | |
if (entity && entity.get('type') === 'link') { | |
return | |
} | |
} | |
const selection = SelectionState.createEmpty(block.getKey()) | |
.set('anchorOffset', start) | |
.set('focusOffset', end) | |
const linkText = plainText.substring(start, end) | |
const entity = schema !== 'mailto:' | |
? { url, target: '_blank' } | |
: { url } | |
const entityKey = Entity.create('LINK', 'IMMUTABLE', entity) | |
newContentState = Modifier.replaceText( | |
newContentState, | |
selection, | |
linkText, | |
null, | |
entityKey, | |
) | |
} | |
findLinks(block, addEntityToLink) | |
}) | |
if (!newContentState.equals(contentState)) { | |
return EditorState.push( | |
editorState, | |
newContentState, | |
'convert-to-links', | |
) | |
} | |
return editorState | |
} | |
const findLinks = (contentBlock, callback) => { | |
const links = linkify.match(contentBlock.get('text')) | |
if (typeof links !== 'undefined' && links !== null) { | |
for (let i = 0; i < links.length; i++) { | |
callback(links[i]) | |
} | |
} | |
} | |
export default linkifyEditorState |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment