forked from jsdf/react-native-htmlview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
htmlToElement.js
114 lines (100 loc) · 2.89 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import React from 'react';
import {
Text,
} from 'react-native';
import htmlparser from 'htmlparser2-without-node-native';
import entities from 'entities';
import AutoSizedImage from './AutoSizedImage';
const LINE_BREAK = '\n';
const PARAGRAPH_BREAK = '\n\n';
const BULLET = '\u2022 ';
const Img = props => {
const width = Number(props.attribs['width']) || Number(props.attribs['data-width']) || 0;
const height = Number(props.attribs['height']) || Number(props.attribs['data-height']) || 0;
const imgStyle = {
width,
height,
};
const source = {
uri: props.attribs.src,
width,
height,
};
return (
<AutoSizedImage source={source} style={imgStyle} />
);
};
export default 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, parent, domToElement);
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') {
return (
<Img key={index} attribs={node.attribs} />
);
}
let linkPressHandler = null;
if (node.name == 'a' && node.attribs && node.attribs.href) {
linkPressHandler = () => opts.linkHandler(entities.decodeHTML(node.attribs.href));
}
let linebreakBefore = null;
let linebreakAfter = null;
if (opts.addLineBreaks) {
switch (node.name) {
case 'pre':
linebreakBefore = LINE_BREAK;
break;
case 'p':
if (index < list.length - 1) {
linebreakAfter = PARAGRAPH_BREAK;
}
break;
case 'br':
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
linebreakAfter = LINE_BREAK;
break;
}
}
let listItemPrefix = null;
if (node.name == 'li') {
if (parent.name == 'ol') {
listItemPrefix = `${index + 1}. `;
} else if (parent.name == 'ul') {
listItemPrefix = BULLET;
}
}
return (
<Text key={index} onPress={linkPressHandler}>
{linebreakBefore}
{listItemPrefix}
{domToElement(node.children, node)}
{linebreakAfter}
</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();
}