Created
June 5, 2016 10:58
-
-
Save vinhlh/30482f9741d2148a1693410f3114d478 to your computer and use it in GitHub Desktop.
Convert Draftjs Mentions raw content to HTML
This file contains 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
const renderMention = (entity) => { | |
const { link, name } = entity.data.mention | |
return `<a href="${link}">${name}</a>` | |
} | |
const renderEntity = (entity) => { | |
if (entity.type === 'mention') { | |
return renderMention(entity) | |
} | |
return '' | |
} | |
const getRangeKey = (start, end) => `${start}_${end}` | |
const parseEntityRanges = (entityRanges) => { | |
const points = new Set() | |
const entityRangeMap = new Map() | |
points.add(0) | |
entityRanges.forEach((range) => { | |
points.add(range.offset) | |
const end = range.offset + range.length | |
points.add(end) | |
entityRangeMap.set(getRangeKey(range.offset, end), range.key) | |
}) | |
return { points, entityRangeMap } | |
} | |
const convertRawToHTML = (raw) => { | |
const blockResults = raw.blocks.map(block => { | |
let { points, entityRangeMap } = parseEntityRanges(block.entityRanges) | |
points.add(block.text.length) | |
points = Array.from(points) | |
const results = points.map((start, index) => { | |
if (index < points.length - 1) { | |
const end = points[index + 1] | |
const rangeKey = getRangeKey(start, end) | |
if (entityRangeMap.has(rangeKey)) { | |
const entity = raw.entityMap[entityRangeMap.get(rangeKey)] | |
return renderEntity(entity) | |
} else { | |
return block.text.slice(start, end) | |
} | |
} | |
return '' | |
}) | |
return `<p>${results.join('')}</p>` | |
}) | |
return blockResults.join('') | |
} | |
export { | |
convertRawToHTML | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment