forked from remarkjs/remark-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
102 lines (85 loc) · 2.56 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
'use strict';
/*
* Dependencies.
*/
var toHAST = require('mdast-util-to-hast');
var sanitize = require('hast-util-sanitize');
var toH = require('hast-to-hyperscript');
try {
var globalCreateElement = require('react').createElement;
} catch (e) { }
var own = {}.hasOwnProperty;
var TABLE_ELEMENTS = ['table', 'thead', 'tbody', 'tfoot', 'tr'];
/**
* Attach a react compiler.
*
* @param {Unified} processor - Instance.
* @param {Object?} [options]
* @param {Object?} [options.sanitize]
* - Sanitation schema.
* @param {Object?} [options.remarkReactComponents]
* - Components.
* @param {string?} [options.prefix]
* - Key prefix.
* @param {Function?} [options.createElement]
* - `h()`.
*/
function plugin(processor, options) {
var settings = options || {};
var createElement = settings.createElement || globalCreateElement;
var components = settings.remarkReactComponents || {};
var clean = settings.sanitize !== false;
var scheme = clean && (typeof settings.sanitize !== 'boolean') ? settings.sanitize : null;
var toHastOptions = settings.toHast || {};
/**
* Wrapper around `createElement` to pass
* components in.
*
* @param {string} name - Element name.
* @param {Object} props - Attributes.
* @return {ReactElement} - React element.
*/
function h(name, props, children) {
var component = own.call(components, name) ? components[name] : name;
/*
* Currently, a warning is triggered by react for
* *any* white-space in tables. So we remove the
* pretty lines for now:
* https://github.com/facebook/react/pull/7081
*/
if (children && TABLE_ELEMENTS.indexOf(component) !== -1) {
children = children.filter(function (child) {
return child !== '\n';
});
}
return createElement(component, props, children);
}
/**
* Extensible constructor.
*/
function Compiler() {}
/**
* Compile MDAST to React.
*
* @param {Node} node - MDAST node.
* @return {ReactElement} - React element.
*/
function compile(node) {
var hast = {
type: 'element',
tagName: 'div',
properties: {},
children: toHAST(node, toHastOptions).children
};
if (clean) {
hast = sanitize(hast, scheme);
}
return toH(h, hast, settings.prefix);
}
Compiler.prototype.compile = compile;
processor.Compiler = Compiler;
}
/*
* Expose `plugin`.
*/
module.exports = plugin;