typescript-docs-renderer.ts 8.5 KB

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