typescript-docs-renderer.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. // tslint:disable:no-console
  2. import fs from 'fs-extra';
  3. import klawSync from 'klaw-sync';
  4. import path from 'path';
  5. import ts from 'typescript';
  6. import { assertNever } from '../../packages/common/src/shared-utils';
  7. import { deleteGeneratedDocs, generateFrontMatter } from './docgen-utils';
  8. import { ClassInfo, DeclarationInfo, EnumInfo, InterfaceInfo, ParsedDeclaration, TypeAliasInfo, TypeMap } from './typescript-docgen-types';
  9. export class TypescriptDocsRenderer {
  10. render(parsedDeclarations: ParsedDeclaration[], docsUrl: string, outputPath: string, typeMap: TypeMap): number {
  11. let generatedCount = 0;
  12. if (!fs.existsSync(outputPath)) {
  13. fs.mkdirs(outputPath);
  14. }
  15. for (const info of parsedDeclarations) {
  16. let markdown = '';
  17. switch (info.kind) {
  18. case 'interface':
  19. markdown = this.renderInterfaceOrClass(info, typeMap, docsUrl);
  20. break;
  21. case 'typeAlias':
  22. markdown = this.renderTypeAlias(info, typeMap, docsUrl);
  23. break;
  24. case 'class':
  25. markdown = this.renderInterfaceOrClass(info, typeMap, docsUrl);
  26. break;
  27. case 'enum':
  28. markdown = this.renderEnum(info, typeMap, docsUrl);
  29. break;
  30. default:
  31. assertNever(info);
  32. }
  33. const categoryDir = path.join(outputPath, info.category);
  34. const indexFile = path.join(categoryDir, '_index.md');
  35. if (!fs.existsSync(categoryDir)) {
  36. fs.mkdirsSync(categoryDir);
  37. }
  38. if (!fs.existsSync(indexFile)) {
  39. const indexFileContent = generateFrontMatter(info.category, 10, false) + `\n\n# ${info.category}`;
  40. fs.writeFileSync(indexFile, indexFileContent);
  41. generatedCount++;
  42. }
  43. fs.writeFileSync(path.join(categoryDir, info.fileName + '.md'), markdown);
  44. generatedCount++;
  45. }
  46. return generatedCount;
  47. }
  48. /**
  49. * Render the interface to a markdown string.
  50. */
  51. private renderInterfaceOrClass(info: InterfaceInfo | ClassInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  52. const { title, weight, category, description, members } = info;
  53. let output = '';
  54. output += generateFrontMatter(title, weight);
  55. output += `\n\n# ${title}\n\n`;
  56. output += this.renderGenerationInfoShortcode(info);
  57. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  58. output += `## Signature\n\n`;
  59. output += info.kind === 'interface' ? this.renderInterfaceSignature(info) : this.renderClassSignature(info);
  60. output += `## Members\n\n`;
  61. output += `${this.renderMembers(info, knownTypeMap, docsUrl)}\n`;
  62. return output;
  63. }
  64. /**
  65. * Render the type alias to a markdown string.
  66. */
  67. private renderTypeAlias(typeAliasInfo: TypeAliasInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  68. const { title, weight, description, type, fullText } = typeAliasInfo;
  69. let output = '';
  70. output += generateFrontMatter(title, weight);
  71. output += `\n\n# ${title}\n\n`;
  72. output += this.renderGenerationInfoShortcode(typeAliasInfo);
  73. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  74. output += `## Signature\n\n`;
  75. output += this.renderTypeAliasSignature(typeAliasInfo);
  76. if (typeAliasInfo.members) {
  77. output += `## Members\n\n`;
  78. output += `${this.renderMembers(typeAliasInfo, knownTypeMap, docsUrl)}\n`;
  79. }
  80. return output;
  81. }
  82. private renderEnum(enumInfo: EnumInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  83. const { title, weight, description, fullText } = enumInfo;
  84. let output = '';
  85. output += generateFrontMatter(title, weight);
  86. output += `\n\n# ${title}\n\n`;
  87. output += this.renderGenerationInfoShortcode(enumInfo);
  88. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  89. output += `## Signature\n\n`;
  90. output += this.renderEnumSignature(enumInfo);
  91. return output;
  92. }
  93. /**
  94. * Generates a markdown code block string for the interface signature.
  95. */
  96. private renderInterfaceSignature(interfaceInfo: InterfaceInfo): string {
  97. const { fullText, members } = interfaceInfo;
  98. let output = '';
  99. output += `\`\`\`TypeScript\n`;
  100. output += `interface ${fullText} `;
  101. if (interfaceInfo.extends) {
  102. output += interfaceInfo.extends + ' ';
  103. }
  104. output += `{\n`;
  105. output += members.map(member => ` ${member.fullText}`).join(`\n`);
  106. output += `\n}\n`;
  107. output += `\`\`\`\n`;
  108. return output;
  109. }
  110. private renderClassSignature(classInfo: ClassInfo): string {
  111. const { fullText, members } = classInfo;
  112. let output = '';
  113. output += `\`\`\`TypeScript\n`;
  114. output += `class ${fullText} `;
  115. if (classInfo.extends) {
  116. output += classInfo.extends + ' ';
  117. }
  118. if (classInfo.implements) {
  119. output += classInfo.implements + ' ';
  120. }
  121. output += `{\n`;
  122. output += members
  123. .map(member => {
  124. if (member.kind === 'method') {
  125. const args = member.parameters
  126. .map(p => {
  127. return `${p.name}: ${p.type}`;
  128. })
  129. .join(', ');
  130. if (member.fullText === 'constructor') {
  131. return ` constructor(${args})`;
  132. } else {
  133. return ` ${member.fullText}(${args}) => ${member.type};`;
  134. }
  135. } else {
  136. return ` ${member.fullText}`;
  137. }
  138. })
  139. .join(`\n`);
  140. output += `\n}\n`;
  141. output += `\`\`\`\n`;
  142. return output;
  143. }
  144. private renderTypeAliasSignature(typeAliasInfo: TypeAliasInfo): string {
  145. const { fullText, members, type } = typeAliasInfo;
  146. let output = '';
  147. output += `\`\`\`TypeScript\n`;
  148. output += `type ${fullText} = `;
  149. if (members) {
  150. output += `{\n`;
  151. output += members.map(member => ` ${member.fullText}`).join(`\n`);
  152. output += `\n}\n`;
  153. } else {
  154. output += type.getText() + `\n`;
  155. }
  156. output += `\`\`\`\n`;
  157. return output;
  158. }
  159. private renderEnumSignature(enumInfo: EnumInfo): string {
  160. const { fullText, members } = enumInfo;
  161. let output = '';
  162. output += `\`\`\`TypeScript\n`;
  163. output += `enum ${fullText} `;
  164. if (members) {
  165. output += `{\n`;
  166. output += members.map(member => {
  167. let line = member.description ? ` // ${member.description}\n` : '';
  168. line += ` ${member.fullText}`;
  169. return line;
  170. }).join(`\n`);
  171. output += `\n}\n`;
  172. }
  173. output += `\`\`\`\n`;
  174. return output;
  175. }
  176. private renderMembers(info: InterfaceInfo | ClassInfo | TypeAliasInfo | EnumInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  177. const { members, title } = info;
  178. let output = '';
  179. for (const member of members || []) {
  180. let defaultParam = '';
  181. let type = '';
  182. if (member.kind === 'property') {
  183. type = this.renderType(member.type, knownTypeMap, docsUrl);
  184. defaultParam = member.defaultValue
  185. ? `default="${this.renderType(member.defaultValue, knownTypeMap, docsUrl)}" `
  186. : '';
  187. } else {
  188. const args = member.parameters
  189. .map(p => {
  190. return `${p.name}: ${this.renderType(p.type, knownTypeMap, docsUrl)}`;
  191. })
  192. .join(', ');
  193. if (member.fullText === 'constructor') {
  194. type = `(${args}) => ${title}`;
  195. } else {
  196. type = `(${args}) => ${this.renderType(member.type, knownTypeMap, docsUrl)}`;
  197. }
  198. }
  199. output += `### ${member.name}\n\n`;
  200. output += `{{< member-info kind="${member.kind}" type="${type}" ${defaultParam}>}}\n\n`;
  201. output += `${this.renderDescription(member.description, knownTypeMap, docsUrl)}\n\n`;
  202. }
  203. return output;
  204. }
  205. private renderGenerationInfoShortcode(info: DeclarationInfo): string {
  206. const sourceFile = info.sourceFile.replace(/^\.\.\//, '');
  207. return `{{< generation-info sourceFile="${sourceFile}" sourceLine="${info.sourceLine}" packageName="${info.packageName}">}}\n\n`;
  208. }
  209. /**
  210. * This function takes a string representing a type (e.g. "Array<ShippingMethod>") and turns
  211. * and known types (e.g. "ShippingMethod") into hyperlinks.
  212. */
  213. private renderType(type: string, knownTypeMap: TypeMap, docsUrl: string): string {
  214. let typeText = type
  215. .trim()
  216. // encode HTML entities
  217. .replace(/[\u00A0-\u9999<>\&]/gim, i => '&#' + i.charCodeAt(0) + ';')
  218. // remove newlines
  219. .replace(/\n/g, ' ');
  220. for (const [key, val] of knownTypeMap) {
  221. const re = new RegExp(`\\b${key}\\b`, 'g');
  222. const strippedIndex = val.replace(/\/_index$/, '');
  223. typeText = typeText.replace(re, `<a href='${docsUrl}/${strippedIndex}/'>${key}</a>`);
  224. }
  225. return typeText;
  226. }
  227. /**
  228. * Replaces any `{@link Foo}` references in the description with hyperlinks.
  229. */
  230. private renderDescription(description: string, knownTypeMap: TypeMap, docsUrl: string): string {
  231. for (const [key, val] of knownTypeMap) {
  232. const re = new RegExp(`{@link\\s*${key}}`, 'g');
  233. description = description.replace(re, `<a href='${docsUrl}/${val}/'>${key}</a>`);
  234. }
  235. return description;
  236. }
  237. }