-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcommonmark-react-native-renderer.js
456 lines (394 loc) · 14.7 KB
/
commonmark-react-native-renderer.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
'use strict';
var React = require('react');
import {
Text,
View,
Linking
} from 'react-native'
var assign = require('lodash.assign');
var isPlainObject = require('lodash.isplainobject');
var xssFilters = require('xss-filters');
var pascalCase = require('pascalcase');
import defaultStyles from './styles';
const openUrl = (url) => {
Linking.openURL(url).catch(error => console.warn('An error occurred: ', error))
}
var typeAliases = {
blockquote: 'block_quote',
thematicbreak: 'thematic_break',
htmlblock: 'html_block',
htmlinline: 'html_inline',
codeblock: 'code_block',
hardbreak: 'linebreak'
};
var defaultRenderers = {
block_quote: (props) => {
let newProps = assign({}, props)
let style = newProps.style
delete newProps.style
return <View style={style}><Text {...newProps}></Text></View>
},
emph: 'em',
linebreak: 'br',
image: 'img',
item: 'li',
link: 'a',
paragraph: 'p',
strong: 'strong',
thematic_break: 'hr', // eslint-disable-line camelcase
html_block: HtmlRenderer, // eslint-disable-line camelcase
html_inline: HtmlRenderer, // eslint-disable-line camelcase
list: function List(props) {
var tag = props.type.toLowerCase() === 'bullet' ? 'ul' : 'ol';
var attrs = getCoreProps(props);
if (props.start !== null && props.start !== 1) {
attrs.start = props.start.toString();
}
return createElement(tag, attrs, props.children);
},
code_block: function CodeBlock(props) { // eslint-disable-line camelcase
var className = props.language && 'language-' + props.language;
var code = createElement('code', { className: className }, props.literal);
return createElement('pre', getCoreProps(props), code);
},
code: function Code(props) {
return createElement('code', getCoreProps(props), props.children);
},
heading: function Heading(props) {
return createElement('h' + props.level, getCoreProps(props), props.children);
},
text: null,
softbreak: null
};
var coreTypes = Object.keys(defaultRenderers);
function getCoreProps(props) {
return {
'key': props.nodeKey,
'data-sourcepos': props['data-sourcepos']
};
}
function normalizeTypeName(typeName) {
var norm = typeName.toLowerCase();
var type = typeAliases[norm] || norm;
return typeof defaultRenderers[type] !== 'undefined' ? type : typeName;
}
function normalizeRenderers(renderers) {
return Object.keys(renderers || {}).reduce(function(normalized, type) {
var norm = normalizeTypeName(type);
normalized[norm] = renderers[type];
return normalized;
}, {});
}
function HtmlRenderer(props) {
var nodeProps = props.escapeHtml ? {} : { dangerouslySetInnerHTML: { __html: props.literal } };
var children = props.escapeHtml ? [props.literal] : null;
if (props.escapeHtml || !props.skipHtml) {
return createElement(props.isBlock ? 'div' : 'span', nodeProps, children);
}
}
function isGrandChildOfList(node) {
var grandparent = node.parent.parent;
return (
grandparent &&
grandparent.type.toLowerCase() === 'list' &&
grandparent.listTight
);
}
function addChild(node, child) {
var parent = node;
do {
parent = parent.parent;
} while (!parent.react);
parent.react.children.push(child);
}
function createElement(tagName, props, children) {
var nodeChildren = Array.isArray(children) && children.reduce(reduceChildren, []);
var args = [tagName, props].concat(nodeChildren || children);
return React.createElement.apply(React, args);
}
function reduceChildren(children, child) {
var lastIndex = children.length - 1;
if (typeof child === 'string' && typeof children[lastIndex] === 'string') {
children[lastIndex] += child;
} else {
children.push(child);
}
return children;
}
function flattenPosition(pos) {
return [
pos[0][0], ':', pos[0][1], '-',
pos[1][0], ':', pos[1][1]
].map(String).join('');
}
// For some nodes, we want to include more props than for others
function getNodeProps(node, key, opts, renderer) {
var props = { key: key }, undef;
// `sourcePos` is true if the user wants source information (line/column info from markdown source)
if (opts.sourcePos && node.sourcepos) {
props['data-sourcepos'] = flattenPosition(node.sourcepos);
}
let parent = node.parent;
var type = normalizeTypeName(node.type);
switch (type) {
case 'block_quote':
props.style = opts.styles.blockQuote
break;
case 'code_block':
var codeInfo = node.info ? node.info.split(/ +/) : [];
if (codeInfo.length > 0 && codeInfo[0].length > 0) {
props.language = codeInfo[0];
props.codeinfo = codeInfo;
}
props.children = node.literal;
props.style = opts.styles.codeBlock;
break;
case 'code':
props.children = node.literal;
props.inline = true;
break;
case 'heading':
props.style = opts.styles[type]
props.level = node.level;
break;
case 'softbreak':
props.softBreak = opts.softBreak;
break;
case 'link':
let url = opts.transformLinkUri ? opts.transformLinkUri(node.destination) : node.destination;
props.title = node.title || undef;
if (opts.linkTarget) {
props.target = opts.linkTarget;
}
props.onPress = () => openUrl(url)
props.style = url.match(/@/) ? opts.styles.mailTo : opts.styles.link
break;
case 'image':
props.source = {uri: opts.transformImageUri ? opts.transformImageUri(node.destination) : node.destination};
props.style = {width: 200, height: 300};
// Commonmark treats image description as children. We just want the text
node.react.children = undef;
break;
case 'list':
props.style = opts.styles[type]
props.start = node.listStart;
props.type = node.listType;
props.tight = node.listTight;
break;
case 'text':
props.children = node.literal;
props.style = opts.styles[type]
console.log('text parent.type', parent.type)
switch (parent.type) {
case 'heading':
props.style = assign({}, opts.styles[parent.type + parent.level], props.style)
break;
}
break;
case 'paragraph':
props.style = opts.styles[type]
break;
case 'item':
props.style = opts.styles.listItem;
break;
default:
props.style = opts.styles[type]
break;
}
if (typeof renderer !== 'string') {
props.literal = node.literal;
}
var children = props.children || (node.react && node.react.children);
if (Array.isArray(children)) {
props.children = children.reduce(reduceChildren, []) || null;
}
return props;
}
function getPosition(node) {
if (!node) {
return null;
}
if (node.sourcepos) {
return flattenPosition(node.sourcepos);
}
return getPosition(node.parent);
}
function renderNodes(block) {
var walker = block.walker();
// Softbreaks are usually treated as newlines, but in HTML we might want explicit linebreaks
var softBreak = (
this.softBreak === 'br' ?
React.createElement('br') :
this.softBreak
);
var propOptions = {
sourcePos: this.sourcePos,
escapeHtml: this.escapeHtml,
skipHtml: this.skipHtml,
transformLinkUri: this.transformLinkUri,
transformImageUri: this.transformImageUri,
softBreak: softBreak,
linkTarget: this.linkTarget,
styles: this.styles,
listItemBulletType: this.listItemBulletType
};
var e, node, entering, leaving, type, doc, key, nodeProps, prevPos, prevIndex = 0;
while ((e = walker.next())) {
var pos = getPosition(e.node.sourcepos ? e.node : e.node.parent);
if (prevPos === pos) {
key = pos + prevIndex;
prevIndex++;
} else {
key = pos;
prevIndex = 0;
}
prevPos = pos;
entering = e.entering;
leaving = !entering;
node = e.node;
type = normalizeTypeName(node.type);
console.log(type)
nodeProps = null;
// If we have not assigned a document yet, assume the current node is just that
if (!doc) {
doc = node;
node.react = { children: [] };
continue;
} else if (node === doc) {
// When we're leaving...
continue;
}
// In HTML, we don't want paragraphs inside of list items
if (type === 'paragraph' && isGrandChildOfList(node)) {
continue;
}
// If we're skipping HTML nodes, don't keep processing
if (this.skipHtml && (type === 'html_block' || type === 'html_inline')) {
continue;
}
var isDocument = node === doc;
var disallowedByConfig = this.allowedTypes.indexOf(type) === -1;
var disallowedByUser = false;
// Do we have a user-defined function?
var isCompleteParent = node.isContainer && leaving;
var renderer = this.renderers[type];
if (this.allowNode && (isCompleteParent || !node.isContainer)) {
var nodeChildren = isCompleteParent ? node.react.children : [];
nodeProps = getNodeProps(node, key, propOptions, renderer);
disallowedByUser = !this.allowNode({
type: pascalCase(type),
renderer: this.renderers[type],
props: nodeProps,
children: nodeChildren
});
}
if (!isDocument && (disallowedByUser || disallowedByConfig)) {
if (!this.unwrapDisallowed && entering && node.isContainer) {
walker.resumeAt(node, false);
}
continue;
}
var isSimpleNode = type === 'text' || type === 'softbreak';
if (typeof renderer !== 'function' && !isSimpleNode && typeof renderer !== 'string') {
throw new Error(
'Renderer for type `' + pascalCase(node.type) + '` not defined or is not renderable'
);
}
if (node.isContainer && entering) {
let containerProps = {}
let containerChildren = []
switch (node.parent.type) {
case 'list':
containerProps.style = this.styles.listItem
if (node.listType == 'bullet') {
containerChildren = [React.createElement(Text, {key: getPosition(node) + '_bullet'}, `${this.listItemBulletType}`)]
} else {
containerChildren = [React.createElement(Text, {key: getPosition(node) + '_bullet'}, node.listStart + '. ')]
}
break;
}
node.react = {
component: renderer,
props: containerProps,
children: containerChildren
};
} else {
var childProps = nodeProps || getNodeProps(node, key, propOptions, renderer);
if (renderer) {
childProps = typeof renderer === 'string'
? childProps
: assign(childProps, {nodeKey: childProps.key});
addChild(node, React.createElement(renderer, childProps));
} else if (type === 'text') {
addChild(node, node.literal);
} else if (type === 'softbreak') {
addChild(node, softBreak);
}
}
}
return doc.react.children;
}
function defaultLinkUriFilter(uri) {
var url = uri.replace(/file:\/\//g, 'x-file://');
// React does a pretty swell job of escaping attributes,
// so to prevent double-escaping, we need to decode
return decodeURI(xssFilters.uriInDoubleQuotedAttr(url));
}
function ReactNativeRenderer(options) {
var opts = options || {};
if (opts.allowedTypes && opts.disallowedTypes) {
throw new Error('Only one of `allowedTypes` and `disallowedTypes` should be defined');
}
if (opts.allowedTypes && !Array.isArray(opts.allowedTypes)) {
throw new Error('`allowedTypes` must be an array');
}
if (opts.disallowedTypes && !Array.isArray(opts.disallowedTypes)) {
throw new Error('`disallowedTypes` must be an array');
}
if (opts.allowNode && typeof opts.allowNode !== 'function') {
throw new Error('`allowNode` must be a function');
}
var linkFilter = opts.transformLinkUri;
if (typeof linkFilter === 'undefined') {
linkFilter = defaultLinkUriFilter;
} else if (linkFilter && typeof linkFilter !== 'function') {
throw new Error('`transformLinkUri` must either be a function, or `null` to disable');
}
var imageFilter = opts.transformImageUri;
if (typeof imageFilter !== 'undefined' && typeof imageFilter !== 'function') {
throw new Error('`transformImageUri` must be a function');
}
if (opts.renderers && !isPlainObject(opts.renderers)) {
throw new Error('`renderers` must be a plain object of `Type`: `Renderer` pairs');
}
var allowedTypes = (opts.allowedTypes && opts.allowedTypes.map(normalizeTypeName)) || coreTypes;
if (opts.disallowedTypes) {
var disallowed = opts.disallowedTypes.map(normalizeTypeName);
allowedTypes = allowedTypes.filter(function filterDisallowed(type) {
return disallowed.indexOf(type) === -1;
});
}
return {
sourcePos: Boolean(opts.sourcePos),
softBreak: opts.softBreak || '\n',
renderers: assign({}, defaultRenderers, normalizeRenderers(opts.renderers)),
escapeHtml: Boolean(opts.escapeHtml),
skipHtml: Boolean(opts.skipHtml),
transformLinkUri: linkFilter,
transformImageUri: imageFilter,
allowNode: opts.allowNode,
allowedTypes: allowedTypes,
unwrapDisallowed: Boolean(opts.unwrapDisallowed),
render: renderNodes,
styles: assign({}, defaultStyles, opts.styles),
linkTarget: opts.linkTarget || false,
listItemBulletType: opts.listItemBulletType || '\u2022 '
};
}
ReactNativeRenderer.uriTransformer = defaultLinkUriFilter;
ReactNativeRenderer.types = coreTypes.map(pascalCase);
ReactNativeRenderer.renderers = coreTypes.reduce(function(renderers, type) {
renderers[pascalCase(type)] = defaultRenderers[type];
return renderers;
}, {});
module.exports = ReactNativeRenderer;