|
| 1 | +import { DeclarationReflection, Reflection, ReflectionKind } from 'typedoc/dist/lib/models'; |
| 2 | +import ContainerRenderer from './container-renderer'; |
| 3 | +import join from '../util/join'; |
| 4 | + |
| 5 | +export default class ModuleRenderer extends ContainerRenderer { |
| 6 | + constructor() { |
| 7 | + super('module'); |
| 8 | + } |
| 9 | + |
| 10 | + public render(node: Reflection): string { |
| 11 | + if (this.isNamespace(node)) { |
| 12 | + let renderNode = node as DeclarationReflection; |
| 13 | + const nodeNames: string[] = []; |
| 14 | + let latestComment: string | undefined; |
| 15 | + let currentComment: string | undefined; |
| 16 | + |
| 17 | + do { |
| 18 | + currentComment = this.renderComment(renderNode); |
| 19 | + |
| 20 | + // cannot combine modules into namespace because comments differ |
| 21 | + if (latestComment && currentComment && latestComment !== currentComment) { |
| 22 | + break; |
| 23 | + } |
| 24 | + |
| 25 | + if (currentComment) { |
| 26 | + latestComment = currentComment; |
| 27 | + } |
| 28 | + |
| 29 | + nodeNames.push(renderNode.name); |
| 30 | + if (renderNode.children?.length === 1 && renderNode.children[0].kindOf(ReflectionKind.SomeModule)) { |
| 31 | + const nextNode = renderNode.children[0]; |
| 32 | + const nextComment = this.renderComment(nextNode); |
| 33 | + |
| 34 | + // cannot combine modules into namespace because comments differ |
| 35 | + if (latestComment && nextComment && latestComment !== nextComment) { |
| 36 | + break; |
| 37 | + } |
| 38 | + |
| 39 | + renderNode = nextNode; |
| 40 | + } else { |
| 41 | + break; |
| 42 | + } |
| 43 | + } while (this.isNamespace(renderNode)); |
| 44 | + |
| 45 | + const lines: string[] = []; |
| 46 | + const declarationParts: string[] = [ |
| 47 | + this.isTop(node) ? 'declare' : '', |
| 48 | + 'namespace', `${nodeNames.join('.')}` |
| 49 | + ]; |
| 50 | + |
| 51 | + if (latestComment) { |
| 52 | + this.pushIfTruthy(lines, latestComment); |
| 53 | + } |
| 54 | + |
| 55 | + lines.push(join(' ', ...declarationParts, '{')); |
| 56 | + |
| 57 | + const body = this.renderBody(renderNode); |
| 58 | + if (body) { |
| 59 | + lines.push(body); |
| 60 | + } |
| 61 | + |
| 62 | + lines.push('}'); |
| 63 | + |
| 64 | + return lines.join('\n'); |
| 65 | + } |
| 66 | + |
| 67 | + return super.render(node); |
| 68 | + } |
| 69 | + |
| 70 | + private isNamespace(node: Reflection) { |
| 71 | + const hasSpecialCharacterExpression = /[^\w]/; |
| 72 | + return !hasSpecialCharacterExpression.test(node.name); |
| 73 | + } |
| 74 | +} |
0 commit comments