typescript-docs-renderer.ts 12 KB

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