UNPKG

1.96 kBJavaScriptView Raw
1'use strict';
2
3const unescape = require('lodash.unescape');
4const marked = require('marked');
5const chalk = require('chalk');
6const index = require('./index');
7
8const allElements = [
9 'blockquote', 'html', 'strong', 'em', 'br', 'del',
10 'heading', 'hr', 'image', 'link', 'list', 'listitem',
11 'paragraph', 'strikethrough', 'table', 'tablecell', 'tablerow'
12];
13
14function unhtml(text){
15 return unescape(text);
16}
17
18exports.parse = (markdown) => {
19 // Creating the page structure
20 let page = {
21 name: '',
22 description: '',
23 examples: [],
24 seeAlso: []
25 };
26 // Initializing the markdown renderer
27 let r = new marked.Renderer();
28
29 // ignore all syntax by default
30 allElements.forEach((e) => {
31 r[e] = () => { return ''; };
32 });
33
34 // Overriding the different elements to incorporate the custom tldr format
35
36 r.codespan = (text) => {
37 if (index.hasPage(text) && text !== page.name) {
38 if (page.seeAlso.indexOf(text) < 0) {
39 page.seeAlso.push(text);
40 }
41 }
42 let example = page.examples[page.examples.length-1];
43 // If example exists and a code is already not added
44 if (example && !example.code) {
45 example.code = unhtml(text);
46 }
47 return text;
48 };
49
50
51 // paragraphs just pass through (automatically created by new lines)
52 r.paragraph = (text) => {
53 return text;
54 };
55
56 r.heading = (text, level) => {
57 if (level === 1) {
58 page.name = text.trim();
59 }
60 return text;
61 };
62
63 r.blockquote = (text) => {
64 page.description += unhtml(text);
65 return text;
66 };
67
68 r.strong = (text) => {
69 return chalk.bold(text);
70 };
71
72 r.em = (text) => {
73 return chalk.italic(text);
74 };
75
76 r.listitem = (text) => {
77 page.examples.push({
78 description: unhtml(text)
79 });
80 return text;
81 };
82
83 marked(markdown, {
84 renderer: r,
85 sanitize: true
86 });
87
88 page.examples = page.examples.filter((example) => {
89 return example.description && example.code;
90 });
91
92 return page;
93};