forked from ember-learn/ember-jsonapi-docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarkup.js
118 lines (100 loc) · 2.49 KB
/
markup.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
import marked from 'marked'
import hljs from 'highlight.js'
import cheerio from 'cheerio'
marked.setOptions({
highlight: code => hljs.highlightAuto(code).value,
})
export default doc => {
doc.data.forEach(({ id, attributes }) => {
console.log(`Generating markup for ${id}`)
let description = attributes.description
if (description) {
attributes.description = highlight(description)
}
replaceDescriptionFor(attributes.methods)
replaceDescriptionFor(attributes.properties)
replaceDescriptionFor(attributes.events)
})
return doc
}
function replaceDescriptionFor(items) {
if (items) {
items.forEach(item => {
let itemDescription = item.description
if (itemDescription) {
item.description = highlight(itemDescription)
}
})
}
}
function highlight(description) {
if (description) {
description = description.replace(/&#(\d+);/g, function(match, dec) {
return String.fromCharCode(dec)
})
}
let markedup = removeHLJSPrefix(marked(description))
let $ = cheerio.load(markedup)
let codeBlocks = $('pre code')
codeBlocks.each((i, el) => {
let element = $(el)
let klass = element.attr('class')
let lang = ''
let tableHeader = ''
if (klass) {
let type = klass.split('-').pop()
if (isFile(type)) {
tableHeader = `
<thead>
<tr>
<td colspan="2">${type}</td>
</tr>
</thead>`
}
lang = determineLanguage(type)
}
let lines = element.html().split('\n')
// get rid of empty blank line
if (lines[lines.length - 1].trim() === '') {
lines.pop()
}
let wrappedLines = `<pre>${lines.join('\n')}</pre>`
let lineNumbers = lines.map((_, i) => `${i + 1}\n`).join('')
element.parent().after(`<div class="highlight ${lang}">
<div class="ribbon"></div>
<div class="scroller">
<table class="CodeRay">${tableHeader}
<tbody>
<tr>
<td class="line-numbers"><pre>${lineNumbers}</pre></td>
<td class="code">${wrappedLines}</td>
</tr>
</tbody>
</table>
</div>
</div>
`)
element.parent().remove()
})
return $.html()
}
function determineLanguage(maybeFileName) {
const lang = maybeFileName.split('.').pop()
switch (lang) {
case 'js':
case 'javascript':
return 'javascript'
case 'ts':
return 'typescript'
case 'hbs':
return 'handlebars'
default:
return lang
}
}
function removeHLJSPrefix(string) {
return string.replace(/hljs-/g, '')
}
function isFile(string) {
return /\./.test(string)
}