publish.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  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. for ( const [ subCategory, links ] of map ) {
  221. nav += `<h3>${subCategory}</h3>`;
  222. let navItems = '';
  223. for ( const link of links ) {
  224. navItems += link;
  225. }
  226. nav += `<ul>${navItems}</ul>`;
  227. }
  228. }
  229. }
  230. return nav;
  231. }
  232. function buildGlobalsNav( globals, seen ) {
  233. let globalNav;
  234. let nav = '';
  235. if ( globals.length ) {
  236. // TSL
  237. let tslNav = '';
  238. globals.forEach( ( { kind, longname, name, tags } ) => {
  239. if ( kind !== 'typedef' && ! hasOwnProp.call( seen, longname ) && Array.isArray( tags ) && tags[ 0 ].title === 'tsl' ) {
  240. tslNav += `<li data-name="${longname}">${linkto( longname, name )}</li>`;
  241. seen[ longname ] = true;
  242. }
  243. } );
  244. nav += `<h2>TSL</h2><ul>${tslNav}</ul>`;
  245. // Globals
  246. globalNav = '';
  247. globals.forEach( ( { kind, longname, name } ) => {
  248. if ( kind !== 'typedef' && ! hasOwnProp.call( seen, longname ) ) {
  249. globalNav += `<li data-name="${longname}">${linkto( longname, name )}</li>`;
  250. }
  251. seen[ longname ] = true;
  252. } );
  253. if ( ! globalNav ) {
  254. // turn the heading into a link so you can actually get to the global page
  255. nav += `<h3>${linkto( 'global', 'Global' )}</h3>`;
  256. } else {
  257. nav += `<h2>Global</h2><ul>${globalNav}</ul>`;
  258. }
  259. }
  260. return nav;
  261. }
  262. function pushNavItem( hierarchy, mainCategory, subCategory, itemNav ) {
  263. subCategory = subCategory[ 0 ].toUpperCase() + subCategory.slice( 1 ); // capitalize
  264. if ( hierarchy.get( mainCategory ).get( subCategory ) === undefined ) {
  265. hierarchy.get( mainCategory ).set( subCategory, [] );
  266. }
  267. const categoryList = hierarchy.get( mainCategory ).get( subCategory );
  268. categoryList.push( itemNav );
  269. }
  270. /**
  271. * Create the navigation sidebar.
  272. * @param {object} members The members that will be used to create the sidebar.
  273. * @param {array<object>} members.classes
  274. * @return {string} The HTML for the navigation sidebar.
  275. */
  276. function buildNav( members ) {
  277. let nav = '';
  278. const seen = {};
  279. nav += buildClassNav( members.classes, seen, linkto );
  280. nav += buildGlobalsNav( members.globals, seen );
  281. return nav;
  282. }
  283. /**
  284. @param {TAFFY} taffyData See <http://taffydb.com/>.
  285. @param {object} opts
  286. @param {Tutorial} tutorials
  287. */
  288. exports.publish = ( taffyData, opts, tutorials ) => {
  289. const sourceFilePaths = [];
  290. let sourceFiles = {};
  291. let staticFileFilter;
  292. let staticFilePaths;
  293. let staticFileScanner;
  294. data = taffyData;
  295. const conf = env.conf.templates || {};
  296. conf.default = conf.default || {};
  297. const templatePath = path.normalize( opts.template );
  298. view = new template.Template( path.join( templatePath, 'tmpl' ) );
  299. // claim some special filenames in advance, so the All-Powerful Overseer of Filename Uniqueness
  300. // doesn't try to hand them out later
  301. const indexUrl = helper.getUniqueFilename( 'index' );
  302. // don't call registerLink() on this one! 'index' is also a valid longname
  303. const globalUrl = helper.getUniqueFilename( 'global' );
  304. helper.registerLink( 'global', globalUrl );
  305. // set up templating
  306. view.layout = conf.default.layoutFile ?
  307. path.getResourcePath( path.dirname( conf.default.layoutFile ),
  308. path.basename( conf.default.layoutFile ) ) :
  309. 'layout.tmpl';
  310. // set up tutorials for helper
  311. helper.setTutorials( tutorials );
  312. data = helper.prune( data );
  313. data.sort( 'longname, version, since' );
  314. helper.addEventListeners( data );
  315. data().each( doclet => {
  316. let sourcePath;
  317. doclet.attribs = '';
  318. if ( doclet.see ) {
  319. doclet.see.forEach( ( seeItem, i ) => {
  320. doclet.see[ i ] = hashToLink( doclet, seeItem );
  321. } );
  322. }
  323. // build a list of source files
  324. if ( doclet.meta ) {
  325. sourcePath = getPathFromDoclet( doclet );
  326. sourceFiles[ sourcePath ] = {
  327. resolved: sourcePath,
  328. shortened: null
  329. };
  330. if ( ! sourceFilePaths.includes( sourcePath ) ) {
  331. sourceFilePaths.push( sourcePath );
  332. }
  333. }
  334. } );
  335. // update outdir if necessary, then create outdir
  336. const packageInfo = ( find( { kind: 'package' } ) || [] )[ 0 ];
  337. if ( packageInfo && packageInfo.name ) {
  338. outdir = path.join( outdir, packageInfo.name, ( packageInfo.version || '' ) );
  339. }
  340. fs.mkPath( outdir );
  341. // copy the template's static files to outdir
  342. const fromDir = path.join( templatePath, 'static' );
  343. const staticFiles = fs.ls( fromDir, 3 );
  344. staticFiles.forEach( fileName => {
  345. const toDir = fs.toDir( fileName.replace( fromDir, outdir ) );
  346. fs.mkPath( toDir );
  347. fs.copyFileSync( fileName, toDir );
  348. } );
  349. // copy user-specified static files to outdir
  350. if ( conf.default.staticFiles ) {
  351. // The canonical property name is `include`. We accept `paths` for backwards compatibility
  352. // with a bug in JSDoc 3.2.x.
  353. staticFilePaths = conf.default.staticFiles.include ||
  354. conf.default.staticFiles.paths ||
  355. [];
  356. staticFileFilter = new ( require( 'jsdoc/src/filter' ).Filter )( conf.default.staticFiles );
  357. staticFileScanner = new ( require( 'jsdoc/src/scanner' ).Scanner )();
  358. staticFilePaths.forEach( filePath => {
  359. filePath = path.resolve( env.pwd, filePath );
  360. const extraStaticFiles = staticFileScanner.scan( [ filePath ], 10, staticFileFilter );
  361. extraStaticFiles.forEach( fileName => {
  362. const sourcePath = fs.toDir( filePath );
  363. const toDir = fs.toDir( fileName.replace( sourcePath, outdir ) );
  364. fs.mkPath( toDir );
  365. fs.copyFileSync( fileName, toDir );
  366. } );
  367. } );
  368. }
  369. if ( sourceFilePaths.length ) {
  370. sourceFiles = shortenPaths( sourceFiles, path.commonPrefix( sourceFilePaths ) );
  371. }
  372. data().each( doclet => {
  373. let docletPath;
  374. const url = helper.createLink( doclet );
  375. helper.registerLink( doclet.longname, url );
  376. // add a shortened version of the full path
  377. if ( doclet.meta ) {
  378. docletPath = getPathFromDoclet( doclet );
  379. docletPath = sourceFiles[ docletPath ].shortened;
  380. if ( docletPath ) {
  381. doclet.meta.shortpath = docletPath;
  382. }
  383. }
  384. } );
  385. data().each( doclet => {
  386. const url = helper.longnameToUrl[ doclet.longname ];
  387. if ( url.includes( '#' ) ) {
  388. doclet.id = helper.longnameToUrl[ doclet.longname ].split( /#/ ).pop();
  389. } else {
  390. doclet.id = doclet.name;
  391. }
  392. if ( needsSignature( doclet ) ) {
  393. addSignatureParams( doclet );
  394. addSignatureReturns( doclet );
  395. addAttribs( doclet );
  396. }
  397. } );
  398. // do this after the urls have all been generated
  399. data().each( doclet => {
  400. doclet.ancestors = getAncestorLinks( doclet );
  401. if ( doclet.kind === 'member' ) {
  402. addSignatureTypes( doclet );
  403. addAttribs( doclet );
  404. }
  405. if ( doclet.kind === 'constant' ) {
  406. addSignatureTypes( doclet );
  407. addAttribs( doclet );
  408. doclet.kind = 'member';
  409. }
  410. } );
  411. const members = helper.getMembers( data );
  412. members.tutorials = tutorials.children;
  413. // output pretty-printed source files by default
  414. const outputSourceFiles = conf.default && conf.default.outputSourceFiles !== false;
  415. // add template helpers
  416. view.find = find;
  417. view.linkto = linkto;
  418. view.resolveAuthorLinks = resolveAuthorLinks;
  419. view.htmlsafe = htmlsafe;
  420. view.outputSourceFiles = outputSourceFiles;
  421. // once for all
  422. view.nav = buildNav( members );
  423. // generate the pretty-printed source files first so other pages can link to them
  424. if ( outputSourceFiles ) {
  425. generateSourceFiles( sourceFiles, opts.encoding );
  426. }
  427. if ( members.globals.length ) {
  428. generate( 'Global', [ { kind: 'globalobj' } ], globalUrl );
  429. }
  430. // index page displays information from package.json and lists files
  431. const files = find( { kind: 'file' } );
  432. const packages = find( { kind: 'package' } );
  433. generate( '', // MODIFIED (Remove Home title)
  434. packages.concat(
  435. [ {
  436. kind: 'mainpage',
  437. readme: opts.readme,
  438. longname: ( opts.mainpagetitle ) ? opts.mainpagetitle : 'Main Page'
  439. } ]
  440. ).concat( files ), indexUrl );
  441. // set up the lists that we'll use to generate pages
  442. const classes = taffy( members.classes );
  443. Object.keys( helper.longnameToUrl ).forEach( longname => {
  444. const myClasses = helper.find( classes, { longname: longname } );
  445. if ( myClasses.length ) {
  446. generate( `${myClasses[ 0 ].name}`, myClasses, helper.longnameToUrl[ longname ] );
  447. }
  448. } );
  449. // search
  450. const searchList = buildSearchListForData();
  451. mkdirSync( path.join( outdir, 'data' ) );
  452. fs.writeFileSync(
  453. path.join( outdir, 'data', 'search.json' ),
  454. JSON.stringify( {
  455. list: searchList,
  456. } )
  457. );
  458. };
粤ICP备19079148号