publish.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. const env = require( 'jsdoc/env' );
  2. const fs = require( 'jsdoc/fs' );
  3. const helper = require( 'jsdoc/util/templateHelper' );
  4. const logger = require( 'jsdoc/util/logger' );
  5. const path = require( 'jsdoc/path' );
  6. const { taffy } = require( '@jsdoc/salty' );
  7. const template = require( 'jsdoc/template' );
  8. const util = require( 'util' );
  9. const htmlsafe = helper.htmlsafe;
  10. const linkto = helper.linkto;
  11. const resolveAuthorLinks = helper.resolveAuthorLinks;
  12. const hasOwnProp = Object.prototype.hasOwnProperty;
  13. let data;
  14. let view;
  15. const outdir = path.normalize( env.opts.destination );
  16. const themeOpts = ( env.opts.themeOpts ) || {};
  17. function mkdirSync( filepath ) {
  18. return fs.mkdirSync( filepath, { recursive: true } );
  19. }
  20. function find( spec ) {
  21. return helper.find( data, spec );
  22. }
  23. function getAncestorLinks( doclet ) {
  24. return helper.getAncestorLinks( data, doclet );
  25. }
  26. function hashToLink( doclet, hash ) {
  27. let url;
  28. if ( ! /^(#.+)/.test( hash ) ) {
  29. return hash;
  30. }
  31. url = helper.createLink( doclet );
  32. url = url.replace( /(#.+|$)/, hash );
  33. return `<a href="${url}">${hash}</a>`;
  34. }
  35. function needsSignature( { kind, type, meta } ) {
  36. let needsSig = false;
  37. // function and class definitions always get a signature
  38. if ( kind === 'function' || kind === 'class' ) {
  39. needsSig = true;
  40. } else if ( kind === 'typedef' && type && type.names && type.names.length ) {
  41. // typedefs that contain functions get a signature, too
  42. for ( let i = 0, l = type.names.length; i < l; i ++ ) {
  43. if ( type.names[ i ].toLowerCase() === 'function' ) {
  44. needsSig = true;
  45. break;
  46. }
  47. }
  48. } else if ( kind === 'namespace' && meta && meta.code && meta.code.type && meta.code.type.match( /[Ff]unction/ ) ) {
  49. // and namespaces that are functions get a signature (but finding them is a
  50. // bit messy)
  51. needsSig = true;
  52. }
  53. return needsSig;
  54. }
  55. function updateItemName( item ) {
  56. let itemName = item.name || '';
  57. if ( item.variable ) {
  58. itemName = `&hellip;${itemName}`;
  59. }
  60. return itemName;
  61. }
  62. function addParamAttributes( params ) {
  63. return params.filter( ( { name } ) => name && ! name.includes( '.' ) ).map( updateItemName );
  64. }
  65. function buildItemTypeStrings( item ) {
  66. const types = [];
  67. if ( item && item.type && item.type.names ) {
  68. item.type.names.forEach( name => {
  69. types.push( linkto( name, htmlsafe( name ) ) );
  70. } );
  71. }
  72. return types;
  73. }
  74. function buildSearchListForData() {
  75. const searchList = [];
  76. data().each( ( item ) => {
  77. if ( item.kind !== 'package' && item.kind !== 'typedef' && ! item.inherited ) {
  78. searchList.push( {
  79. title: item.longname,
  80. link: linkto( item.longname, item.name ),
  81. description: item.description,
  82. } );
  83. }
  84. } );
  85. return searchList;
  86. }
  87. function buildAttribsString( attribs ) {
  88. let attribsString = '';
  89. if ( attribs && attribs.length ) {
  90. attribsString = htmlsafe( util.format( '(%s) ', attribs.join( ', ' ) ) );
  91. }
  92. return attribsString;
  93. }
  94. function addNonParamAttributes( items ) {
  95. let types = [];
  96. items.forEach( item => {
  97. types = types.concat( buildItemTypeStrings( item ) );
  98. } );
  99. return types;
  100. }
  101. function addSignatureParams( f ) {
  102. const params = f.params ? addParamAttributes( f.params ) : [];
  103. f.signature = util.format( '%s(%s)', ( f.signature || '' ), params.join( ', ' ) );
  104. }
  105. function addSignatureReturns( f ) {
  106. const attribs = [];
  107. let attribsString = '';
  108. let returnTypes = [];
  109. let returnTypesString = '';
  110. const source = f.yields || f.returns;
  111. // jam all the return-type attributes into an array. this could create odd results (for example,
  112. // if there are both nullable and non-nullable return types), but let's assume that most people
  113. // who use multiple @return tags aren't using Closure Compiler type annotations, and vice-versa.
  114. if ( source ) {
  115. source.forEach( item => {
  116. helper.getAttribs( item ).forEach( attrib => {
  117. if ( ! attribs.includes( attrib ) ) {
  118. attribs.push( attrib );
  119. }
  120. } );
  121. } );
  122. attribsString = buildAttribsString( attribs );
  123. }
  124. if ( source ) {
  125. returnTypes = addNonParamAttributes( source );
  126. }
  127. if ( returnTypes.length ) {
  128. returnTypesString = util.format( ' &rarr; %s{%s}', attribsString, returnTypes.join( '|' ) );
  129. }
  130. f.signature = `<span class="signature">${f.signature || ''}</span><span class="type-signature">${returnTypesString}</span>`;
  131. }
  132. function addSignatureTypes( f ) {
  133. const types = f.type ? buildItemTypeStrings( f ) : [];
  134. f.signature = `${f.signature || ''}<span class="type-signature">${types.length ? ` :${types.join( '|' )}` : ''}</span>`;
  135. }
  136. function addAttribs( f ) {
  137. const attribs = helper.getAttribs( f );
  138. const attribsString = buildAttribsString( attribs );
  139. f.attribs = util.format( '<span class="type-signature">%s</span>', attribsString );
  140. }
  141. function shortenPaths( files, commonPrefix ) {
  142. Object.keys( files ).forEach( file => {
  143. files[ file ].shortened = files[ file ].resolved.replace( commonPrefix, '' )
  144. // always use forward slashes
  145. .replace( /\\/g, '/' );
  146. } );
  147. return files;
  148. }
  149. function getPathFromDoclet( { meta } ) {
  150. if ( ! meta ) {
  151. return null;
  152. }
  153. return meta.path && meta.path !== 'null' ?
  154. path.join( meta.path, meta.filename ) :
  155. meta.filename;
  156. }
  157. function generate( title, docs, filename, resolveLinks ) {
  158. let html;
  159. resolveLinks = resolveLinks !== false;
  160. const docData = {
  161. env: env,
  162. title: title,
  163. docs: docs
  164. };
  165. const outpath = path.join( outdir, filename );
  166. html = view.render( 'container.tmpl', docData );
  167. if ( resolveLinks ) {
  168. html = helper.resolveLinks( html ); // turn {@link foo} into <a href="foodoc.html">foo</a>
  169. }
  170. fs.writeFileSync( outpath, html, 'utf8' );
  171. }
  172. function generateSourceFiles( sourceFiles, encoding = 'utf8' ) {
  173. Object.keys( sourceFiles ).forEach( file => {
  174. let source;
  175. // links are keyed to the shortened path in each doclet's `meta.shortpath` property
  176. const sourceOutfile = helper.getUniqueFilename( sourceFiles[ file ].shortened );
  177. helper.registerLink( sourceFiles[ file ].shortened, sourceOutfile );
  178. try {
  179. source = {
  180. kind: 'source',
  181. code: helper.htmlsafe( fs.readFileSync( sourceFiles[ file ].resolved, encoding ) )
  182. };
  183. } catch ( e ) {
  184. logger.error( 'Error while generating source file %s: %s', file, e.message );
  185. }
  186. generate( `Source: ${sourceFiles[ file ].shortened}`, [ source ], sourceOutfile,
  187. false );
  188. } );
  189. }
  190. function buildMainNav( items, itemsSeen, linktoFn ) {
  191. const coreDirectory = 'src';
  192. const addonsDirectory = 'examples/jsm';
  193. const hierarchy = new Map();
  194. hierarchy.set( 'Core', new Map() );
  195. hierarchy.set( 'Addons', new Map() );
  196. let nav = '';
  197. if ( items.length ) {
  198. items.forEach( item => {
  199. let displayName;
  200. let itemNav = '';
  201. if ( ! hasOwnProp.call( itemsSeen, item.longname ) ) {
  202. if ( env.conf.templates.default.useLongnameInNav ) {
  203. displayName = item.longname;
  204. } else {
  205. displayName = item.name;
  206. }
  207. itemNav += `<li data-name="${item.name}">${linktoFn( item.longname, displayName.replace( /\b(module|event):/g, '' ) )}</li>`;
  208. itemsSeen[ item.longname ] = true;
  209. const path = item.meta.shortpath;
  210. if ( path.startsWith( coreDirectory ) ) {
  211. const subCategory = path.split( '/' )[ 1 ];
  212. pushNavItem( hierarchy, 'Core', subCategory, itemNav );
  213. } else if ( path.startsWith( addonsDirectory ) ) {
  214. const subCategory = path.split( '/' )[ 2 ];
  215. pushNavItem( hierarchy, 'Addons', subCategory, itemNav );
  216. }
  217. }
  218. } );
  219. for ( const [ mainCategory, map ] of hierarchy ) {
  220. nav += `<h2>${mainCategory}</h2>`;
  221. const sortedMap = new Map( [ ...map.entries() ].sort() ); // sort sub categories
  222. for ( const [ subCategory, links ] of sortedMap ) {
  223. nav += `<h3>${subCategory}</h3>`;
  224. let navItems = '';
  225. links.sort();
  226. for ( const link of links ) {
  227. navItems += link;
  228. }
  229. nav += `<ul>${navItems}</ul>`;
  230. }
  231. }
  232. }
  233. return nav;
  234. }
  235. function buildGlobalsNav( globals, seen ) {
  236. let globalNav;
  237. let nav = '';
  238. if ( globals.length ) {
  239. // TSL
  240. let tslNav = '';
  241. globals.forEach( ( { kind, longname, name, tags } ) => {
  242. if ( kind !== 'typedef' && ! hasOwnProp.call( seen, longname ) && Array.isArray( tags ) && tags[ 0 ].title === 'tsl' ) {
  243. tslNav += `<li data-name="${longname}">${linkto( longname, name )}</li>`;
  244. seen[ longname ] = true;
  245. }
  246. } );
  247. nav += `<h2>TSL</h2><ul>${tslNav}</ul>`;
  248. // Globals
  249. globalNav = '';
  250. globals.forEach( ( { kind, longname, name } ) => {
  251. if ( kind !== 'typedef' && ! hasOwnProp.call( seen, longname ) ) {
  252. globalNav += `<li data-name="${longname}">${linkto( longname, name )}</li>`;
  253. }
  254. seen[ longname ] = true;
  255. } );
  256. if ( ! globalNav ) {
  257. // turn the heading into a link so you can actually get to the global page
  258. nav += `<h3>${linkto( 'global', 'Global' )}</h3>`;
  259. } else {
  260. nav += `<h2>Global</h2><ul>${globalNav}</ul>`;
  261. }
  262. }
  263. return nav;
  264. }
  265. function pushNavItem( hierarchy, mainCategory, subCategory, itemNav ) {
  266. subCategory = subCategory[ 0 ].toUpperCase() + subCategory.slice( 1 ); // capitalize
  267. if ( hierarchy.get( mainCategory ).get( subCategory ) === undefined ) {
  268. hierarchy.get( mainCategory ).set( subCategory, [] );
  269. }
  270. const categoryList = hierarchy.get( mainCategory ).get( subCategory );
  271. categoryList.push( itemNav );
  272. }
  273. /**
  274. * Create the navigation sidebar.
  275. * @param {Object} members The members that will be used to create the sidebar.
  276. * @return {string} The HTML for the navigation sidebar.
  277. */
  278. function buildNav( members ) {
  279. let nav = '';
  280. const seen = {};
  281. nav += buildMainNav( [ ...members.classes, ...members.modules ], seen, linkto );
  282. nav += buildGlobalsNav( members.globals, seen );
  283. return nav;
  284. }
  285. /**
  286. @param {TAFFY} taffyData See <http://taffydb.com/>.
  287. @param {Object} opts
  288. @param {Tutorial} tutorials
  289. */
  290. exports.publish = ( taffyData, opts, tutorials ) => {
  291. const sourceFilePaths = [];
  292. let sourceFiles = {};
  293. let staticFileFilter;
  294. let staticFilePaths;
  295. let staticFileScanner;
  296. data = taffyData;
  297. const conf = env.conf.templates || {};
  298. conf.default = conf.default || {};
  299. const templatePath = path.normalize( opts.template );
  300. view = new template.Template( path.join( templatePath, 'tmpl' ) );
  301. // claim some special filenames in advance, so the All-Powerful Overseer of Filename Uniqueness
  302. // doesn't try to hand them out later
  303. const indexUrl = helper.getUniqueFilename( 'index' );
  304. // don't call registerLink() on this one! 'index' is also a valid longname
  305. const globalUrl = helper.getUniqueFilename( 'global' );
  306. helper.registerLink( 'global', globalUrl );
  307. // set up templating
  308. view.layout = conf.default.layoutFile ?
  309. path.getResourcePath( path.dirname( conf.default.layoutFile ),
  310. path.basename( conf.default.layoutFile ) ) :
  311. 'layout.tmpl';
  312. // set up tutorials for helper
  313. helper.setTutorials( tutorials );
  314. data = helper.prune( data );
  315. data.sort( 'longname, version, since' );
  316. helper.addEventListeners( data );
  317. data().each( doclet => {
  318. let sourcePath;
  319. doclet.attribs = '';
  320. if ( doclet.see ) {
  321. doclet.see.forEach( ( seeItem, i ) => {
  322. doclet.see[ i ] = hashToLink( doclet, seeItem );
  323. } );
  324. }
  325. // build a list of source files
  326. if ( doclet.meta ) {
  327. sourcePath = getPathFromDoclet( doclet );
  328. sourceFiles[ sourcePath ] = {
  329. resolved: sourcePath,
  330. shortened: null
  331. };
  332. if ( ! sourceFilePaths.includes( sourcePath ) ) {
  333. sourceFilePaths.push( sourcePath );
  334. }
  335. }
  336. } );
  337. fs.mkPath( outdir );
  338. // copy the template's static files to outdir
  339. const fromDir = path.join( templatePath, 'static' );
  340. const staticFiles = fs.ls( fromDir, 3 );
  341. staticFiles.forEach( fileName => {
  342. const toDir = fs.toDir( fileName.replace( fromDir, outdir ) );
  343. fs.mkPath( toDir );
  344. fs.copyFileSync( fileName, toDir );
  345. } );
  346. // copy user-specified static files to outdir
  347. if ( conf.default.staticFiles ) {
  348. // The canonical property name is `include`. We accept `paths` for backwards compatibility
  349. // with a bug in JSDoc 3.2.x.
  350. staticFilePaths = conf.default.staticFiles.include ||
  351. conf.default.staticFiles.paths ||
  352. [];
  353. staticFileFilter = new ( require( 'jsdoc/src/filter' ).Filter )( conf.default.staticFiles );
  354. staticFileScanner = new ( require( 'jsdoc/src/scanner' ).Scanner )();
  355. staticFilePaths.forEach( filePath => {
  356. filePath = path.resolve( env.pwd, filePath );
  357. const extraStaticFiles = staticFileScanner.scan( [ filePath ], 10, staticFileFilter );
  358. extraStaticFiles.forEach( fileName => {
  359. const sourcePath = fs.toDir( filePath );
  360. const toDir = fs.toDir( fileName.replace( sourcePath, outdir ) );
  361. fs.mkPath( toDir );
  362. fs.copyFileSync( fileName, toDir );
  363. } );
  364. } );
  365. }
  366. if ( sourceFilePaths.length ) {
  367. sourceFiles = shortenPaths( sourceFiles, path.commonPrefix( sourceFilePaths ) );
  368. }
  369. data().each( doclet => {
  370. let docletPath;
  371. const url = helper.createLink( doclet );
  372. helper.registerLink( doclet.longname, url );
  373. // add a shortened version of the full path
  374. if ( doclet.meta ) {
  375. docletPath = getPathFromDoclet( doclet );
  376. docletPath = sourceFiles[ docletPath ].shortened;
  377. if ( docletPath ) {
  378. doclet.meta.shortpath = docletPath;
  379. }
  380. }
  381. } );
  382. data().each( doclet => {
  383. const url = helper.longnameToUrl[ doclet.longname ];
  384. if ( url.includes( '#' ) ) {
  385. doclet.id = helper.longnameToUrl[ doclet.longname ].split( /#/ ).pop();
  386. } else {
  387. doclet.id = doclet.name;
  388. }
  389. if ( needsSignature( doclet ) ) {
  390. addSignatureParams( doclet );
  391. addSignatureReturns( doclet );
  392. addAttribs( doclet );
  393. }
  394. } );
  395. // do this after the urls have all been generated
  396. data().each( doclet => {
  397. doclet.ancestors = getAncestorLinks( doclet );
  398. if ( doclet.kind === 'member' ) {
  399. addSignatureTypes( doclet );
  400. addAttribs( doclet );
  401. }
  402. if ( doclet.kind === 'constant' ) {
  403. addSignatureTypes( doclet );
  404. addAttribs( doclet );
  405. doclet.kind = 'member';
  406. }
  407. } );
  408. const members = helper.getMembers( data );
  409. members.tutorials = tutorials.children;
  410. // output pretty-printed source files by default
  411. const outputSourceFiles = conf.default && conf.default.outputSourceFiles !== false;
  412. // add template helpers
  413. view.find = find;
  414. view.linkto = linkto;
  415. view.resolveAuthorLinks = resolveAuthorLinks;
  416. view.htmlsafe = htmlsafe;
  417. view.outputSourceFiles = outputSourceFiles;
  418. view.ignoreInheritedSymbols = themeOpts.ignoreInheritedSymbols;
  419. // once for all
  420. view.nav = buildNav( members );
  421. // generate the pretty-printed source files first so other pages can link to them
  422. if ( outputSourceFiles ) {
  423. generateSourceFiles( sourceFiles, opts.encoding );
  424. }
  425. if ( members.globals.length ) {
  426. generate( 'Global', [ { kind: 'globalobj' } ], globalUrl );
  427. }
  428. // index page displays information from package.json and lists files
  429. const files = find( { kind: 'file' } );
  430. const packages = find( { kind: 'package' } );
  431. generate( '', // MODIFIED (Remove Home title)
  432. packages.concat(
  433. [ {
  434. kind: 'mainpage',
  435. readme: opts.readme,
  436. longname: ( opts.mainpagetitle ) ? opts.mainpagetitle : 'Main Page'
  437. } ]
  438. ).concat( files ), indexUrl );
  439. // set up the lists that we'll use to generate pages
  440. const classes = taffy( members.classes );
  441. const modules = taffy( members.modules );
  442. Object.keys( helper.longnameToUrl ).forEach( longname => {
  443. const myClasses = helper.find( classes, { longname: longname } );
  444. const myModules = helper.find( modules, { longname: longname } );
  445. if ( myClasses.length ) {
  446. generate( `${myClasses[ 0 ].name}`, myClasses, helper.longnameToUrl[ longname ] );
  447. }
  448. if ( myModules.length ) {
  449. generate( `${myModules[ 0 ].name}`, myModules, helper.longnameToUrl[ longname ] );
  450. }
  451. } );
  452. // search
  453. const searchList = buildSearchListForData();
  454. mkdirSync( path.join( outdir, 'data' ) );
  455. fs.writeFileSync(
  456. path.join( outdir, 'data', 'search.json' ),
  457. JSON.stringify( {
  458. list: searchList,
  459. } )
  460. );
  461. };
粤ICP备19079148号