publish.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  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 ) ) {
  243. const tslTag = tags.find( tag => tag.title === 'tsl' );
  244. if ( tslTag !== undefined ) {
  245. tslNav += `<li data-name="${longname}">${linkto( longname, name )}</li>`;
  246. seen[ longname ] = true;
  247. }
  248. }
  249. } );
  250. nav += `<h2>TSL</h2><ul>${tslNav}</ul>`;
  251. // Globals
  252. globalNav = '';
  253. globals.forEach( ( { kind, longname, name } ) => {
  254. if ( kind !== 'typedef' && ! hasOwnProp.call( seen, longname ) ) {
  255. globalNav += `<li data-name="${longname}">${linkto( longname, name )}</li>`;
  256. }
  257. seen[ longname ] = true;
  258. } );
  259. if ( ! globalNav ) {
  260. // turn the heading into a link so you can actually get to the global page
  261. nav += `<h3>${linkto( 'global', 'Global' )}</h3>`;
  262. } else {
  263. nav += `<h2>Global</h2><ul>${globalNav}</ul>`;
  264. }
  265. }
  266. return nav;
  267. }
  268. function pushNavItem( hierarchy, mainCategory, subCategory, itemNav ) {
  269. subCategory = subCategory[ 0 ].toUpperCase() + subCategory.slice( 1 ); // capitalize
  270. if ( hierarchy.get( mainCategory ).get( subCategory ) === undefined ) {
  271. hierarchy.get( mainCategory ).set( subCategory, [] );
  272. }
  273. const categoryList = hierarchy.get( mainCategory ).get( subCategory );
  274. categoryList.push( itemNav );
  275. }
  276. /**
  277. * Create the navigation sidebar.
  278. * @param {Object} members The members that will be used to create the sidebar.
  279. * @return {string} The HTML for the navigation sidebar.
  280. */
  281. function buildNav( members ) {
  282. let nav = '';
  283. const seen = {};
  284. nav += buildMainNav( [ ...members.classes, ...members.modules ], seen, linkto );
  285. nav += buildGlobalsNav( members.globals, seen );
  286. return nav;
  287. }
  288. /**
  289. @param {TAFFY} taffyData See <http://taffydb.com/>.
  290. @param {Object} opts
  291. @param {Tutorial} tutorials
  292. */
  293. exports.publish = ( taffyData, opts, tutorials ) => {
  294. const sourceFilePaths = [];
  295. let sourceFiles = {};
  296. let staticFileFilter;
  297. let staticFilePaths;
  298. let staticFileScanner;
  299. data = taffyData;
  300. const conf = env.conf.templates || {};
  301. conf.default = conf.default || {};
  302. const templatePath = path.normalize( opts.template );
  303. view = new template.Template( path.join( templatePath, 'tmpl' ) );
  304. // claim some special filenames in advance, so the All-Powerful Overseer of Filename Uniqueness
  305. // doesn't try to hand them out later
  306. const indexUrl = helper.getUniqueFilename( 'index' );
  307. // don't call registerLink() on this one! 'index' is also a valid longname
  308. const globalUrl = helper.getUniqueFilename( 'global' );
  309. helper.registerLink( 'global', globalUrl );
  310. // set up templating
  311. view.layout = conf.default.layoutFile ?
  312. path.getResourcePath( path.dirname( conf.default.layoutFile ),
  313. path.basename( conf.default.layoutFile ) ) :
  314. 'layout.tmpl';
  315. // set up tutorials for helper
  316. helper.setTutorials( tutorials );
  317. data = helper.prune( data );
  318. data.sort( 'longname, version, since' );
  319. helper.addEventListeners( data );
  320. data().each( doclet => {
  321. let sourcePath;
  322. doclet.attribs = '';
  323. if ( doclet.see ) {
  324. doclet.see.forEach( ( seeItem, i ) => {
  325. doclet.see[ i ] = hashToLink( doclet, seeItem );
  326. } );
  327. }
  328. // build a list of source files
  329. if ( doclet.meta ) {
  330. sourcePath = getPathFromDoclet( doclet );
  331. sourceFiles[ sourcePath ] = {
  332. resolved: sourcePath,
  333. shortened: null
  334. };
  335. if ( ! sourceFilePaths.includes( sourcePath ) ) {
  336. sourceFilePaths.push( sourcePath );
  337. }
  338. }
  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. // prepare import statements
  412. data().each( doclet => {
  413. if ( doclet.kind === 'class' || doclet.kind === 'module' ) {
  414. const tags = doclet.tags;
  415. if ( Array.isArray( tags ) ) {
  416. const importTag = tags.find( tag => tag.title === 'three_import' );
  417. doclet.import = ( importTag !== undefined ) ? importTag.text : null;
  418. }
  419. }
  420. } );
  421. const members = helper.getMembers( data );
  422. members.tutorials = tutorials.children;
  423. // output pretty-printed source files by default
  424. const outputSourceFiles = conf.default && conf.default.outputSourceFiles !== false;
  425. // add template helpers
  426. view.find = find;
  427. view.linkto = linkto;
  428. view.resolveAuthorLinks = resolveAuthorLinks;
  429. view.htmlsafe = htmlsafe;
  430. view.outputSourceFiles = outputSourceFiles;
  431. view.ignoreInheritedSymbols = themeOpts.ignoreInheritedSymbols;
  432. // once for all
  433. view.nav = buildNav( members );
  434. // generate the pretty-printed source files first so other pages can link to them
  435. if ( outputSourceFiles ) {
  436. generateSourceFiles( sourceFiles, opts.encoding );
  437. }
  438. if ( members.globals.length ) {
  439. generate( 'Global', [ { kind: 'globalobj' } ], globalUrl );
  440. }
  441. // index page displays information from package.json and lists files
  442. const files = find( { kind: 'file' } );
  443. const packages = find( { kind: 'package' } );
  444. generate( '', // MODIFIED (Remove Home title)
  445. packages.concat(
  446. [ {
  447. kind: 'mainpage',
  448. readme: opts.readme,
  449. longname: ( opts.mainpagetitle ) ? opts.mainpagetitle : 'Main Page'
  450. } ]
  451. ).concat( files ), indexUrl );
  452. // set up the lists that we'll use to generate pages
  453. const classes = taffy( members.classes );
  454. const modules = taffy( members.modules );
  455. Object.keys( helper.longnameToUrl ).forEach( longname => {
  456. const myClasses = helper.find( classes, { longname: longname } );
  457. const myModules = helper.find( modules, { longname: longname } );
  458. if ( myClasses.length ) {
  459. generate( `${myClasses[ 0 ].name}`, myClasses, helper.longnameToUrl[ longname ] );
  460. }
  461. if ( myModules.length ) {
  462. generate( `${myModules[ 0 ].name}`, myModules, helper.longnameToUrl[ longname ] );
  463. }
  464. } );
  465. // search
  466. const searchList = buildSearchListForData();
  467. mkdirSync( path.join( outdir, 'data' ) );
  468. fs.writeFileSync(
  469. path.join( outdir, 'data', 'search.json' ),
  470. JSON.stringify( {
  471. list: searchList,
  472. } )
  473. );
  474. };
粤ICP备19079148号