forked from mientjan/react-native-markdown-renderer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAstRenderer.js
More file actions
76 lines (65 loc) · 1.74 KB
/
AstRenderer.js
File metadata and controls
76 lines (65 loc) · 1.74 KB
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
import React, { Component, PropTypes } from "react";
import { Text, View } from "react-native";
import getUniqueID from "./util/getUniqueID";
export function rootRenderRule(children, styles) {
return <View key={getUniqueID()} style={styles.root}>{children}</View>;
}
/**
*
*/
export default class AstRenderer {
/**
*
* @param {Object.<string, function>} renderRules
* @param {any} style
*/
constructor(renderRules, style, onLinkPress) {
this._renderRules = renderRules;
this._style = style;
this._onLinkPress = onLinkPress;
}
/**
*
* @param {string} type
* @return {string}
*/
getRenderFunction = type => {
const renderFunction = this._renderRules[type];
if (!renderFunction) {
throw new Error(
`${type} renderRule not defined example: <Markdown rules={renderRules}>`
);
}
return renderFunction;
};
/**
*
* @param node
* @param parentNodes
* @return {*}
*/
renderNode = (node, parentNodes) => {
const renderFunction = this.getRenderFunction(node.type);
const parents = [...parentNodes];
parents.unshift(node);
if (node.type === "text") {
return renderFunction(node, [], parentNodes, this._style);
}
const children = node.children.map(value => {
return this.renderNode(value, parents);
});
if (node.type === "link" || node.type === "blocklink") {
return renderFunction(node, children, parentNodes, this._style, this._onLinkPress);
}
return renderFunction(node, children, parentNodes, this._style);
};
/**
*
* @param nodes
* @return {*}
*/
render = nodes => {
const children = nodes.map(value => this.renderNode(value, []));
return rootRenderRule(children, this._style);
};
}