Last active
August 31, 2020 19:48
-
-
Save jackcallister/af55f3705add9d9ec34fd0cb25ef2f67 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 = (start, end) => { | |
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 entityKey = Entity.create('LINK', 'IMMUTABLE', { url: linkText }) | |
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].index, links[i].lastIndex) | |
} | |
} | |
} | |
export default linkifyEditorState |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's too outdated, but I rebuild logic and it works fine https://gist.github.com/anders0l/7a2c2b9a59b1c66a85089c597984d916