| 1 | import { DocNode, DocExcerpt } from "@microsoft/tsdoc"; |
| 2 | |
| 3 | export class Formatter { |
| 4 | public static renderDocNode(docNode: DocNode | undefined): string { |
| 5 | let result = ""; |
| 6 | if (docNode) { |
| 7 | if (docNode instanceof DocExcerpt) { |
| 8 | result += docNode.content.toString(); |
| 9 | } |
| 10 | for (const childNode of docNode.getChildNodes()) { |
| 11 | result += Formatter.renderDocNode(childNode); |
| 12 | } |
| 13 | } |
| 14 | return result; |
| 15 | } |
| 16 | |
| 17 | public static renderDocNodes(docNodes: ReadonlyArray<DocNode>): string { |
| 18 | let result = ""; |
| 19 | for (const docNode of docNodes) { |
| 20 | result += Formatter.renderDocNode(docNode); |
| 21 | } |
| 22 | return result; |
| 23 | } |
| 24 | |
| 25 | private static matchInitialWhitespaces(str: string) { |
| 26 | return str.match(/^\s+/g)?.[0].length ?? 0; |
| 27 | } |
| 28 | |
| 29 | private static INDENTATION_WHITESPACES = 2; |
| 30 | |
| 31 | public static indentDeclaration(declaration: string): string { |
| 32 | const lines = declaration.trim().split("\n"); |
| 33 | if (lines.length > 1) { |
| 34 | let indentChars = 0; |
| 35 | // this is set to the indentation of the first line which does not have whitespaces at the beginning |
| 36 | let previousIndentedChars = |
| 37 | this.matchInitialWhitespaces(lines[1]) - this.INDENTATION_WHITESPACES; |
| 38 | |
| 39 | const indentedLines: string[] = [lines[0]]; |
| 40 | for (let i = 1; i < lines.length; i += 1) { |
| 41 | const line = lines[i]; |
| 42 | const currentIndentedChars = this.matchInitialWhitespaces(line); |
| 43 | const indentCharDiff = currentIndentedChars - previousIndentedChars; |
| 44 | if (indentCharDiff !== 0) { |
| 45 | indentChars += indentCharDiff; |
| 46 | } |
| 47 | previousIndentedChars = currentIndentedChars; |
| 48 | indentedLines.push(`${" ".repeat(indentChars)}${line.trim()}`); |
| 49 | } |
| 50 | |
| 51 | return indentedLines.join("\n"); |
| 52 | } |
| 53 | return lines[0]; |
| 54 | } |
| 55 | } |