forked from osdio/react-native-html-render
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhtmlToElement.js
executable file
·78 lines (66 loc) · 2.3 KB
/
htmlToElement.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import React from 'react'
import htmlparser from 'htmlparser2-without-node-native'
import entities from 'entities'
import {
Text
} from 'react-native'
const Image = require('./helper/Image')
const LINE_BREAK = '\n'
const PARAGRAPH_BREAK = '\n\n'
const BULLET = '\u2022 '
function htmlToElement(rawHtml, opts, done) {
function domToElement(dom, parent) {
if (!dom) return null
return dom.map((node, index, list) => {
if (opts.customRenderer) {
const rendered = opts.customRenderer(node, index, list)
if (rendered || rendered === null) return rendered
}
if (node.type == 'text') {
return (
<Text key={index} style={parent ? opts.styles[parent.name] : null}>
{entities.decodeHTML(node.data)}
</Text>
)
}
if (node.type == 'tag') {
if (node.name == 'img') {
const style = {
width: +node.attribs['width'] || +node.attribs['data-width'] || 0,
height: +node.attribs['height'] || +node.attribs['data-height'] || 0
}
const source = {
uri: node.attribs.src,
width: style.width,
height: style.height,
}
return (
<Image key={index} source={source} style={style} />
)
}
let linkPressHandler = null
if (node.name == 'a' && node.attribs && node.attribs.href) {
linkPressHandler = () => opts.linkHandler(entities.decodeHTML(node.attribs.href))
}
return (
<Text key={index} onPress={linkPressHandler} style={{flex: 1}}>
{node.name == 'pre' ? LINE_BREAK : null}
{node.name == 'li' ? BULLET : null}
{domToElement(node.children, node)}
{node.name == 'br' || node.name == 'li' ? LINE_BREAK : null}
{node.name == 'p' && index < list.length - 1 ? PARAGRAPH_BREAK : null}
{node.name == 'h1' || node.name == 'h2' || node.name == 'h3' || node.name == 'h4' || node.name == 'h5' ? LINE_BREAK : null}
</Text>
)
}
})
}
const handler = new htmlparser.DomHandler(function (err, dom) {
if (err) done(err)
done(null, domToElement(dom))
})
const parser = new htmlparser.Parser(handler)
parser.write(rawHtml)
parser.done()
}
export default htmlToElement