typescript-docs-renderer.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. /* eslint-disable no-console */
  2. import fs from 'fs-extra';
  3. import path from 'path';
  4. import { HeritageClause } from 'typescript';
  5. import { assertNever } from '../../packages/common/src/shared-utils';
  6. import { generateFrontMatter } from './docgen-utils';
  7. import {
  8. ClassInfo,
  9. DeclarationInfo,
  10. DocsPage,
  11. EnumInfo,
  12. FunctionInfo,
  13. InterfaceInfo,
  14. MethodParameterInfo,
  15. TypeAliasInfo,
  16. TypeMap,
  17. VariableInfo,
  18. } from './typescript-docgen-types';
  19. export class TypescriptDocsRenderer {
  20. render(pages: DocsPage[], docsUrl: string, outputPath: string, typeMap: TypeMap): number {
  21. let generatedCount = 0;
  22. if (!fs.existsSync(outputPath)) {
  23. fs.mkdirs(outputPath);
  24. }
  25. for (const page of pages) {
  26. let markdown = '';
  27. markdown += generateFrontMatter(page.title, 10);
  28. markdown += `\n# ${page.title}\n`;
  29. const declarationsByWeight = page.declarations.sort((a, b) => a.weight - b.weight);
  30. for (const info of declarationsByWeight) {
  31. markdown += '<div class="symbol">\n';
  32. switch (info.kind) {
  33. case 'interface':
  34. markdown += this.renderInterfaceOrClass(info, typeMap, docsUrl);
  35. break;
  36. case 'typeAlias':
  37. markdown += this.renderTypeAlias(info, typeMap, docsUrl);
  38. break;
  39. case 'class':
  40. markdown += this.renderInterfaceOrClass(info, typeMap, docsUrl);
  41. break;
  42. case 'enum':
  43. markdown += this.renderEnum(info, typeMap, docsUrl);
  44. break;
  45. case 'function':
  46. markdown += this.renderFunction(info, typeMap, docsUrl);
  47. break;
  48. case 'variable':
  49. markdown += this.renderVariable(info, typeMap, docsUrl);
  50. break;
  51. default:
  52. assertNever(info);
  53. }
  54. markdown += '</div>\n';
  55. }
  56. const categoryDir = path.join(outputPath, ...page.category);
  57. if (!fs.existsSync(categoryDir)) {
  58. fs.mkdirsSync(categoryDir);
  59. }
  60. const pathParts = [];
  61. for (const subCategory of page.category) {
  62. pathParts.push(subCategory);
  63. const indexFile = path.join(outputPath, ...pathParts, '_index.md');
  64. if (!fs.existsSync(indexFile)) {
  65. const indexFileContent =
  66. generateFrontMatter(subCategory, 10, false) + `\n\n# ${subCategory}`;
  67. fs.writeFileSync(indexFile, indexFileContent);
  68. generatedCount++;
  69. }
  70. }
  71. fs.writeFileSync(path.join(categoryDir, page.fileName + '.md'), markdown);
  72. generatedCount++;
  73. }
  74. return generatedCount;
  75. }
  76. /**
  77. * Render the interface to a markdown string.
  78. */
  79. private renderInterfaceOrClass(
  80. info: InterfaceInfo | ClassInfo,
  81. knownTypeMap: TypeMap,
  82. docsUrl: string,
  83. ): string {
  84. const { title, weight, category, description, members } = info;
  85. let output = '';
  86. output += `\n\n# ${title}\n\n`;
  87. output += this.renderGenerationInfoShortcode(info);
  88. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  89. output += '## Signature\n\n';
  90. output +=
  91. info.kind === 'interface' ? this.renderInterfaceSignature(info) : this.renderClassSignature(info);
  92. if (info.extendsClause) {
  93. output += '## Extends\n\n';
  94. output += `${this.renderHeritageClause(info.extendsClause, knownTypeMap, docsUrl)}\n`;
  95. }
  96. if (info.kind === 'class' && info.implementsClause) {
  97. output += '## Implements\n\n';
  98. output += `${this.renderHeritageClause(info.implementsClause, knownTypeMap, docsUrl)}\n`;
  99. }
  100. if (info.members && info.members.length) {
  101. output += '## Members\n\n';
  102. output += `${this.renderMembers(info, knownTypeMap, docsUrl)}\n`;
  103. }
  104. return output;
  105. }
  106. /**
  107. * Render the type alias to a markdown string.
  108. */
  109. private renderTypeAlias(typeAliasInfo: TypeAliasInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  110. const { title, weight, description, type, fullText } = typeAliasInfo;
  111. let output = '';
  112. output += `\n\n# ${title}\n\n`;
  113. output += this.renderGenerationInfoShortcode(typeAliasInfo);
  114. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  115. output += '## Signature\n\n';
  116. output += this.renderTypeAliasSignature(typeAliasInfo);
  117. if (typeAliasInfo.members && typeAliasInfo.members.length) {
  118. output += '## Members\n\n';
  119. output += `${this.renderMembers(typeAliasInfo, knownTypeMap, docsUrl)}\n`;
  120. }
  121. return output;
  122. }
  123. private renderEnum(enumInfo: EnumInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  124. const { title, weight, description, fullText } = enumInfo;
  125. let output = '';
  126. output += `\n\n# ${title}\n\n`;
  127. output += this.renderGenerationInfoShortcode(enumInfo);
  128. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  129. output += '## Signature\n\n';
  130. output += this.renderEnumSignature(enumInfo);
  131. return output;
  132. }
  133. private renderFunction(functionInfo: FunctionInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  134. const { title, weight, description, fullText, parameters } = functionInfo;
  135. let output = '';
  136. output += `\n\n# ${title}\n\n`;
  137. output += this.renderGenerationInfoShortcode(functionInfo);
  138. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  139. output += '## Signature\n\n';
  140. output += this.renderFunctionSignature(functionInfo, knownTypeMap);
  141. if (parameters.length) {
  142. output += '## Parameters\n\n';
  143. output += this.renderFunctionParams(parameters, knownTypeMap, docsUrl);
  144. }
  145. return output;
  146. }
  147. private renderVariable(variableInfo: VariableInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  148. const { title, weight, description, fullText } = variableInfo;
  149. let output = '';
  150. output += `\n\n# ${title}\n\n`;
  151. output += this.renderGenerationInfoShortcode(variableInfo);
  152. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  153. return output;
  154. }
  155. /**
  156. * Generates a markdown code block string for the interface signature.
  157. */
  158. private renderInterfaceSignature(interfaceInfo: InterfaceInfo): string {
  159. const { fullText, members } = interfaceInfo;
  160. let output = '';
  161. output += '```TypeScript\n';
  162. output += `interface ${fullText} `;
  163. if (interfaceInfo.extendsClause) {
  164. output += interfaceInfo.extendsClause.getText() + ' ';
  165. }
  166. output += '{\n';
  167. output += members.map(member => ` ${member.fullText}`).join('\n');
  168. output += '\n}\n';
  169. output += '```\n';
  170. return output;
  171. }
  172. private renderClassSignature(classInfo: ClassInfo): string {
  173. const { fullText, members } = classInfo;
  174. let output = '';
  175. output += '```TypeScript\n';
  176. output += `class ${fullText} `;
  177. if (classInfo.extendsClause) {
  178. output += classInfo.extendsClause.getText() + ' ';
  179. }
  180. if (classInfo.implementsClause) {
  181. output += classInfo.implementsClause.getText() + ' ';
  182. }
  183. output += '{\n';
  184. const renderModifiers = (modifiers: string[]) => (modifiers.length ? modifiers.join(' ') + ' ' : '');
  185. output += members
  186. .map(member => {
  187. if (member.kind === 'method') {
  188. const args = member.parameters.map(p => this.renderParameter(p, p.type)).join(', ');
  189. if (member.fullText === 'constructor') {
  190. return ` constructor(${args})`;
  191. } else {
  192. return ` ${renderModifiers(member.modifiers)}${member.fullText}(${args}) => ${
  193. member.type
  194. };`;
  195. }
  196. } else {
  197. return ` ${renderModifiers(member.modifiers)}${member.fullText}`;
  198. }
  199. })
  200. .join('\n');
  201. output += '\n}\n';
  202. output += '```\n';
  203. return output;
  204. }
  205. private renderTypeAliasSignature(typeAliasInfo: TypeAliasInfo): string {
  206. const { fullText, members, type } = typeAliasInfo;
  207. let output = '';
  208. output += '```TypeScript\n';
  209. output += `type ${fullText} = `;
  210. if (members) {
  211. output += '{\n';
  212. output += members.map(member => ` ${member.fullText}`).join('\n');
  213. output += '\n}\n';
  214. } else {
  215. output += type.getText() + '\n';
  216. }
  217. output += '```\n';
  218. return output;
  219. }
  220. private renderEnumSignature(enumInfo: EnumInfo): string {
  221. const { fullText, members } = enumInfo;
  222. let output = '';
  223. output += '```TypeScript\n';
  224. output += `enum ${fullText} `;
  225. if (members) {
  226. output += '{\n';
  227. output += members
  228. .map(member => {
  229. let line = member.description ? ` // ${member.description}\n` : '';
  230. line += ` ${member.fullText}`;
  231. return line;
  232. })
  233. .join('\n');
  234. output += '\n}\n';
  235. }
  236. output += '```\n';
  237. return output;
  238. }
  239. private renderFunctionSignature(functionInfo: FunctionInfo, knownTypeMap: TypeMap): string {
  240. const { fullText, parameters, type } = functionInfo;
  241. const args = parameters.map(p => this.renderParameter(p, p.type)).join(', ');
  242. let output = '';
  243. output += '```TypeScript\n';
  244. output += `function ${fullText}(${args}): ${type ? type.getText() : 'void'}\n`;
  245. output += '```\n';
  246. return output;
  247. }
  248. private renderFunctionParams(
  249. params: MethodParameterInfo[],
  250. knownTypeMap: TypeMap,
  251. docsUrl: string,
  252. ): string {
  253. let output = '';
  254. for (const param of params) {
  255. const type = this.renderType(param.type, knownTypeMap, docsUrl);
  256. output += `### ${param.name}\n\n`;
  257. output += `{{< member-info kind="parameter" type="${type}" >}}\n\n`;
  258. }
  259. return output;
  260. }
  261. private renderMembers(
  262. info: InterfaceInfo | ClassInfo | TypeAliasInfo | EnumInfo,
  263. knownTypeMap: TypeMap,
  264. docsUrl: string,
  265. ): string {
  266. const { members, title } = info;
  267. let output = '';
  268. for (const member of members || []) {
  269. let defaultParam = '';
  270. let sinceParam = '';
  271. let experimentalParam = '';
  272. let type = '';
  273. if (member.kind === 'property') {
  274. type = this.renderType(member.type, knownTypeMap, docsUrl);
  275. defaultParam = member.defaultValue
  276. ? `default="${this.renderType(member.defaultValue, knownTypeMap, docsUrl)}" `
  277. : '';
  278. } else {
  279. const args = member.parameters
  280. .map(p => this.renderParameter(p, this.renderType(p.type, knownTypeMap, docsUrl)))
  281. .join(', ');
  282. if (member.fullText === 'constructor') {
  283. type = `(${args}) => ${title}`;
  284. } else {
  285. type = `(${args}) => ${this.renderType(member.type, knownTypeMap, docsUrl)}`;
  286. }
  287. }
  288. if (member.since) {
  289. sinceParam = `since="${member.since}" `;
  290. }
  291. if (member.experimental) {
  292. experimentalParam = 'experimental="true"';
  293. }
  294. output += `### ${member.name}\n\n`;
  295. output += `{{< member-info kind="${[member.kind].join(
  296. ' ',
  297. )}" type="${type}" ${defaultParam} ${sinceParam}${experimentalParam}>}}\n\n`;
  298. output += `{{< member-description >}}${this.renderDescription(
  299. member.description,
  300. knownTypeMap,
  301. docsUrl,
  302. )}{{< /member-description >}}\n\n`;
  303. }
  304. return output;
  305. }
  306. private renderHeritageClause(clause: HeritageClause, knownTypeMap: TypeMap, docsUrl: string) {
  307. return (
  308. clause.types.map(t => ` * ${this.renderType(t.getText(), knownTypeMap, docsUrl)}`).join('\n') +
  309. '\n\n'
  310. );
  311. }
  312. private renderParameter(p: MethodParameterInfo, typeString: string): string {
  313. return `${p.name}${p.optional ? '?' : ''}: ${typeString}${
  314. p.initializer ? ` = ${p.initializer}` : ''
  315. }`;
  316. }
  317. private renderGenerationInfoShortcode(info: DeclarationInfo): string {
  318. const sourceFile = info.sourceFile.replace(/^\.\.\//, '');
  319. let sinceData = '';
  320. if (info.since) {
  321. sinceData = ` since="${info.since}"`;
  322. }
  323. let experimental = '';
  324. if (info.experimental) {
  325. experimental = ' experimental="true"';
  326. }
  327. return `{{< generation-info sourceFile="${sourceFile}" sourceLine="${info.sourceLine}" packageName="${info.packageName}"${sinceData}${experimental}>}}\n\n`;
  328. }
  329. /**
  330. * This function takes a string representing a type (e.g. "Array<ShippingMethod>") and turns
  331. * and known types (e.g. "ShippingMethod") into hyperlinks.
  332. */
  333. private renderType(type: string, knownTypeMap: TypeMap, docsUrl: string): string {
  334. let typeText = type
  335. .trim()
  336. // encode HTML entities
  337. .replace(/[\u00A0-\u9999<>\&]/gim, i => '&#' + i.charCodeAt(0) + ';')
  338. // remove newlines
  339. .replace(/\n/g, ' ');
  340. for (const [key, val] of knownTypeMap) {
  341. const re = new RegExp(`\\b${key}\\b`, 'g');
  342. const strippedIndex = val.replace(/\/_index$/, '');
  343. typeText = typeText.replace(re, `<a href='${docsUrl}/${strippedIndex}'>${key}</a>`);
  344. }
  345. return typeText;
  346. }
  347. /**
  348. * Replaces any `{@link Foo}` references in the description with hyperlinks.
  349. */
  350. private renderDescription(description: string, knownTypeMap: TypeMap, docsUrl: string): string {
  351. for (const [key, val] of knownTypeMap) {
  352. const re = new RegExp(`{@link\\s*${key}}`, 'g');
  353. description = description.replace(re, `<a href='${docsUrl}/${val}'>${key}</a>`);
  354. }
  355. return description;
  356. }
  357. }