forked from michaelphines/react-native-markdown
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
81 lines (71 loc) · 1.98 KB
/
index.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
import React, { Component } from "react";
import {
View,
} from "react-native";
import SimpleMarkdown from "simple-markdown";
import rules from "./rules";
function collapseConsecutiveTextNodes(nodes) {
let collapsedNodes = [];
let previousText = "";
for (const node of nodes) {
if (node.type === "text") {
previousText += node.content;
} else if (typeof node.content === "object" && node.content.length) {
if (previousText.length) {
collapsedNodes.push({
content: previousText,
type: "text",
});
previousText = "";
}
const collapsedNode = {
...node,
content: collapseConsecutiveTextNodes(node.content),
};
collapsedNodes.push(collapsedNode);
} else {
if (previousText.length) {
collapsedNodes.push({
content: previousText,
type: "text",
});
previousText = "";
}
collapsedNodes.push(node);
}
}
if (previousText.length) {
collapsedNodes.push({
content: previousText,
type: "text",
});
}
return collapsedNodes;
}
const style = {
flexWrap: "wrap",
};
class Markdown extends Component {
constructor(props) {
super(props);
this.parser = SimpleMarkdown.parserFor({...SimpleMarkdown.defaultRules, ...rules});
this.renderer = SimpleMarkdown.reactFor(SimpleMarkdown.ruleOutput(rules, "react"));
}
render() {
const tree = this.parser(`${this.props.text}\n\n`, null, {
inline: false,
});
const collapsedTree = collapseConsecutiveTextNodes(tree);
const renderedElements = this.renderer(collapsedTree, {
onLinkPress: this.props.onLinkPress,
textStyle: Object.assign({}, { fontSize: 14, lineHeight: 19, fontWeight: "100" }, this.props.textStyle),
});
return <View style={style}>{renderedElements}</View>;
}
}
Markdown.propTypes = {
textStyle: React.PropTypes.object,
text: React.PropTypes.string,
onLinkPress: React.PropTypes.func,
};
module.exports = Markdown