forked from HubSpot/draft-convert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencodeBlock.js
45 lines (37 loc) · 1.03 KB
/
encodeBlock.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import updateMutation from './util/updateMutation'
import rangeSort from './util/rangeSort'
const ENTITY_MAP = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'`': '`',
'\n': '<br/>',
}
export default (block) => {
const blockText = [...block.text]
let entities = block.entityRanges.sort(rangeSort)
let styles = block.inlineStyleRanges.sort(rangeSort)
let resultText = ''
for (let index = 0; index < blockText.length; index += 1) {
const char = blockText[index]
if (ENTITY_MAP[char] !== undefined) {
const encoded = ENTITY_MAP[char]
const resultIndex = [...resultText].length
resultText += encoded
const updateForChar = (mutation) =>
updateMutation(mutation, resultIndex, char.length, encoded.length, 0, 0)
entities = entities.map(updateForChar)
styles = styles.map(updateForChar)
} else {
resultText += char
}
}
return {
...block,
text: resultText,
inlineStyleRanges: styles,
entityRanges: entities,
}
}