typescript-docs-renderer.ts 14 KB

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