forked from prettier/prettier
/
type-parameters.js
100 lines (89 loc) · 2.52 KB
/
type-parameters.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
"use strict";
const { printDanglingComments } = require("../../main/comments");
const {
builders: { concat, join, line, hardline, softline, group, indent, ifBreak },
} = require("../../document");
const {
hasDanglingComments,
isTestCall,
isBlockComment,
shouldPrintComma,
} = require("../utils");
const { shouldHugType } = require("./type-annotation");
const typeParametersGroupIds = new WeakMap();
function getTypeParametersGroupId(node) {
if (!typeParametersGroupIds.has(node)) {
typeParametersGroupIds.set(node, Symbol("typeParameters"));
}
return typeParametersGroupIds.get(node);
}
function printTypeParameters(path, options, print, paramsKey) {
const n = path.getValue();
if (!n[paramsKey]) {
return "";
}
// for TypeParameterDeclaration typeParameters is a single node
if (!Array.isArray(n[paramsKey])) {
return path.call(print, paramsKey);
}
const grandparent = path.getNode(2);
const isParameterInTestCall = grandparent != null && isTestCall(grandparent);
const shouldInline =
isParameterInTestCall ||
n[paramsKey].length === 0 ||
(n[paramsKey].length === 1 &&
(shouldHugType(n[paramsKey][0]) ||
(n[paramsKey][0].type === "GenericTypeAnnotation" &&
shouldHugType(n[paramsKey][0].id)) ||
(n[paramsKey][0].type === "TSTypeReference" &&
shouldHugType(n[paramsKey][0].typeName)) ||
n[paramsKey][0].type === "NullableTypeAnnotation"));
if (shouldInline) {
return concat([
"<",
join(", ", path.map(print, paramsKey)),
printDanglingCommentsForInline(path, options),
">",
]);
}
return group(
concat([
"<",
indent(
concat([
softline,
join(concat([",", line]), path.map(print, paramsKey)),
])
),
ifBreak(
options.parser !== "typescript" &&
options.parser !== "babel-ts" &&
shouldPrintComma(options, "all")
? ","
: ""
),
softline,
">",
]),
{ id: getTypeParametersGroupId(n) }
);
}
function printDanglingCommentsForInline(path, options) {
const n = path.getValue();
if (!hasDanglingComments(n)) {
return "";
}
const hasOnlyBlockComments = n.comments.every((comment) =>
isBlockComment(comment)
);
const printed = printDanglingComments(
path,
options,
/* sameIndent */ hasOnlyBlockComments
);
if (hasOnlyBlockComments) {
return printed;
}
return concat([printed, hardline]);
}
module.exports = { printTypeParameters, getTypeParametersGroupId };