0
# AST Node Transforms
1
2
Helper utilities for transforming and manipulating DocNode trees after parsing. These transforms are commonly used for cleaning up and optimizing parsed comments for rendering.
3
4
## Capabilities
5
6
### DocNodeTransforms
7
8
Static class providing utility functions for transforming DocNode trees.
9
10
```typescript { .api }
11
/**
12
* Helper functions that transform DocNode trees
13
*/
14
class DocNodeTransforms {
15
/**
16
* Collapses extra spacing characters from plain text nodes in paragraphs
17
* @param docParagraph - A DocParagraph containing nodes to be transformed
18
* @returns The transformed child nodes
19
*/
20
static trimSpacesInParagraphNodes(docParagraph: DocParagraph): ReadonlyArray<DocNode>;
21
}
22
```
23
24
**Usage Examples:**
25
26
```typescript
27
import { TSDocParser, DocNodeTransforms } from "@microsoft/tsdoc";
28
29
const parser = new TSDocParser();
30
const context = parser.parseString(`
31
/**
32
* This has extra spaces and
33
* line breaks with more spacing.
34
*/
35
`);
36
37
// Find paragraph nodes and apply transform
38
const findParagraphs = (node: DocNode): DocParagraph[] => {
39
const paragraphs: DocParagraph[] = [];
40
if (node instanceof DocParagraph) {
41
paragraphs.push(node);
42
}
43
for (const child of node.getChildNodes()) {
44
if (child) {
45
paragraphs.push(...findParagraphs(child));
46
}
47
}
48
return paragraphs;
49
};
50
51
const paragraphs = findParagraphs(context.docComment);
52
paragraphs.forEach(paragraph => {
53
// Apply spacing transformation
54
const transformedNodes = DocNodeTransforms.trimSpacesInParagraphNodes(paragraph);
55
console.log(`Original nodes: ${paragraph.getChildNodes().length}`);
56
console.log(`Transformed nodes: ${transformedNodes.length}`);
57
});
58
```
59
60
### Transform Use Cases
61
62
The spacing transform is particularly useful for:
63
64
- **HTML Rendering**: Where multiple spaces are equivalent to a single space
65
- **Markdown Output**: Where spaces can be misinterpreted as indented code blocks
66
- **Clean Text Extraction**: For generating readable plain text from comments
67
- **Optimization**: Reducing redundant whitespace nodes in the AST
68
69
**Before Transform:**
70
```
71
nodes: [
72
{ kind: PlainText, text: " Here are some " },
73
{ kind: SoftBreak },
74
{ kind: PlainText, text: " words" },
75
{ kind: SoftBreak },
76
{ kind: InlineTag, text: "{@inheritDoc}" },
77
{ kind: PlainText, text: "to process." },
78
{ kind: PlainText, text: " " }
79
]
80
```
81
82
**After Transform:**
83
```
84
nodes: [
85
{ kind: PlainText, text: "Here are some " },
86
{ kind: PlainText, text: "words " },
87
{ kind: InlineTag, text: "{@inheritDoc}" },
88
{ kind: PlainText, text: "to process." }
89
]
90
```
91
92
Note that `"words "` is not merged with the preceding node because DocPlainText excerpts cannot span multiple lines.