publish.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  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. let html;
  151. resolveLinks = resolveLinks !== false;
  152. const docData = {
  153. env: env,
  154. title: title,
  155. docs: docs,
  156. augments: docs && docs[0] ? docs[0].augments : null
  157. };
  158. const outpath = path.join( outdir, filename );
  159. html = view.render( 'container.tmpl', docData );
  160. if ( resolveLinks ) {
  161. html = helper.resolveLinks( html ); // turn {@link foo} into <a href="foodoc.html">foo</a>
  162. }
  163. // Remove lines that only contain whitespace
  164. html = html.replace( /^\s*\n/gm, '' );
  165. fs.writeFileSync( outpath, html, 'utf8' );
  166. }
  167. function generateSourceFiles( sourceFiles, encoding = 'utf8' ) {
  168. Object.keys( sourceFiles ).forEach( file => {
  169. let source;
  170. // links are keyed to the shortened path in each doclet's `meta.shortpath` property
  171. const sourceOutfile = helper.getUniqueFilename( sourceFiles[ file ].shortened );
  172. helper.registerLink( sourceFiles[ file ].shortened, sourceOutfile );
  173. try {
  174. source = {
  175. kind: 'source',
  176. code: helper.htmlsafe( fs.readFileSync( sourceFiles[ file ].resolved, encoding ) )
  177. };
  178. } catch ( e ) {
  179. logger.error( 'Error while generating source file %s: %s', file, e.message );
  180. }
  181. generate( `Source: ${sourceFiles[ file ].shortened}`, [ source ], sourceOutfile,
  182. false );
  183. } );
  184. }
  185. function buildMainNav( items, itemsSeen, linktoFn ) {
  186. const coreDirectory = 'src';
  187. const addonsDirectory = 'examples/jsm';
  188. const hierarchy = new Map();
  189. hierarchy.set( 'Core', new Map() );
  190. hierarchy.set( 'Addons', new Map() );
  191. let nav = '';
  192. if ( items.length ) {
  193. items.forEach( item => {
  194. let displayName;
  195. let itemNav = '';
  196. if ( ! hasOwnProp.call( itemsSeen, item.longname ) ) {
  197. if ( env.conf.templates.default.useLongnameInNav ) {
  198. displayName = item.longname;
  199. } else {
  200. displayName = item.name;
  201. }
  202. itemNav += `<li>${linktoFn( item.longname, displayName.replace( /\b(module|event):/g, '' ) )}</li>`;
  203. itemsSeen[ item.longname ] = true;
  204. const path = item.meta.shortpath;
  205. if ( path.startsWith( coreDirectory ) ) {
  206. const subCategory = path.split( '/' )[ 1 ];
  207. pushNavItem( hierarchy, 'Core', subCategory, itemNav );
  208. } else if ( path.startsWith( addonsDirectory ) ) {
  209. const subCategory = path.split( '/' )[ 2 ];
  210. pushNavItem( hierarchy, 'Addons', subCategory, itemNav );
  211. }
  212. }
  213. } );
  214. for ( const [ mainCategory, map ] of hierarchy ) {
  215. nav += `<h2>${mainCategory}</h2>\n`;
  216. const sortedMap = new Map( [ ...map.entries() ].sort() ); // sort sub categories
  217. for ( const [ subCategory, links ] of sortedMap ) {
  218. nav += `<h3>${subCategory}</h3>\n`;
  219. let navItems = '';
  220. links.sort();
  221. for ( const link of links ) {
  222. navItems += link + '\n';
  223. }
  224. nav += `<ul>\n${navItems}</ul>\n`;
  225. }
  226. }
  227. }
  228. return nav;
  229. }
  230. function buildGlobalsNav( globals, seen ) {
  231. let globalNav;
  232. let nav = '';
  233. if ( globals.length ) {
  234. // TSL
  235. let tslNav = '';
  236. globals.forEach( ( { kind, longname, name, tags } ) => {
  237. if ( kind !== 'typedef' && ! hasOwnProp.call( seen, longname ) && Array.isArray( tags ) ) {
  238. const tslTag = tags.find( tag => tag.title === 'tsl' );
  239. if ( tslTag !== undefined ) {
  240. tslNav += `<li>${linkto( longname, name )}</li>\n`;
  241. seen[ longname ] = true;
  242. }
  243. }
  244. } );
  245. nav += `<h2>TSL</h2>\n<ul>\n${tslNav}</ul>\n`;
  246. // Globals
  247. globalNav = '';
  248. globals.forEach( ( { kind, longname, name } ) => {
  249. if ( kind !== 'typedef' && ! hasOwnProp.call( seen, longname ) ) {
  250. globalNav += `<li>${linkto( longname, name )}</li>\n`;
  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>\n`;
  257. } else {
  258. nav += `<h2>Global</h2>\n<ul>\n${globalNav}</ul>\n`;
  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. * @return {string} The HTML for the navigation sidebar.
  275. */
  276. function buildNav( members ) {
  277. let nav = '';
  278. const seen = {};
  279. nav += buildMainNav( [ ...members.classes, ...members.modules ], 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. fs.mkPath( outdir );
  336. // copy the template's static files to outdir
  337. const fromDir = path.join( templatePath, 'static' );
  338. const staticFiles = fs.ls( fromDir, 3 );
  339. staticFiles.forEach( fileName => {
  340. const toDir = fs.toDir( fileName.replace( fromDir, outdir ) );
  341. fs.mkPath( toDir );
  342. fs.copyFileSync( fileName, toDir );
  343. } );
  344. // copy user-specified static files to outdir
  345. if ( conf.default.staticFiles ) {
  346. // The canonical property name is `include`. We accept `paths` for backwards compatibility
  347. // with a bug in JSDoc 3.2.x.
  348. staticFilePaths = conf.default.staticFiles.include ||
  349. conf.default.staticFiles.paths ||
  350. [];
  351. staticFileFilter = new ( require( 'jsdoc/src/filter' ).Filter )( conf.default.staticFiles );
  352. staticFileScanner = new ( require( 'jsdoc/src/scanner' ).Scanner )();
  353. staticFilePaths.forEach( filePath => {
  354. filePath = path.resolve( env.pwd, filePath );
  355. const extraStaticFiles = staticFileScanner.scan( [ filePath ], 10, staticFileFilter );
  356. extraStaticFiles.forEach( fileName => {
  357. const sourcePath = fs.toDir( filePath );
  358. const toDir = fs.toDir( fileName.replace( sourcePath, outdir ) );
  359. fs.mkPath( toDir );
  360. fs.copyFileSync( fileName, toDir );
  361. } );
  362. } );
  363. }
  364. if ( sourceFilePaths.length ) {
  365. sourceFiles = shortenPaths( sourceFiles, path.commonPrefix( sourceFilePaths ) );
  366. }
  367. data().each( doclet => {
  368. let docletPath;
  369. const url = helper.createLink( doclet );
  370. helper.registerLink( doclet.longname, url );
  371. // add a shortened version of the full path
  372. if ( doclet.meta ) {
  373. docletPath = getPathFromDoclet( doclet );
  374. docletPath = sourceFiles[ docletPath ].shortened;
  375. if ( docletPath ) {
  376. doclet.meta.shortpath = docletPath;
  377. }
  378. }
  379. } );
  380. data().each( doclet => {
  381. const url = helper.longnameToUrl[ doclet.longname ];
  382. if ( url.includes( '#' ) ) {
  383. doclet.id = helper.longnameToUrl[ doclet.longname ].split( /#/ ).pop();
  384. } else {
  385. doclet.id = doclet.name;
  386. }
  387. if ( needsSignature( doclet ) ) {
  388. addSignatureParams( doclet );
  389. addSignatureReturns( doclet );
  390. addAttribs( doclet );
  391. }
  392. } );
  393. // do this after the urls have all been generated
  394. data().each( doclet => {
  395. doclet.ancestors = getAncestorLinks( doclet );
  396. if ( doclet.kind === 'member' ) {
  397. addSignatureTypes( doclet );
  398. addAttribs( doclet );
  399. }
  400. if ( doclet.kind === 'constant' ) {
  401. addSignatureTypes( doclet );
  402. addAttribs( doclet );
  403. doclet.kind = 'member';
  404. }
  405. } );
  406. // prepare import statements
  407. data().each( doclet => {
  408. if ( doclet.kind === 'class' || doclet.kind === 'module' ) {
  409. const tags = doclet.tags;
  410. if ( Array.isArray( tags ) ) {
  411. const importTag = tags.find( tag => tag.title === 'three_import' );
  412. doclet.import = ( importTag !== undefined ) ? importTag.text : null;
  413. }
  414. }
  415. } );
  416. const members = helper.getMembers( data );
  417. members.tutorials = tutorials.children;
  418. // output pretty-printed source files by default
  419. const outputSourceFiles = conf.default && conf.default.outputSourceFiles !== false;
  420. // add template helpers
  421. view.find = find;
  422. view.linkto = linkto;
  423. view.resolveAuthorLinks = resolveAuthorLinks;
  424. view.htmlsafe = htmlsafe;
  425. view.outputSourceFiles = outputSourceFiles;
  426. view.ignoreInheritedSymbols = themeOpts.ignoreInheritedSymbols;
  427. // Empty nav in templates - will be loaded from nav.html client-side
  428. view.nav = '';
  429. // generate the pretty-printed source files first so other pages can link to them
  430. if ( outputSourceFiles ) {
  431. generateSourceFiles( sourceFiles, opts.encoding );
  432. }
  433. if ( members.globals.length ) {
  434. generate( 'Global', [ { kind: 'globalobj' } ], globalUrl );
  435. }
  436. // index page displays information from package.json and lists files
  437. const files = find( { kind: 'file' } );
  438. const packages = find( { kind: 'package' } );
  439. generate( '', // MODIFIED (Remove Home title)
  440. packages.concat(
  441. [ {
  442. kind: 'mainpage',
  443. readme: opts.readme,
  444. longname: ( opts.mainpagetitle ) ? opts.mainpagetitle : 'Main Page'
  445. } ]
  446. ).concat( files ), indexUrl );
  447. // set up the lists that we'll use to generate pages
  448. const classes = taffy( members.classes );
  449. const modules = taffy( members.modules );
  450. Object.keys( helper.longnameToUrl ).forEach( longname => {
  451. const myClasses = helper.find( classes, { longname: longname } );
  452. const myModules = helper.find( modules, { longname: longname } );
  453. if ( myClasses.length ) {
  454. generate( `${myClasses[ 0 ].name}`, myClasses, helper.longnameToUrl[ longname ] );
  455. }
  456. if ( myModules.length ) {
  457. generate( `${myModules[ 0 ].name}`, myModules, helper.longnameToUrl[ longname ] );
  458. }
  459. } );
  460. // Write navigation to separate file
  461. fs.writeFileSync(
  462. path.join( outdir, 'nav.html' ),
  463. buildNav( members ),
  464. 'utf8'
  465. );
  466. // search
  467. const searchList = buildSearchListForData();
  468. mkdirSync( path.join( outdir, 'data' ) );
  469. fs.writeFileSync(
  470. path.join( outdir, 'data', 'search.json' ),
  471. JSON.stringify( {
  472. list: searchList,
  473. } )
  474. );
  475. };
粤ICP备19079148号