Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
99 lines (82 loc) · 2.53 KB
/
Copy pathindex.js
File metadata and controls
99 lines (82 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import babelPlugin from "prettier/plugins/babel";
import estreePlugin from "prettier/plugins/estree";
import typescriptPlugin from "prettier/plugins/typescript";
import { builders } from "prettier/doc";
const { group } = builders;
export const parsers = {
...babelPlugin.parsers,
...typescriptPlugin.parsers,
};
export const printers = {
estree: {
// Inherit all default estree printer behavior (comment handling, etc.)
...estreePlugin.printers.estree,
print (path, options, print) {
let node = path.getValue();
if ([
// JavaScript node types
"FunctionDeclaration",
"FunctionExpression",
"ObjectMethod",
"MethodDefinition",
"ClassMethod",
"ClassPrivateMethod",
// TypeScript node types
"TSMethodSignature",
"TSDeclareFunction",
"TSAbstractMethodDefinition",
].includes(node.type) ||
// Handle object methods in TypeScript (Property is what TS uses instead of ObjectMethod)
(node.type === "Property" && (node.method || node.kind === "get" || node.kind === "set"))) {
// Skip anonymous functions (they are already formatted properly)
if (
(node.type === "FunctionExpression" || node.type === "FunctionDeclaration") &&
!node.id
) {
return estreePlugin.printers.estree.print(path, options, print);
}
let doc = estreePlugin.printers.estree.print(path, options, print);
// For decorated methods, search for "(" only after the method name
// to avoid matching "(" inside decorator arguments
let marker = node.decorators?.length ? (node.key?.name || node.key?.value) : null;
let contents = findContents(doc, marker);
if (contents) {
// Open paren is always the second item in the contents array
contents[1] = group([" ", "("]);
}
return doc;
}
return estreePlugin.printers.estree.print(path, options, print);
},
},
};
// Recursively find the (possibly nested) array with the first "(" in the doc produced by prettier.
// If `marker` is given, only match "(" that appears after the marker string (used for decorated methods).
function findContents (doc, marker) {
let found = !marker;
function search (node) {
if (!node) {
return null;
}
if (!found && node === marker) {
found = true;
return null;
}
if (node.type === "group") {
return search(node.contents);
}
if (Array.isArray(node)) {
if (found && node.includes("(")) {
return node;
}
for (let item of node) {
let result = search(item);
if (result) {
return result;
}
}
}
return null;
}
return search(doc);
}