-
Notifications
You must be signed in to change notification settings - Fork 63
/
index.js
323 lines (263 loc) · 7.43 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
319
320
321
322
323
var Marked = require('marked');
var Cheerio = require('cheerio');
var extend = require('util')._extend;
module.exports = Styledown;
var Filters = Styledown.filters = {};
/**
* Document.
*/
function Styledown (src, options) {
this.raw = src;
this.options = extend(extend({}, Styledown.defaults), options || {});
this.$ = Cheerio.load(Marked(src));
Filters.processConfig(src, this.options);
Filters.removeConfig(this.$);
var pre = this.options.prefix;
Filters.addClasses(this.$, this.options);
Filters.sectionize(this.$, 'h3', { 'class': pre+'-block', prefix: pre });
Filters.sectionize(this.$, 'h2', { 'class': pre+'-section', until: 'h1, h2', prefix: pre });
Filters.unpackExamples(this.$, this.options, this._highlightHTML.bind(this));
Filters.isolateTextBlocks(this.$, pre);
}
Styledown.defaults = {
/**
* 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,
body: "<div sg-content></div>",
/**
* Prefix for classnames
*/
prefix: 'sg',
/**
* Indentation spaces
*/
indentSize: 2
};
/**
* Shorthand for parsing.
*/
Styledown.parseSync = function (source, options) {
return new Styledown(source, options).toHTML();
};
Styledown.parse = Styledown.parseSync;
Styledown.prototype = {
/**
* Converts to HTML
*/
toHTML: function() {
var html = this.$.html();
if (this.options.head !== false) {
// Unpack template
var $ = Cheerio.load(this.options.template);
$('body').append(htmlize(this.options.body));
$('[sg-content]').append(html).removeAttr('sg-content');
$('html, body').addClass(this.options.prefix);
$('head').append(htmlize(this.options.head));
html = $.html();
}
html = this._prettyprint(html);
return html;
},
/**
* Reindents HTML based on indent size option
*/
_prettyprint: function (html) {
var Html = require('html');
return Html.prettyPrint(html, { indent_size: this.options.indentSize });
},
/**
* Syntax highlighting helper
*/
_highlightHTML: function (html) {
var Hljs = require('highlight.js');
html = this._prettyprint(html);
html = Hljs.highlight('html', html).value;
return html;
}
};
/**
* Filters mixin
*/
extend(Filters, {
/**
* Adds HTML classnames to things
*/
addClasses: function ($, options) {
var prefix = options.prefix;
$("*").addClass(prefix);
},
/**
* Unpacks `pre` blocks into examples.
*/
unpackExamples: function ($, options, highlight) {
var pre = options.prefix;
var klass;
$('pre').each(function() {
var code = this.text();
var block = Filters.parseCodeText(code);
var tags = Filters.parseTags(block.tag);
if (tags.example) {
var html = htmlize(block.code);
var canvas = "<div class='"+pre+"-canvas'>"+html+"</div>";
var codeblock = "<pre class='"+pre+"-code'>"+highlight(html)+"</pre>";
var $block = Cheerio.load("<div class='"+pre+"-example'>" + canvas + codeblock + "</div>");
if (tags['class']) {
klass = Filters.prefixClass(tags['class'], pre);
$block(':root').addClass(klass);
}
this.replaceWith($block.root());
} else {
klass = this.find('code').attr('class');
var m = klass.match(/lang-([a-z]+)/);
if (m) {
var lang = m[1];
var Hljs = require('highlight.js');
this.html(Hljs.highlight(lang, this.text()).value);
this.addClass(pre+'-lang-'+lang);
this.addClass(pre+'-code');
}
}
});
},
/**
* Prefixes classnames.
*
* prefixClass('white', 'sg') => 'sg-white'
* prefixClass('pad dark', 'sg') => 'sg-pad sg-dark'
*/
prefixClass: function (klass, prefix) {
return klass.split(' ').map(function (n) {
return n.length > 0 ? (prefix + '-' + n) : n;
}).join(' ');
},
/**
* Get the tags and code out of the code text.
*
* parseCodeText('@example\nhello')
* => { tag: 'example', code: 'hello' }
*
* parseCodeText('hello')
* => { tag: null, code: 'hello' }
*/
parseCodeText: function (code) {
var m = code.trim().match(/^@([^\n]+)/);
if (m) return { tag: m[1], code: code.substr(m[1].length+2) };
return { tag: null, code: code };
},
/**
* Break it apart into sections.
*
* Puts <h3> blocks into <section> blocks.
*/
sectionize: function ($, tag, options) {
options = extend({
'class': '',
'until': 'h1, h2, h3, section',
'prefix': ''
}, options);
$(tag).each(function (i) {
var $heading = this;
var $extras = $heading.nextUntil(options.until);
$heading.before("<section class='"+options.class+"'>");
var $div = $("section."+options.class).eq(-1);
$div.addClass(options.prefix + '-section-' + $heading.attr('id'));
$div.append($heading.remove());
$div.append($extras.remove());
});
},
/**
* Remove the configuration block.
*
* Removes the "Styleguide options" block from the DOM in `$`.
*/
removeConfig: function ($) {
var $h1 = $('h1#styleguide-options');
$h1.nextUntil('h1').remove();
$h1.remove();
},
/**
* Process the configuration block
*/
processConfig: function (src, options) {
var Mdconf = require('./lib/mdconf');
try {
var data = Mdconf(src, { normalizer: 'camelcase' });
data = (data && data.styleguideOptions);
if (data) extend(options, data);
} catch (e) {
// Don't bother if mdconf fails.
}
},
/**
* Parse tags
*/
parseTags: function (str) {
if (typeof str !== 'string') return {};
var m;
var obj = {};
str = str.trim();
while (true) {
if (m = str.match(/^\.([a-z\-]+)\s*/)) {
if (!obj["class"]) obj["class"] = [];
obj["class"].push(m[1]);
} else if (m = str.match(/^([a-z\-]+)="([^"]+)"\s*/)) {
obj[m[1]] = m[2];
} else if (m = str.match(/^([a-z\-]+)='([^']+)'\s*/)) {
obj[m[1]] = m[2];
} else if (m = str.match(/^([a-z\-]+)=([^\s]+)\s*/)) {
obj[m[1]] = m[2];
} else if (m = str.match(/^([a-z\-]+)\s*/)) {
obj[m[1]] = true;
} else {
if (obj["class"]) obj["class"] = obj["class"].join(' ');
return obj;
}
// Trim
str = str.substr(m[0].length);
}
},
/**
* Isolates text blocks
*/
isolateTextBlocks: function ($, prefix) {
$('.'+prefix+'-block').each(function() {
// Check if there's an example block.
// $('.sg-example', this).length doesn't work.
var noExample = (this.html().indexOf(prefix+'-example') === -1);
var noCode = (this.html().indexOf(prefix+'-code') === -1);
if (noExample && noCode) return;
var $first = $('h3', this);
var $text = $first.nextUntil('.'+prefix+'-example, .'+prefix+'-code');
var $block = Cheerio.load('<div>');
this.prepend($block.root());
$block(':root').addClass(prefix + '-text');
$block(':root').append($first);
$block(':root').append($text);
});
}
});
function htmlize (src) {
// Mdconf processes them as arrays
if (src.constructor === Array) src = src[0];
if (src.substr(0, 1) === '<') {
return src;
} else {
var Jade = require('jade');
return Jade.render(src);
}
}