Debian Codegraph @

ivette/src/dome/doc/template/publish.js

raw
1 'use strict';
2
3 var doop = require('jsdoc/util/doop');
4 var env = require('jsdoc/env');
5 var fs = require('jsdoc/fs');
6 var helper = require('jsdoc/util/templateHelper');
7 var logger = require('jsdoc/util/logger');
8 var path = require('jsdoc/path');
9 var taffy = require('taffydb').taffy;
10 var template = require('jsdoc/template');
11 var util = require('util');
12
13 var htmlsafe = helper.htmlsafe;
14 var linkto = helper.linkto;
15 var resolveAuthorLinks = helper.resolveAuthorLinks;
16 var scopeToPunc = helper.scopeToPunc;
17 var hasOwnProp = Object.prototype.hasOwnProperty;
18
19 var data;
20 var view;
21
22 var outdir = path.normalize(env.opts.destination);
23
24 function find(spec) {
25 return helper.find(data, spec);
26 }
27
28 function tutoriallink(tutorial) {
29 return helper.toTutorial(tutorial, null, { tag: 'em', classname: 'disabled', prefix: 'Tutorial: ' });
30 }
31
32 function getAncestorLinks(doclet) {
33 return helper.getAncestorLinks(data, doclet);
34 }
35
36 function hashToLink(doclet, hash) {
37 if ( !/^(#.+)/.test(hash) ) { return hash; }
38
39 var url = helper.createLink(doclet);
40
41 url = url.replace(/(#.+|$)/, hash);
42 return '<a href="' + url + '">' + hash + '</a>';
43 }
44
45 function needsSignature(doclet) {
46 var needsSig = false;
47
48 // function and class definitions always get a signature
49 if (doclet.kind === 'function' || doclet.kind === 'class') {
50 needsSig = true;
51 }
52 // typedefs that contain functions get a signature, too
53 else if (doclet.kind === 'typedef' && doclet.type && doclet.type.names &&
54 doclet.type.names.length) {
55 for (var i = 0, l = doclet.type.names.length; i < l; i++) {
56 if (doclet.type.names[i].toLowerCase() === 'function') {
57 needsSig = true;
58 break;
59 }
60 }
61 }
62
63 return needsSig;
64 }
65
66 function getSignatureAttributes(item) {
67 var attributes = [];
68
69 if (item.optional) {
70 attributes.push('opt');
71 }
72
73 if (item.nullable === true) {
74 attributes.push('nullable');
75 }
76 else if (item.nullable === false) {
77 attributes.push('non-null');
78 }
79
80 return attributes;
81 }
82
83 function updateItemName(item) {
84 var attributes = getSignatureAttributes(item);
85 var itemName = item.name || '';
86
87 if (item.variable) {
88 itemName = '&hellip;' + itemName;
89 }
90
91 if (attributes && attributes.length) {
92 itemName = util.format( '%s<span class="signature-attributes">%s</span>', itemName,
93 attributes.join(', ') );
94 }
95
96 return itemName;
97 }
98
99 function addParamAttributes(params) {
100 return params.filter(function(param) {
101 return param.name && param.name.indexOf('.') === -1;
102 }).map(updateItemName);
103 }
104
105 function buildItemTypeStrings(item) {
106 var types = [];
107
108 if (item && item.type && item.type.names) {
109 item.type.names.forEach(function(name) {
110 types.push( linkto(name, htmlsafe(name)) );
111 });
112 }
113
114 return types;
115 }
116
117 function buildAttribsString(attribs) {
118 var attribsString = '';
119
120 if (attribs && attribs.length) {
121 attribsString = htmlsafe( util.format('(%s) ', attribs.join(', ')) );
122 }
123
124 return attribsString;
125 }
126
127 function addNonParamAttributes(items) {
128 var types = [];
129
130 items.forEach(function(item) {
131 types = types.concat( buildItemTypeStrings(item) );
132 });
133
134 return types;
135 }
136
137 function addSignatureParams(f) {
138 var params = f.params ? addParamAttributes(f.params) : [];
139
140 f.signature = util.format( '%s(%s)', (f.signature || ''), params.join(', ') );
141 }
142
143 function addSignatureReturns(f) {
144 var attribs = [];
145 var attribsString = '';
146 var returnTypes = [];
147 var returnTypesString = '';
148
149 // jam all the return-type attributes into an array. this could create odd results (for example,
150 // if there are both nullable and non-nullable return types), but let's assume that most people
151 // who use multiple @return tags aren't using Closure Compiler type annotations, and vice-versa.
152 if (f.returns) {
153 f.returns.forEach(function(item) {
154 helper.getAttribs(item).forEach(function(attrib) {
155 if (attribs.indexOf(attrib) === -1) {
156 attribs.push(attrib);
157 }
158 });
159 });
160
161 attribsString = buildAttribsString(attribs);
162 }
163
164 if (f.returns) {
165 returnTypes = addNonParamAttributes(f.returns);
166 }
167 if (returnTypes.length) {
168 returnTypesString = util.format( ' &rarr; %s{%s}', attribsString, returnTypes.join('|') );
169 }
170
171 f.signature = '<span class="signature">' + (f.signature || '') + '</span>' +
172 '<span class="type-signature">' + returnTypesString + '</span>';
173 }
174
175 function addSignatureTypes(f) {
176 var types = f.type ? buildItemTypeStrings(f) : [];
177
178 f.signature = (f.signature || '') + '<span class="type-signature">' +
179 (types.length ? ' :' + types.join('|') : '') + '</span>';
180 }
181
182 function addAttribs(f) {
183 var attribs = helper.getAttribs(f);
184 var attribsString = buildAttribsString(attribs);
185
186 f.attribs = util.format('<span class="type-signature">%s</span>', attribsString);
187 }
188
189 function shortenPaths(files, commonPrefix) {
190 Object.keys(files).forEach(function(file) {
191 files[file].shortened = files[file].resolved.replace(commonPrefix, '')
192 // always use forward slashes
193 .replace(/\\/g, '/');
194 });
195
196 return files;
197 }
198
199 function getPathFromDoclet(doclet) {
200 if (!doclet.meta) {
201 return null;
202 }
203
204 return doclet.meta.path && doclet.meta.path !== 'null' ?
205 path.join(doclet.meta.path, doclet.meta.filename) :
206 doclet.meta.filename;
207 }
208
209 function generate(title, docs, filename, resolveLinks) {
210 resolveLinks = resolveLinks === false ? false : true;
211
212 var docData = {
213 env: env,
214 title: title,
215 docs: docs
216 };
217
218 var outpath = path.join(outdir, filename),
219 html = view.render('container.tmpl', docData);
220
221 if (resolveLinks) {
222 html = helper.resolveLinks(html); // turn {@link foo} into <a href="foodoc.html">foo</a>
223 }
224
225 fs.writeFileSync(outpath, html, 'utf8');
226 }
227
228 function generateSourceFiles(sourceFiles, encoding) {
229 encoding = encoding || 'utf8';
230 Object.keys(sourceFiles).forEach(function(file) {
231 var source;
232 // links are keyed to the shortened path in each doclet's `meta.shortpath` property
233 var sourceOutfile = helper.getUniqueFilename(sourceFiles[file].shortened);
234 helper.registerLink(sourceFiles[file].shortened, sourceOutfile);
235
236 try {
237 source = {
238 kind: 'source',
239 code: helper.htmlsafe( fs.readFileSync(sourceFiles[file].resolved, encoding) )
240 };
241 }
242 catch(e) {
243 logger.error('Error while generating source file %s: %s', file, e.message);
244 }
245
246 generate('Source: ' + sourceFiles[file].shortened, [source], sourceOutfile,
247 false);
248 });
249 }
250
251 /**
252 * Look for classes or functions with the same name as modules (which indicates that the module
253 * exports only that class or function), then attach the classes or functions to the `module`
254 * property of the appropriate module doclets. The name of each class or function is also updated
255 * for display purposes. This function mutates the original arrays.
256 *
257 * @private
258 * @param {Array.<module:jsdoc/doclet.Doclet>} doclets - The array of classes and functions to
259 * check.
260 * @param {Array.<module:jsdoc/doclet.Doclet>} modules - The array of module doclets to search.
261 */
262 function attachModuleSymbols(doclets, modules) {
263 var symbols = {};
264
265 // build a lookup table
266 doclets.forEach(function(symbol) {
267 symbols[symbol.longname] = symbols[symbol.longname] || [];
268 symbols[symbol.longname].push(symbol);
269 });
270
271 return modules.map(function(module) {
272 if (symbols[module.longname]) {
273 module.modules = symbols[module.longname]
274 // Only show symbols that have a description. Make an exception for classes, because
275 // we want to show the constructor-signature heading no matter what.
276 .filter(function(symbol) {
277 return symbol.description || symbol.kind === 'class';
278 })
279 .map(function(symbol) {
280 symbol = doop(symbol);
281
282 if (symbol.kind === 'class' || symbol.kind === 'function') {
283 symbol.name = symbol.name.replace('module:', '(require("') + '"))';
284 }
285
286 return symbol;
287 });
288 }
289 });
290 }
291
292 function buildMemberNav(items, itemHeading, itemsSeen, linktoFn) {
293 var nav = '';
294
295 if (items.length) {
296 var itemsNav = '';
297
298 items.forEach(function(item) {
299 if ( !hasOwnProp.call(item, 'longname') ) {
300 itemsNav += '<li>' + linktoFn('', item.name) + '</li>';
301 }
302 else if ( !hasOwnProp.call(itemsSeen, item.longname) ) {
303 var displayName;
304 if (env.conf.templates.default.useLongnameInNav) {
305 displayName = item.longname;
306 } else {
307 displayName = item.name;
308 }
309 itemsNav += '<li>' + linktoFn(item.longname, displayName.replace(/\b(module|event):/g, '')) + '</li>';
310
311 itemsSeen[item.longname] = true;
312 }
313 });
314
315 if (itemsNav !== '') {
316 nav += '<h3>' + itemHeading + '</h3><ul>' + itemsNav + '</ul>';
317 }
318 }
319
320 return nav;
321 }
322
323 function linktoTutorial(longName, name) {
324 return tutoriallink(name);
325 }
326
327 function linktoExternal(longName, name) {
328 return linkto(longName, name.replace(/(^"|"$)/g, ''));
329 }
330
331 /**
332 * Create the navigation sidebar.
333 * @param {object} members The members that will be used to create the sidebar.
334 * @param {array<object>} members.classes
335 * @param {array<object>} members.externals
336 * @param {array<object>} members.globals
337 * @param {array<object>} members.mixins
338 * @param {array<object>} members.modules
339 * @param {array<object>} members.namespaces
340 * @param {array<object>} members.tutorials
341 * @param {array<object>} members.events
342 * @param {array<object>} members.interfaces
343 * @return {string} The HTML for the navigation sidebar.
344 */
345 function buildNav(members) {
346 const title = process.env.APP || 'Dome' ;
347 var nav = '<h2><a href="index.html">' + title + '</a></h2>';
348 var seen = {};
349 var seenTutorials = {};
350
351 const indexTutorials = require( path.resolve(process.env.DOME,'doc/tutorials/index.json' ));
352 const sortedTutorials = members.tutorials.sort((a,b) => {
353 const ta = indexTutorials[a.name] ;
354 const tb = indexTutorials[b.name] ;
355 const ra = (ta && ta.order) || 0 ;
356 const rb = (tb && tb.order) || 0 ;
357 return ra - rb ;
358 });
359
360 const isDome = (item) =>
361 (item.name && item.name.startsWith('dome')) ||
362 (item.longname && item.longname.startsWith('dome')) ;
363 const isApp = (item) => !isDome(item);
364 const domeModules = members.modules.filter(isDome);
365 const appModules = members.modules.filter(isApp);
366
367 nav += buildMemberNav(sortedTutorials, 'Tutorials', seenTutorials, linktoTutorial);
368 nav += buildMemberNav(appModules, `${title} Modules`, {}, linkto);
369 nav += buildMemberNav(domeModules, 'Dome Modules', {}, linkto);
370 nav += buildMemberNav(members.events, 'Events', seen, linkto);
371 nav += buildMemberNav(members.classes, 'Classes', seen, linkto);
372 nav += buildMemberNav(members.interfaces, 'Interfaces', seen, linkto);
373 nav += buildMemberNav(members.mixins, 'Mixins', seen, linkto);
374 nav += buildMemberNav(members.namespaces, 'Namespaces', seen, linkto);
375 nav += buildMemberNav(members.externals, 'Externals', seen, linktoExternal);
376
377 if (members.globals.length) {
378 var globalNav = '';
379
380 members.globals.forEach(function(g) {
381 if ( g.kind !== 'typedef' && !hasOwnProp.call(seen, g.longname) ) {
382 globalNav += '<li>' + linkto(g.longname, g.name) + '</li>';
383 }
384 seen[g.longname] = true;
385 });
386
387 if (!globalNav) {
388 // turn the heading into a link so you can actually get to the global page
389 nav += '<h3>' + linkto('global', 'Global') + '</h3>';
390 }
391 else {
392 nav += '<h3>Global</h3><ul>' + globalNav + '</ul>';
393 }
394 }
395
396 return nav;
397 }
398
399 /**
400 @param {TAFFY} taffyData See <http://taffydb.com/>.
401 @param {object} opts
402 @param {Tutorial} tutorials
403 */
404 exports.publish = function(taffyData, opts, tutorials) {
405 data = taffyData;
406
407 var conf = env.conf.templates || {};
408 conf.default = conf.default || {};
409
410 var templatePath = path.normalize(opts.template);
411 view = new template.Template( path.join(templatePath, 'tmpl') );
412
413 // claim some special filenames in advance, so the All-Powerful Overseer of Filename Uniqueness
414 // doesn't try to hand them out later
415 var indexUrl = helper.getUniqueFilename('index');
416 // don't call registerLink() on this one! 'index' is also a valid longname
417
418 var globalUrl = helper.getUniqueFilename('global');
419 helper.registerLink('global', globalUrl);
420
421 // set up templating
422 view.layout = conf.default.layoutFile ?
423 path.getResourcePath(path.dirname(conf.default.layoutFile),
424 path.basename(conf.default.layoutFile) ) :
425 'layout.tmpl';
426
427 // set up tutorials for helper
428 helper.setTutorials(tutorials);
429
430 data = helper.prune(data);
431 data.sort('longname, version, since');
432 helper.addEventListeners(data);
433
434 var sourceFiles = {};
435 var sourceFilePaths = [];
436 data().each(function(doclet) {
437 doclet.attribs = '';
438
439 if (doclet.examples) {
440 doclet.examples = doclet.examples.map(function(example) {
441 var caption, code;
442
443 if (example.match(/^\s*<caption>([\s\S]+?)<\/caption>(\s*[\n\r])([\s\S]+)$/i)) {
444 caption = RegExp.$1;
445 code = RegExp.$3;
446 }
447
448 return {
449 caption: caption || '',
450 code: code || example
451 };
452 });
453 }
454 if (doclet.see) {
455 doclet.see.forEach(function(seeItem, i) {
456 doclet.see[i] = hashToLink(doclet, seeItem);
457 });
458 }
459
460 // build a list of source files
461 var sourcePath;
462 if (doclet.meta) {
463 sourcePath = getPathFromDoclet(doclet);
464 sourceFiles[sourcePath] = {
465 resolved: sourcePath,
466 shortened: null
467 };
468 if (sourceFilePaths.indexOf(sourcePath) === -1) {
469 sourceFilePaths.push(sourcePath);
470 }
471 }
472 });
473
474 // update outdir if necessary, then create outdir
475 var packageInfo = ( find({kind: 'package'}) || [] ) [0];
476 if (packageInfo && packageInfo.name) {
477 outdir = path.join( outdir, packageInfo.name, (packageInfo.version || '') );
478 }
479 fs.mkPath(outdir);
480
481 // copy the template's static files to outdir
482 var fromDir = path.join(templatePath, 'static');
483 var staticFiles = fs.ls(fromDir, 3);
484
485 staticFiles.forEach(function(fileName) {
486 var toDir = fs.toDir( fileName.replace(fromDir, outdir) );
487 fs.mkPath(toDir);
488 fs.copyFileSync(fileName, toDir);
489 });
490
491 // copy user-specified static files to outdir
492 var staticFilePaths;
493 var staticFileFilter;
494 var staticFileScanner;
495 if (conf.default.staticFiles) {
496 // The canonical property name is `include`. We accept `paths` for backwards compatibility
497 // with a bug in JSDoc 3.2.x.
498 staticFilePaths = conf.default.staticFiles.include ||
499 conf.default.staticFiles.paths ||
500 [];
501 staticFileFilter = new (require('jsdoc/src/filter')).Filter(conf.default.staticFiles);
502 staticFileScanner = new (require('jsdoc/src/scanner')).Scanner();
503
504 staticFilePaths.forEach(function(filePath) {
505 var extraStaticFiles;
506
507 filePath = path.resolve(env.pwd, filePath);
508 extraStaticFiles = staticFileScanner.scan([filePath], 10, staticFileFilter);
509
510 extraStaticFiles.forEach(function(fileName) {
511 var sourcePath = fs.toDir(filePath);
512 var toDir = fs.toDir( fileName.replace(sourcePath, outdir) );
513 fs.mkPath(toDir);
514 fs.copyFileSync(fileName, toDir);
515 });
516 });
517 }
518
519 if (sourceFilePaths.length) {
520 sourceFiles = shortenPaths( sourceFiles, path.commonPrefix(sourceFilePaths) );
521 }
522 data().each(function(doclet) {
523 var url = helper.createLink(doclet);
524 helper.registerLink(doclet.longname, url);
525
526 // add a shortened version of the full path
527 var docletPath;
528 if (doclet.meta) {
529 docletPath = getPathFromDoclet(doclet);
530 docletPath = sourceFiles[docletPath].shortened;
531 if (docletPath) {
532 doclet.meta.shortpath = docletPath;
533 }
534 }
535 });
536
537 data().each(function(doclet) {
538 var url = helper.longnameToUrl[doclet.longname];
539
540 if (url.indexOf('#') > -1) {
541 doclet.id = helper.longnameToUrl[doclet.longname].split(/#/).pop();
542 }
543 else {
544 doclet.id = doclet.name;
545 }
546
547 if ( needsSignature(doclet) ) {
548 addSignatureParams(doclet);
549 addSignatureReturns(doclet);
550 addAttribs(doclet);
551 }
552 });
553
554 // do this after the urls have all been generated
555 data().each(function(doclet) {
556 doclet.ancestors = getAncestorLinks(doclet);
557
558 if (doclet.kind === 'member') {
559 addSignatureTypes(doclet);
560 addAttribs(doclet);
561 }
562
563 if (doclet.kind === 'constant') {
564 addSignatureTypes(doclet);
565 addAttribs(doclet);
566 doclet.kind = 'member';
567 }
568 });
569
570 var members = helper.getMembers(data);
571 members.tutorials = tutorials.children;
572
573 // output pretty-printed source files by default
574 var outputSourceFiles = conf.default && conf.default.outputSourceFiles !== false ? true :
575 false;
576
577 // add template helpers
578 view.find = find;
579 view.linkto = linkto;
580 view.resolveAuthorLinks = resolveAuthorLinks;
581 view.tutoriallink = tutoriallink;
582 view.htmlsafe = htmlsafe;
583 view.outputSourceFiles = outputSourceFiles;
584
585 // once for all
586 view.nav = buildNav(members);
587 attachModuleSymbols( find({ longname: {left: 'module:'} }), members.modules );
588
589 // generate the pretty-printed source files first so other pages can link to them
590 if (outputSourceFiles) {
591 generateSourceFiles(sourceFiles, opts.encoding);
592 }
593
594 if (members.globals.length) { generate('Global', [{kind: 'globalobj'}], globalUrl); }
595
596 // index page displays information from package.json and lists files
597 var files = find({kind: 'file'}),
598 packages = find({kind: 'package'});
599
600 const title = process.env.APP || 'Dome' ;
601 generate(title + ' Documentation',
602 packages.concat(
603 [{kind: 'mainpage', readme: opts.readme, longname: (opts.mainpagetitle) ? opts.mainpagetitle : 'Main Page'}]
604 ).concat(files),
605 indexUrl);
606
607 // set up the lists that we'll use to generate pages
608 var classes = taffy(members.classes);
609 var modules = taffy(members.modules);
610 var namespaces = taffy(members.namespaces);
611 var mixins = taffy(members.mixins);
612 var externals = taffy(members.externals);
613 var interfaces = taffy(members.interfaces);
614
615 Object.keys(helper.longnameToUrl).forEach(function(longname) {
616 var myModules = helper.find(modules, {longname: longname});
617 if (myModules.length) {
618 generate('Module: ' + myModules[0].name, myModules, helper.longnameToUrl[longname]);
619 }
620
621 var myClasses = helper.find(classes, {longname: longname});
622 if (myClasses.length) {
623 generate('Class: ' + myClasses[0].name, myClasses, helper.longnameToUrl[longname]);
624 }
625
626 var myNamespaces = helper.find(namespaces, {longname: longname});
627 if (myNamespaces.length) {
628 generate('Namespace: ' + myNamespaces[0].name, myNamespaces, helper.longnameToUrl[longname]);
629 }
630
631 var myMixins = helper.find(mixins, {longname: longname});
632 if (myMixins.length) {
633 generate('Mixin: ' + myMixins[0].name, myMixins, helper.longnameToUrl[longname]);
634 }
635
636 var myExternals = helper.find(externals, {longname: longname});
637 if (myExternals.length) {
638 generate('External: ' + myExternals[0].name, myExternals, helper.longnameToUrl[longname]);
639 }
640
641 var myInterfaces = helper.find(interfaces, {longname: longname});
642 if (myInterfaces.length) {
643 generate('Interface: ' + myInterfaces[0].name, myInterfaces, helper.longnameToUrl[longname]);
644 }
645 });
646
647 // TODO: move the tutorial functions to templateHelper.js
648 function generateTutorial(title, tutorial, filename) {
649 var tutorialData = {
650 title: title,
651 header: tutorial.title,
652 content: tutorial.parse(),
653 children: tutorial.children
654 };
655
656 var tutorialPath = path.join(outdir, filename),
657 html = view.render('tutorial.tmpl', tutorialData);
658
659 // yes, you can use {@link} in tutorials too!
660 html = helper.resolveLinks(html); // turn {@link foo} into <a href="foodoc.html">foo</a>
661
662 fs.writeFileSync(tutorialPath, html, 'utf8');
663 }
664
665 // tutorials can have only one parent so there is no risk for loops
666 function saveChildren(node) {
667 node.children.forEach(function(child) {
668 generateTutorial('Tutorial: ' + child.title, child, helper.tutorialToUrl(child.name));
669 saveChildren(child);
670 });
671 }
672 saveChildren(tutorials);
673 };