typescript-docs-renderer.ts 12 KB

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