typescript-docs-renderer.ts 13 KB

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