forked from prettier/prettier
/
decorators.js
84 lines (72 loc) · 2.21 KB
/
decorators.js
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
"use strict";
const { isNonEmptyArray, hasNewline } = require("../../common/util.js");
const {
builders: { line, hardline, join, breakParent, group },
} = require("../../document/index.js");
const { locStart, locEnd } = require("../loc.js");
const { getParentExportDeclaration } = require("../utils/index.js");
function printClassMemberDecorators(path, options, print) {
const node = path.getValue();
return group([
join(line, path.map(print, "decorators")),
hasNewlineBetweenOrAfterDecorators(node, options) ? hardline : line,
]);
}
function printDecoratorsBeforeExport(path, options, print) {
// Export declarations are responsible for printing any decorators
// that logically apply to node.declaration.
return [
join(hardline, path.map(print, "declaration", "decorators")),
hardline,
];
}
function printDecorators(path, options, print) {
const node = path.getValue();
const { decorators } = node;
if (
!isNonEmptyArray(decorators) ||
// If the parent node is an export declaration and the decorator
// was written before the export, the export will be responsible
// for printing the decorators.
hasDecoratorsBeforeExport(path.getParentNode())
) {
return;
}
const shouldBreak =
node.type === "ClassExpression" ||
node.type === "ClassDeclaration" ||
hasNewlineBetweenOrAfterDecorators(node, options);
return [
getParentExportDeclaration(path)
? hardline
: shouldBreak
? breakParent
: "",
join(line, path.map(print, "decorators")),
line,
];
}
function hasNewlineBetweenOrAfterDecorators(node, options) {
return node.decorators.some((decorator) =>
hasNewline(options.originalText, locEnd(decorator))
);
}
function hasDecoratorsBeforeExport(node) {
if (
node.type !== "ExportDefaultDeclaration" &&
node.type !== "ExportNamedDeclaration" &&
node.type !== "DeclareExportDeclaration"
) {
return false;
}
const decorators = node.declaration && node.declaration.decorators;
return (
isNonEmptyArray(decorators) && locStart(node) === locStart(decorators[0])
);
}
module.exports = {
printDecorators,
printClassMemberDecorators,
printDecoratorsBeforeExport,
hasDecoratorsBeforeExport,
};