publish.js 16 KB

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