publish.js 16 KB

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