1
0

typescript-docs-renderer.ts 15 KB

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