-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
318 lines (270 loc) · 7.79 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
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
/**
* Styledown is available as a Node.js package.
*
* let Styledown = require('@peopledoc/styledown');
*/
const { marked } = require('marked')
const Cheerio = require('cheerio')
const extend = require('util')._extend
const mdextract = require('mdextract')
const hljs = require('highlight.js')
const { version } = require('./package.json')
const { readFileSync } = require('fs')
const default_conf = require('./lib/default_conf.js')
const { beautifyHTML } = require('./lib/utils')
const {
addClasses,
sectionize,
unpackExample,
processConfig,
removeConfig,
isolateTextBlocks
} = require('./lib/filters')
const { htmlize, prefixClass } = require('./lib/utils')
class Styledown {
/***
* Styledown() : new Styledown(source, [options])
* Parses the source `source` into a Styledown document. `source` can be a
* Markdown document.
*
* doc = new Styledown(markdown);
* doc.toHTML();
*
* You may also use `Styledown.parse()` as a shorthand.
*/
constructor(src, options) {
this.options = extend(extend({}, Styledown.defaultOptions), options || {})
let raws = this.extract(src)
this.raws = this.process(raws, this.options)
}
/**
* toHTML() : doc.toHTML()
* Returns the full HTML source based on the Styledown document.
*
* doc.toHTML()
* => "<!doctype html><html>..."
*/
toHTML() {
let html = this.raws.reduce((html, raw) => `${html}${raw.html}`, '')
let config = this.raws.reduce((finalConfig, raw) => {
return extend(finalConfig, raw.config)
}, this.options)
if (config.head !== false) {
// Unpack template
let $ = Cheerio.load(htmlize(config.template))
$('body').append(htmlize(config.body))
$('[sg-content]').append(html).removeAttr('sg-content')
$('html, body').addClass(config.prefix)
$('head').append(htmlize(config.head))
html = $.html()
}
html = html.trim()
// cheerio output tends to have a bunch of extra newlines. kill them.
html = html.replace(/\n\n+/g, "\n\n")
return html
}
/**
* toBareHTML() : doc.toBareHTML()
* Returns the bare HTML without the head/body templates.
*
* doc.toBareHTML()
* => "<div><h3>Your document</h3>..."
*/
toBareHTML() {
return this.raws.reduce((html, raw) => {
return `${html}${raw.html}`
}, '')
}
/**
* @typedef ParsedFile
* @property {string} filePath - Path to the file relative to process.cwd()
* @property {string} html - file content converted to html using marked
* @property {string} raw - File content without the css/scss...
*/
/**
* Extract Markdown content from given `src` an generate html with it.
*
* @private
* @argument {string|string[]} src
* @returns {ParsedFile}
*/
extract(src) {
if (typeof src === 'string') {
return [{
filePath: '.',
html: marked(src),
src
}]
}
if (Array.isArray(src)) {
return src.map((file) => {
if (this.options.inline || file.name && file.name.match(/(sass|scss|styl|less|css)$/)) {
let src = mdextract(file.data, { lang: 'css' }).toMarkdown()
return {
filePath: file.name,
html: marked(src),
src
}
} else {
return {
filePath: file.name,
src: file.data,
html: marked(file.data)
}
}
})
}
}
/**
* Process ParsedFiles to generate documentation pages with HTML highlighting and Pug rendering
*
* @private
* @argument {ParsedFile[]} raws
* @argument {object} options
*/
process(raws, options) {
return raws.map((raw) => {
let $ = Cheerio.load(raw.html)
let config = processConfig(raw.src, options)
removeConfig($)
let highlightHTML = this.highlightHTML.bind(this)
let p = this.prefix.bind(this)
// let pre = this.options.prefix
addClasses($, p)
sectionize($, 'h3', p, { 'class': p('block') })
sectionize($, 'h2', p, { 'class': p('section'), until: 'h1, h2' })
$('pre').each(function () {
unpackExample($(this), p, highlightHTML, raw.filePath)
})
isolateTextBlocks($, p)
return {
filePath: raw.filePath,
src: raw.src,
html: $.html(),
config
}
})
}
// no use at the moment
// /**
// * prettyprint() : doc.prettyprint(html)
// * (private) Reindents given `html` based on the indent size option.
// *
// * doc.prettyprint('<div><a>hello</a></div>')
// * => "<div>\n <a>hello</a>\n</div>"
// */
// prettyprint() {
// let html = this.toHTML()
// let config = this.raws.reduce((finalConfig, raw) => {
// return extend(finalConfig, raw.config)
// }, this.options)
// return beautifyHTML(html, { config })
// }
/**
* highlightHTML():
* (private) Syntax highlighting helper
*/
highlightHTML(html) {
let newHtml = beautifyHTML(html)
let code = hljs.highlight(newHtml, { language: 'html' })
return code.value
}
/**
* prefix():
* (private) Prefix classnames. Takes `options.prefix` into account.
*
* prefix('block')
* => 'sg-block'
*/
prefix(klass) {
return klass ?
prefixClass(klass, this.options.prefix) :
this.options.prefix
}
}
/**
* Styledown.parse() : Styledown.parse(source, [options])
* Generates HTML from a given `source`.
*
* Styledown.parse('### hello *world*');
* => "<!doctype html><html>..."
*
* `source` can be a String or an Array. as a string, it's assumed to be a
* Markdown document. As an array, it's assumed to be a list of files. It's
* expected that it contains objects with `name` and `data` keys.
*
* In array mode, Styledown treats each file differently. Inline comments are
* extracted from those with that end in CSS extensions (css, less, sass, etc),
* while the rest are assumed to be Markdown documents.
*
* let docs = [
* { name: 'css/style.css', data: '...' },
* { name: 'config.md', data: '...' }
* ];
*
* Styledown.parse(docs);
* => "<!doctype html><html>..."
*
* You may pass `options` as the second parameter. Available options are:
*
* ~ prefix (String): prefix for classnames. Defaults to `sg`.
* ~ template (String): HTML template. Defaults to a simple HTML template.
* ~ head (String): HTML to put in the head. Default to `false`.
* ~ body (String): HTML to put in the body. Defaults to `<div sg-content></div>`.
* ~ indentSize (Number): Number of spaces to indent. Defaults to `2`.
* ~ inline (Boolean): if `true`, then inline CSS mode is forced.
*
* This is shorthand for `new Styledown().toHTML()`. You can use `Styledown` as a class.
*/
Styledown.parse = function (source, options) {
return new Styledown(source, options).toHTML()
}
/**
* Styledown.version:
* The version number in semver format.
*/
Styledown.version = version
/**
* Styledown.defaults:
* The returns the default configuration file, JS file and CSS files.
*
* Styledown.defaults.conf()
* Styledown.defaults.js()
* Styledown.defaults.css()
*/
Styledown.defaults = {
conf() {
return default_conf
},
js() {
return readFileSync(`${__dirname }/assets/styledown.js`)
},
css() {
return readFileSync(`${__dirname }/assets/styledown.css`)
}
}
Styledown.defaultOptions = {
/* HTML template */
template: [
"<!doctype html>",
"<html>",
"<head>",
"<meta charset='utf-8'>",
"<title>Styledown</title>",
"</head>",
"<body>",
"</body>",
"</html>"
].join("\n"),
/* Things to put into `head` */
head: false,
/* Force inline mode */
inline: false,
/* Things to put into `body` */
body: "<div sg-content></div>",
/* Prefix for classnames */
prefix: 'sg',
/* Indentation spaces */
indentSize: 2
}
module.exports = Styledown