-
Notifications
You must be signed in to change notification settings - Fork 9
/
html.js
331 lines (298 loc) · 9.03 KB
/
html.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
'use strict';
// stdlib
var fs = require('fs');
var path = require('path');
// backward compatibility for Node <= 0.6.x
var pathExists = fs.exists || path.exists;
// 3rd-party
var FsTools = require('fs-tools');
var Jade = require('jade');
var md2html = require('marked');
// internal
var extend = require('../common').extend;
var assets = require('./html/assets');
////////////////////////////////////////////////////////////////////////////////
module.exports.name = 'html';
module.exports.args = [
{
keys: ['--html-skin'],
opts: {
help: 'Custom templates',
dest: 'htmlSkin',
metavar: 'PATH',
nargs: 1,
defaultValue: path.join(__dirname, 'html', 'skins', 'default')
}
},
{
keys: ['--ribbon'],
opts: {
help: 'Add "ribbon" to generated docs',
dest: 'ribbon',
nargs: 0,
action: 'storeTrue',
defaultValue: false
}
},
{
keys: ['--ribbon-link'],
opts: {
help: 'Ribbon link URL',
dest: 'ribbonLink',
metavar: 'URL',
nargs: 1,
defaultValue: false
}
},
{
keys: ['--ribbon-image'],
opts: {
help: 'Ribbon image URL',
dest: 'ribbonImage',
metavar: 'URL',
nargs: 1,
defaultValue: false
}
},
{
keys: ['--ribbon-title'],
opts: {
help: 'Ribbon link title',
dest: 'ribbonTitle',
metavar: 'TEXT',
nargs: 1,
defaultValue: 'Fork me on GitHub'
}
}
];
module.exports.render = function (ndoc, options, callback) {
var file, str, fn, packageJson, list, id, obj;
// prepare rendering function
// TODO: store it for further reuse, and get rid of jade dependency?
file = path.join(options.htmlSkin, 'templates', 'layout.jade');
str = fs.readFileSync(file, 'utf8');
fn = Jade.compile(str, {
filename: file,
pretty: false
});
// get GitHub ribbon options
if (options.ribbon) {
if (!options.ribbonLink) {
try {
packageJson = fs.readFileSync('./package.json', 'utf8');
packageJson = JSON.parse(packageJson);
} catch (e) {
packageJson = {};
}
if (typeof packageJson.repository !== 'undefined') {
options.ribbonLink = packageJson.repository.url;
if (options.ribbonLink.match(/.*\.git$/)) {
// https://github.com/nodeca/ndoc.git ?
options.ribbonLink = options.ribbonLink.replace(/\.git$/, '');
}
if (options.ribbonLink.match(/^git:\/\/github\.com.*/)) {
// git://github.com/Sannis/ndoc.git?
options.ribbonLink = options.ribbonLink.replace(/^git:/, 'https:');
}
// TODO: More cases?
} else if (typeof packageJson.homepage !== 'undefined') {
options.ribbonLink = packageJson.homepage;
if (options.ribbonLink.match(/^https?:\/\/github\.com\/.*?\/.*?\/?/)) {
// git://github.com/Sannis/ndoc.git?
options.ribbonLink = options.ribbonLink.replace(/^(https?:\/\/github\.com\/.+?\/.+?)(\/.*)?$/, '$1');
}
// TODO: More cases?
}
if (!options.ribbonLink.match(/^https?:\/\/.*/)) {
callback('Cannot determine project repository URL using package.json. Use --ribbon-link option.');
return;
}
}
if (!options.ribbonImage) {
options.ribbonImage = path.join(options.htmlSkin, 'assets', 'images', 'ribbon.png');
}
}
// it's illegal to have slashes in HTML elements ids.
// replace them with dashes
list = ndoc.list;
for (id in list) {
if (list.hasOwnProperty(id)) {
obj = list[id];
// path should be HTML valid id
obj.path = obj.path.replace(/\//g, '-');
}
}
// render link
// N.B. logic is way tricky to move to templates.
// beside, this function is used as parameter in some Array#map() operations
function link(obj, short, classes) {
if (typeof obj === 'string') {
obj = list[obj] || {id: obj};
}
// broken link. `options.brokenLinks` define action
if (!obj.path) {
return obj.id;
/*if (options.brokenLinks === 'throw') {
throw 'Link is broken: ' + obj.id;
}
return options.brokenLinks === 'show' ? '[[' + obj.id + ']]' : obj.id;*/
}
//
var r = '<a href="#' + obj.path +
'" class="' + (classes || []).join(' ') +
'" title="' + obj.id + (obj.type ? ' (' + obj.type + ')' : '') +
'" data-id="' + obj.id.toLowerCase() + '">';
r += typeof short === 'string' ? short : short ? obj.name : obj.id;
r += '</a>';
return r;
}
// convert markdown to HTML
function markdown(text, inline) {
var r = text,
codes;
// render markdown
r = md2html(r);
/* fixed
// restore &entities;
r = r.replace(/&(\w+);/g, function (all, entity) {
return '&' + entity + ';';
});
*/
/* considered wrong
// trim content in <pre><code> CONTENT </code></pre>
r = r.replace(/<pre><code>([\s\S]*?)<\/code><\/pre>/g, function (all, content) {
return '<pre><code>' + content.trim() + '</code></pre>';
});
*/
// FIXME: highlight code
/*r = r.replace(/<code>([\s\S]*?)<\/code>/g, function (all, content) {
return '<code>' + highlight(content) + '</code>';
});*/
// inline markdown means to strip enclosing tag. <p /> in this case
if (inline) {
r = r.slice(3, -4);
}
// desugar [[foo#bar]] tokens into local links
// N.B. in order to not apply conversion in <code> blocks,
// we first store replace code blocks with nonces
codes = {};
r = r.replace(/(<code>[\s\S]*?<\/code>)/g, function (all, def) {
var nonce = Math.random().toString().substring(2);
codes[nonce] = def;
return '@-=@=-@' + nonce + '@-=@=-@';
});
// convert [[link]] to links
r = r.replace(/\[\[([\s\S]+?)\]\]/g, function (all, def) {
def = def.split(/\s+/);
id = def.shift();
// invalid references don't produce links
if (!list[id]) {
if (options.brokenLinks === 'throw') {
throw 'Link is broken: ' + all + '\n' + r;
}
return options.brokenLinks === 'show' ? all : id;
}
//
var obj = extend(list[id], {
name: def.join(' ') || id
});
return link(obj, true, ['link-short']);
});
// restore code blocks, given previously stored nonces
r = r.replace(/@-=@=-@(\d+)@-=@=-@/g, function (all, nonce) {
return codes[nonce];
});
//
return r;
}
// given signature object, recompose its textual representation
function signature(obj, sig) {
if (typeof obj === 'string') {
obj = list[obj];
}
var r = obj.id;
if (sig.args) {
r += '(';
sig.args.forEach(function (arg, idx, args) {
var skip_first, a, value;
// skip the first bound argument for prototype methods
skip_first = obj.bound && obj.id.indexOf('#') >= 0;
a = arg.name;
// argument can be callback
if (arg.args) {
a = signature({id: a}, arg);
}
if (!idx && skip_first) {
return; //a = '@' + a;
}
if (typeof arg.default_value !== 'undefined') {
// apply custom stringifier
value = JSON.stringify(arg.default_value, function (k, v) {
if (v instanceof RegExp) {
// FIXME: get rid of quotes, if possible
v = v.source;
} else if (v === 'null') {
v = null;
}
return v;
});
a = a + ' = ' + value;
}
// compensate for possibly skipped first argument
if (idx > (skip_first ? 1 : 0)) {
a = ', ' + a;
}
if (arg.ellipsis) {
a += '...';
}
if (arg.optional) {
a = '[' + a + ']';
}
r += a;
});
r += ')';
}
return r;
}
assets.prepare(options.htmlSkin, function (err, env) {
var vars, html;
if (err) {
if (err.originalError) {
err = (err.message || err.toString()) + ':\n' +
(err.originalError.message || err.originalError.message);
}
callback(err);
return;
}
// collect context for rendering function
vars = extend(options, {
list: ndoc.list,
tree: ndoc.tree,
date: (new Date()).toUTCString(),
//--
link: link,
markdown: markdown,
signature: signature,
// mincer rocks
inline_asset: function (pathname) {
var asset = env.findAsset(pathname);
return asset ? asset.toString() : "";
}
});
// render HTML
html = fn(vars);
pathExists(options.output, function (exists) {
if (exists) {
callback("Output directory '" + options.output + "' already exists");
return;
}
FsTools.mkdir(options.output, function (err) {
if (err) {
callback(err);
return;
}
fs.writeFile(path.join(options.output, 'index.html'), html, callback);
});
});
});
};