'use strict'; var doop = require('jsdoc/util/doop'); var env = require('jsdoc/env'); var fs = require('jsdoc/fs'); var helper = require('jsdoc/util/templateHelper'); var logger = require('jsdoc/util/logger'); var path = require('jsdoc/path'); var taffy = require('taffydb').taffy; var template = require('jsdoc/template'); var util = require('util'); var htmlsafe = helper.htmlsafe; var linkto = helper.linkto; var resolveAuthorLinks = helper.resolveAuthorLinks; var hasOwnProp = Object.prototype.hasOwnProperty; var data; var view; var outdir = path.normalize(env.opts.destination); function find(spec) { return helper.find(data, spec); } function tutoriallink(tutorial) { return helper.toTutorial(tutorial, null, { tag: 'em', classname: 'disabled', prefix: 'Tutorial: ' }); } function getAncestorLinks(doclet) { return helper.getAncestorLinks(data, doclet); } function hashToLink(doclet, hash) { var url; if ( !/^(#.+)/.test(hash) ) { return hash; } url = helper.createLink(doclet); url = url.replace(/(#.+|$)/, hash); return '' + hash + ''; } function needsSignature(doclet) { var needsSig = false; // function and class definitions always get a signature if (doclet.kind === 'function' || doclet.kind === 'class') { needsSig = true; } // typedefs that contain functions get a signature, too else if (doclet.kind === 'typedef' && doclet.type && doclet.type.names && doclet.type.names.length) { for (var i = 0, l = doclet.type.names.length; i < l; i++) { if (doclet.type.names[i].toLowerCase() === 'function') { needsSig = true; break; } } } // and namespaces that are functions get a signature (but finding them is a // bit messy) else if (doclet.kind === 'namespace' && doclet.meta && doclet.meta.code && doclet.meta.code.type && doclet.meta.code.type.match(/[Ff]unction/)) { needsSig = true; } return needsSig; } function getSignatureAttributes(item) { var attributes = []; if (item.optional) { attributes.push('opt'); } if (item.nullable === true) { attributes.push('nullable'); } else if (item.nullable === false) { attributes.push('non-null'); } return attributes; } function updateItemName(item) { var attributes = getSignatureAttributes(item); var itemName = item.name || ''; if (item.variable) { itemName = '…' + itemName; } if (attributes && attributes.length) { itemName = util.format( '%s%s', itemName, attributes.join(', ') ); } return itemName; } function addParamAttributes(params) { return params.filter(function(param) { return param.name && param.name.indexOf('.') === -1; }).map(updateItemName); } function buildItemTypeStrings(item) { var types = []; if (item && item.type && item.type.names) { item.type.names.forEach(function(name) { types.push( linkto(name, htmlsafe(name)) ); }); } return types; } function buildAttribsString(attribs) { var attribsString = ''; if (attribs && attribs.length) { attribsString = htmlsafe( util.format('(%s) ', attribs.join(', ')) ); } return attribsString; } function addNonParamAttributes(items) { var types = []; items.forEach(function(item) { types = types.concat( buildItemTypeStrings(item) ); }); return types; } function addSignatureParams(f) { var params = f.params ? addParamAttributes(f.params) : []; f.signature = util.format( '%s(%s)', (f.signature || ''), params.join(', ') ); } function addSignatureReturns(f) { var attribs = []; var attribsString = ''; var returnTypes = []; var returnTypesString = ''; var source = f.yields || f.returns; // jam all the return-type attributes into an array. this could create odd results (for example, // if there are both nullable and non-nullable return types), but let's assume that most people // who use multiple @return tags aren't using Closure Compiler type annotations, and vice-versa. if (source) { source.forEach(function(item) { helper.getAttribs(item).forEach(function(attrib) { if (attribs.indexOf(attrib) === -1) { attribs.push(attrib); } }); }); attribsString = buildAttribsString(attribs); } if (source) { returnTypes = addNonParamAttributes(source); } if (returnTypes.length) { returnTypesString = util.format( ' → %s{%s}', attribsString, returnTypes.join('|') ); } f.signature = '' + (f.signature || '') + '' + '' + returnTypesString + ''; } function addSignatureTypes(f) { var types = f.type ? buildItemTypeStrings(f) : []; f.signature = (f.signature || '') + '' + (types.length ? ' :' + types.join('|') : '') + ''; } function addAttribs(f) { var attribs = helper.getAttribs(f); var attribsString = buildAttribsString(attribs); f.attribs = util.format('%s', attribsString); } function shortenPaths(files, commonPrefix) { Object.keys(files).forEach(function(file) { files[file].shortened = files[file].resolved.replace(commonPrefix, '') // always use forward slashes .replace(/\\/g, '/'); }); return files; } function getPathFromDoclet(doclet) { if (!doclet.meta) { return null; } return doclet.meta.path && doclet.meta.path !== 'null' ? path.join(doclet.meta.path, doclet.meta.filename) : doclet.meta.filename; } function generate(title, docs, filename, resolveLinks) { var docData; var html; var outpath; resolveLinks = resolveLinks !== false; docData = { env: env, title: title, docs: docs }; outpath = path.join(outdir, filename); html = view.render('container.tmpl', docData); if (resolveLinks) { html = helper.resolveLinks(html); // turn {@link foo} into foo } fs.writeFileSync(outpath, html, 'utf8'); } function generateSourceFiles(sourceFiles, encoding) { encoding = encoding || 'utf8'; Object.keys(sourceFiles).forEach(function(file) { var source; // links are keyed to the shortened path in each doclet's `meta.shortpath` property var sourceOutfile = helper.getUniqueFilename(sourceFiles[file].shortened); helper.registerLink(sourceFiles[file].shortened, sourceOutfile); try { source = { kind: 'source', code: helper.htmlsafe( fs.readFileSync(sourceFiles[file].resolved, encoding) ) }; } catch (e) { logger.error('Error while generating source file %s: %s', file, e.message); } generate('Source: ' + sourceFiles[file].shortened, [source], sourceOutfile, false); }); } /** * Look for classes or functions with the same name as modules (which indicates that the module * exports only that class or function), then attach the classes or functions to the `module` * property of the appropriate module doclets. The name of each class or function is also updated * for display purposes. This function mutates the original arrays. * * @private * @param {Array.} doclets - The array of classes and functions to * check. * @param {Array.} modules - The array of module doclets to search. */ function attachModuleSymbols(doclets, modules) { var symbols = {}; // build a lookup table doclets.forEach(function(symbol) { symbols[symbol.longname] = symbols[symbol.longname] || []; symbols[symbol.longname].push(symbol); }); modules.forEach(function(module) { if (symbols[module.longname]) { module.modules = symbols[module.longname] // Only show symbols that have a description. Make an exception for classes, because // we want to show the constructor-signature heading no matter what. .filter(function(symbol) { return symbol.description || symbol.kind === 'class'; }) .map(function(symbol) { symbol = doop(symbol); if (symbol.kind === 'class' || symbol.kind === 'function') { symbol.name = symbol.name.replace('module:', '(require("') + '"))'; } return symbol; }); } }); } function buildMemberNav(items, itemHeading, itemsSeen, linktoFn) { var nav = ''; if (items.length) { var itemsNav = ''; items.forEach(function(item) { var displayName; if ( !hasOwnProp.call(item, 'longname') ) { itemsNav += '
  • ' + linktoFn('', item.name) + '
  • '; } else if ( !hasOwnProp.call(itemsSeen, item.longname) ) { if (env.conf.templates.default.useLongnameInNav) { displayName = item.longname; } else { displayName = item.longname; } itemsNav += '
  • ' + linktoFn(item.longname, displayName.replace(/\b(module|event):/g, '')) + '
  • '; itemsSeen[item.longname] = true; } }); if (itemsNav !== '') { nav += '

    ' + itemHeading + '

    '; } } return nav; } function buildMemberNavNamespacesTree(items, itemHeading, itemsSeen, linktoFn) { var nav = ''; var restored_items = restoreSourceTree(items); var recursive_generate_namespaces_old = function (_tree) { var items = _tree.items; var a = 0; var res = ""; if (_tree.item_data) res = ""; return res; }; var g_id = 0; var recursive_generate_namespaces = function (_tree) { var lgid = g_id++; var items = _tree.items; var a = 0; var res = ""; if (_tree.item_data) res = "
  • "; if (_tree.item_data) res += ""; if (items.length != 0 && _tree.item_data) res += ""; if (_tree.item_data) res += linktoFn(_tree.item_data.longname, _tree.item_data.name.replace(/\b(module|event):/g, '')); if (items.length != 0) { if (_tree.item_data) res += "
      "; while (a < items.length) { var name = items[a]; var data = _tree[name]; res += recursive_generate_namespaces(data); a++; } if (_tree.item_data) res += "
    "; } if (_tree.item_data) res += "
  • "; return res; }; var req_res = recursive_generate_namespaces(restored_items); debugger; if (items.length) { var itemsNav = ''; itemsNav += req_res; if (itemsNav !== '') { nav += '

    ' + itemHeading + '

    '; } } return nav; } function restoreSourceTree(items) { var out_tree = {items:[]}; var a = 0; while( a < items.length){ var item = items[a]; var path = item.longname.split("."); // console.log(item.longname); var cur_path = out_tree; var b = 0; while(b < path.length){ var hop = path[b]; var is_exist = !!cur_path[hop]; // console.log("current hop: " + hop); if(!is_exist){ // console.log("new hop: " + hop); cur_path[hop] = {}; cur_path[hop].item_data = item; cur_path[hop].items = []; cur_path.items.push(hop) } else { // console.log("exist hop: " + hop); cur_path = cur_path[hop]; } b++; } // console.log("------------"); a++; } return out_tree; } function linktoTutorial(longName, name) { return tutoriallink(name); } function linktoExternal(longName, name) { return linkto(longName, name.replace(/(^"|"$)/g, '')); } /** * Create the navigation sidebar. * @param {object} members The members that will be used to create the sidebar. * @param {array} members.classes * @param {array} members.externals * @param {array} members.globals * @param {array} members.mixins * @param {array} members.modules * @param {array} members.namespaces * @param {array} members.tutorials * @param {array} members.events * @param {array} members.interfaces * @return {string} The HTML for the navigation sidebar. */ // function buildNav(members) { // var globalNav; // var nav = '

    Home

    '; // var seen = {}; // var seenTutorials = {}; // // nav += buildMemberNav(members.modules, 'Modules', {}, linkto); // nav += buildMemberNav(members.externals, 'Externals', seen, linktoExternal); // nav += buildMemberNavNamespace(members.namespaces, 'Managers', seen, linkto); // nav += buildMemberNavNamespace(members.classes, 'Classes', seen, linkto); // nav += buildMemberNav(members.events, 'Events', seen, linkto); // // nav += buildMemberNavNamespaces(members.namespaces, 'Namespaces', seen, linkto); // // nav += buildMemberNav(members.namespaces, 'Namespaces', seen, linkto); // nav += buildMemberNav(members.mixins, 'Mixins', seen, linkto); // nav += buildMemberNav(members.tutorials, 'Tutorials', seenTutorials, linktoTutorial); // nav += buildMemberNav(members.interfaces, 'Interfaces', seen, linkto); // // if (members.globals.length) { // globalNav = ''; // // members.globals.forEach(function(g) { // if ( g.kind !== 'typedef' && !hasOwnProp.call(seen, g.longname) ) { // globalNav += '
  • ' + linkto(g.longname, g.name) + '
  • '; // } // seen[g.longname] = true; // }); // // if (!globalNav) { // // turn the heading into a link so you can actually get to the global page // nav += '

    ' + linkto('global', 'Global') + '

    '; // } // else { // nav += '

    Global

      ' + globalNav + '
    '; // } // } // // return nav; // } function buildMemberNavNamespace(items, itemHeading, itemsSeen, linktoFn) { var nav = ''; console.log("buildMemberNavNamespace"); console.log("items", JSON.stringify(items, true, 3)); console.log("itemHeading", JSON.stringify(itemHeading, true, 3)); console.log("itemsSeen", JSON.stringify(itemsSeen, true, 3)); console.log("linktoFn", JSON.stringify(linktoFn, true, 3)); if (items.length) { var itemsNav = ''; items.forEach(function(item) { var displayName; if ( !hasOwnProp.call(item, 'longname') ) { itemsNav += '
  • ' + linktoFn('', item.name) + '
  • '; } else if ( !hasOwnProp.call(itemsSeen, item.longname) ) { displayName = item.longname; var arr = displayName.split("."); var end_id = arr.length - 1; var last = arr.pop(); var prev_name = arr.join("."); var res = ""; // res += ""; if (arr.length > 0) res += "" +prev_name+ "."; res += "" +last+ ""; itemsNav += '
  • ' + linktoFn(item.longname, res.replace(/\b(module|event):/g, '')) + '
  • '; // itemsNav += "
    "; itemsSeen[item.longname] = true; } }); if (itemsNav !== '') { nav += '

    ' + itemHeading + '

      ' + itemsNav + '
    '; } } return nav; } function buildNav(members) { var nav = '

    GUI 2.9.1-develop

    '; // var seen = {}; // nav += buildMemberNavNamespace(members.namespaces, 'Managers', seen, linkto); // nav += buildMemberNavNamespace(members.classes, 'Classes', seen, linkto); nav += render_explorer(members.namespaces, members.classes); return nav; } var render_explorer = function (_nss, _clss) { var nav = ""; nav += render_menu_item("Managers", "manager", _nss, _clss, true); nav += render_menu_item("Libraries", "library", _nss, _clss, true); return nav; }; var render_menu_item = function (_title, _type, _nss, _clss, _check_tags) { var nav = ""; nav += "
      "; nav += "
      " + _title + "
      "; for (var a = 0; a < _nss.length; a++) { var ns = _nss[a]; var is_manager = _check_tags && ns.tags && check_tags(ns.tags, _type); if (!is_manager) continue; var members = find_first_members(ns.name, _clss); // console.log(JSON.stringify(ns, true, 3)) nav += ""; } nav += "
    "; return nav; }; var check_tags = function (_tags, _key) { for (var a = 0; a < _tags.length; a++) { var info = _tags[a]; if (info.title == _key) return true; } return false; }; var find_first_members = function (_parent, _clss) { var members = []; for(var a = 0; a < _clss.length; a++ ) { var cls = _clss[a]; var hierarchy = cls.memberof.split("."); if (hierarchy.length == 1 && hierarchy[0] === "") { continue; } var found = false; for(var b = 0; b < hierarchy.length; b++ ) { var hop = hierarchy[b]; if(hop == _parent) { found = true; break; } } // var cls_hierarchy = cls var member_success = found && hierarchy.length - b < 2; // console.log("_parent", _parent); // console.log("cls", JSON.stringify(cls, true, 3)); // console.log("found", found); // console.log("hierarchy.length - b", hierarchy.length - b); if(!member_success) continue; members.push(cls); } return members; }; /** @param {TAFFY} taffyData See . @param {object} opts @param {Tutorial} tutorials */ exports.publish = function(taffyData, opts, tutorials) { var classes; var conf; var externals; var files; var fromDir; var globalUrl; var indexUrl; var interfaces; var members; var mixins; var modules; var namespaces; var outputSourceFiles; var packageInfo; var packages; var sourceFilePaths = []; var sourceFiles = {}; var staticFileFilter; var staticFilePaths; var staticFiles; var staticFileScanner; var templatePath; data = taffyData; conf = env.conf.templates || {}; conf.default = conf.default || {}; templatePath = path.normalize(opts.template); view = new template.Template( path.join(templatePath, 'tmpl') ); // claim some special filenames in advance, so the All-Powerful Overseer of Filename Uniqueness // doesn't try to hand them out later indexUrl = helper.getUniqueFilename('index'); // don't call registerLink() on this one! 'index' is also a valid longname globalUrl = helper.getUniqueFilename('global'); helper.registerLink('global', globalUrl); // set up templating view.layout = conf.default.layoutFile ? path.getResourcePath(path.dirname(conf.default.layoutFile), path.basename(conf.default.layoutFile) ) : 'layout.tmpl'; // set up tutorials for helper helper.setTutorials(tutorials); data = helper.prune(data); data.sort('longname, version, since'); helper.addEventListeners(data); data().each(function(doclet) { var sourcePath; doclet.attribs = ''; if (doclet.examples) { doclet.examples = doclet.examples.map(function(example) { var caption; var code; if (example.match(/^\s*([\s\S]+?)<\/caption>(\s*[\n\r])([\s\S]+)$/i)) { caption = RegExp.$1; code = RegExp.$3; } return { caption: caption || '', code: code || example }; }); } if (doclet.see) { doclet.see.forEach(function(seeItem, i) { doclet.see[i] = hashToLink(doclet, seeItem); }); } // build a list of source files if (doclet.meta) { sourcePath = getPathFromDoclet(doclet); sourceFiles[sourcePath] = { resolved: sourcePath, shortened: null }; if (sourceFilePaths.indexOf(sourcePath) === -1) { sourceFilePaths.push(sourcePath); } } }); // update outdir if necessary, then create outdir packageInfo = ( find({kind: 'package'}) || [] )[0]; if (packageInfo && packageInfo.name) { outdir = path.join( outdir, packageInfo.name, (packageInfo.version || '') ); } fs.mkPath(outdir); // copy the template's static files to outdir fromDir = path.join(templatePath, 'static'); staticFiles = fs.ls(fromDir, 3); staticFiles.forEach(function(fileName) { var toDir = fs.toDir( fileName.replace(fromDir, outdir) ); fs.mkPath(toDir); fs.copyFileSync(fileName, toDir); }); // copy user-specified static files to outdir if (conf.default.staticFiles) { // The canonical property name is `include`. We accept `paths` for backwards compatibility // with a bug in JSDoc 3.2.x. staticFilePaths = conf.default.staticFiles.include || conf.default.staticFiles.paths || []; staticFileFilter = new (require('jsdoc/src/filter')).Filter(conf.default.staticFiles); staticFileScanner = new (require('jsdoc/src/scanner')).Scanner(); staticFilePaths.forEach(function(filePath) { var extraStaticFiles; filePath = path.resolve(env.pwd, filePath); extraStaticFiles = staticFileScanner.scan([filePath], 10, staticFileFilter); extraStaticFiles.forEach(function(fileName) { var sourcePath = fs.toDir(filePath); var toDir = fs.toDir( fileName.replace(sourcePath, outdir) ); fs.mkPath(toDir); fs.copyFileSync(fileName, toDir); }); }); } if (sourceFilePaths.length) { sourceFiles = shortenPaths( sourceFiles, path.commonPrefix(sourceFilePaths) ); } data().each(function(doclet) { var docletPath; var url = helper.createLink(doclet); helper.registerLink(doclet.longname, url); // add a shortened version of the full path if (doclet.meta) { docletPath = getPathFromDoclet(doclet); docletPath = sourceFiles[docletPath].shortened; if (docletPath) { doclet.meta.shortpath = docletPath; } } }); data().each(function(doclet) { var url = helper.longnameToUrl[doclet.longname]; if (url.indexOf('#') > -1) { doclet.id = helper.longnameToUrl[doclet.longname].split(/#/).pop(); } else { doclet.id = doclet.name; } if ( needsSignature(doclet) ) { addSignatureParams(doclet); addSignatureReturns(doclet); addAttribs(doclet); } }); // do this after the urls have all been generated data().each(function(doclet) { doclet.ancestors = getAncestorLinks(doclet); if (doclet.kind === 'member') { addSignatureTypes(doclet); addAttribs(doclet); } if (doclet.kind === 'constant') { addSignatureTypes(doclet); addAttribs(doclet); doclet.kind = 'member'; } }); members = helper.getMembers(data); members.tutorials = tutorials.children; // output pretty-printed source files by default outputSourceFiles = conf.default && conf.default.outputSourceFiles !== false; // add template helpers view.find = find; view.linkto = linkto; view.resolveAuthorLinks = resolveAuthorLinks; view.tutoriallink = tutoriallink; view.htmlsafe = htmlsafe; view.outputSourceFiles = outputSourceFiles; // once for all view.nav = buildNav(members); attachModuleSymbols( find({ longname: {left: 'module:'} }), members.modules ); // generate the pretty-printed source files first so other pages can link to them if (outputSourceFiles) { generateSourceFiles(sourceFiles, opts.encoding); } if (members.globals.length) { generate('Global', [{kind: 'globalobj'}], globalUrl); } // index page displays information from package.json and lists files files = find({kind: 'file'}); packages = find({kind: 'package'}); generate('Home', packages.concat( [{ kind: 'mainpage', readme: opts.readme, longname: (opts.mainpagetitle) ? opts.mainpagetitle : 'Main Page' }] ).concat(files), indexUrl); // set up the lists that we'll use to generate pages classes = taffy(members.classes); modules = taffy(members.modules); namespaces = taffy(members.namespaces); mixins = taffy(members.mixins); externals = taffy(members.externals); interfaces = taffy(members.interfaces); Object.keys(helper.longnameToUrl).forEach(function(longname) { var myClasses = helper.find(classes, {longname: longname}); var myExternals = helper.find(externals, {longname: longname}); var myInterfaces = helper.find(interfaces, {longname: longname}); var myMixins = helper.find(mixins, {longname: longname}); var myModules = helper.find(modules, {longname: longname}); var myNamespaces = helper.find(namespaces, {longname: longname}); if (myModules.length) { generate('Module: ' + myModules[0].name, myModules, helper.longnameToUrl[longname]); } if (myClasses.length) { generate('Class: ' + myClasses[0].name, myClasses, helper.longnameToUrl[longname]); } if (myNamespaces.length) { generate('Namespace: ' + myNamespaces[0].name, myNamespaces, helper.longnameToUrl[longname]); } if (myMixins.length) { generate('Mixin: ' + myMixins[0].name, myMixins, helper.longnameToUrl[longname]); } if (myExternals.length) { generate('External: ' + myExternals[0].name, myExternals, helper.longnameToUrl[longname]); } if (myInterfaces.length) { generate('Interface: ' + myInterfaces[0].name, myInterfaces, helper.longnameToUrl[longname]); } }); // TODO: move the tutorial functions to templateHelper.js function generateTutorial(title, tutorial, filename) { var tutorialData = { title: title, header: tutorial.title, content: tutorial.parse(), children: tutorial.children }; var tutorialPath = path.join(outdir, filename); var html = view.render('tutorial.tmpl', tutorialData); // yes, you can use {@link} in tutorials too! html = helper.resolveLinks(html); // turn {@link foo} into foo fs.writeFileSync(tutorialPath, html, 'utf8'); } // tutorials can have only one parent so there is no risk for loops function saveChildren(node) { node.children.forEach(function(child) { generateTutorial('Tutorial: ' + child.title, child, helper.tutorialToUrl(child.name)); saveChildren(child); }); } saveChildren(tutorials); };