forked from prettier/prettier
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ternary.js
316 lines (297 loc) · 10.1 KB
/
ternary.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
"use strict";
const flat = require("lodash/flatten");
const { isJSXNode } = require("../utils");
const { hasNewlineInRange } = require("../../common/util");
const handleComments = require("../comments");
const {
builders: {
concat,
line,
softline,
group,
indent,
align,
ifBreak,
dedent,
breakParent,
},
} = require("../../document");
/**
* @typedef {import("../../document").Doc} Doc
* @typedef {import("../../common/fast-path")} FastPath
*
* @typedef {any} Options - Prettier options (TBD ...)
*
* @typedef {Object} OperatorOptions
* @property {() => Array<string | Doc>} beforeParts - Parts to print before the `?`.
* @property {(breakClosingParen: boolean) => Array<string | Doc>} afterParts - Parts to print after the conditional expression.
* @property {boolean} shouldCheckJsx - Whether to check for and print in JSX mode.
* @property {string} conditionalNodeType - The type of the conditional expression node, ie "ConditionalExpression" or "TSConditionalType".
* @property {string} consequentNodePropertyName - The property at which the consequent node can be found on the main node, eg "consequent".
* @property {string} alternateNodePropertyName - The property at which the alternate node can be found on the main node, eg "alternate".
* @property {string[]} testNodePropertyNames - The properties at which the test nodes can be found on the main node, eg "test".
*/
// If we have nested conditional expressions, we want to print them in JSX mode
// if there's at least one JSXElement somewhere in the tree.
//
// A conditional expression chain like this should be printed in normal mode,
// because there aren't JSXElements anywhere in it:
//
// isA ? "A" : isB ? "B" : isC ? "C" : "Unknown";
//
// But a conditional expression chain like this should be printed in JSX mode,
// because there is a JSXElement in the last ConditionalExpression:
//
// isA ? "A" : isB ? "B" : isC ? "C" : <span className="warning">Unknown</span>;
//
// This type of ConditionalExpression chain is structured like this in the AST:
//
// ConditionalExpression {
// test: ...,
// consequent: ...,
// alternate: ConditionalExpression {
// test: ...,
// consequent: ...,
// alternate: ConditionalExpression {
// test: ...,
// consequent: ...,
// alternate: ...,
// }
// }
// }
//
// We want to traverse over that shape and convert it into a flat structure so
// that we can find if there's a JSXElement somewhere inside.
function getConditionalChainContents(node) {
// Given this code:
//
// // Using a ConditionalExpression as the consequent is uncommon, but should
// // be handled.
// A ? B : C ? D : E ? F ? G : H : I
//
// which has this AST:
//
// ConditionalExpression {
// test: Identifier(A),
// consequent: Identifier(B),
// alternate: ConditionalExpression {
// test: Identifier(C),
// consequent: Identifier(D),
// alternate: ConditionalExpression {
// test: Identifier(E),
// consequent: ConditionalExpression {
// test: Identifier(F),
// consequent: Identifier(G),
// alternate: Identifier(H),
// },
// alternate: Identifier(I),
// }
// }
// }
//
// we should return this Array:
//
// [
// Identifier(A),
// Identifier(B),
// Identifier(C),
// Identifier(D),
// Identifier(E),
// Identifier(F),
// Identifier(G),
// Identifier(H),
// Identifier(I)
// ];
//
// This loses the information about whether each node was the test,
// consequent, or alternate, but we don't care about that here- we are only
// flattening this structure to find if there's any JSXElements inside.
const nonConditionalExpressions = [];
function recurse(node) {
if (node.type === "ConditionalExpression") {
recurse(node.test);
recurse(node.consequent);
recurse(node.alternate);
} else {
nonConditionalExpressions.push(node);
}
}
recurse(node);
return nonConditionalExpressions;
}
function conditionalExpressionChainContainsJSX(node) {
return getConditionalChainContents(node).some(isJSXNode);
}
/**
* The following is the shared logic for
* ternary operators, namely ConditionalExpression
* and TSConditionalType
* @param {FastPath} path - The path to the ConditionalExpression/TSConditionalType node.
* @param {Options} options - Prettier options
* @param {Function} print - Print function to call recursively
* @param {OperatorOptions} operatorOptions
* @returns {Doc}
*/
function printTernaryOperator(path, options, print, operatorOptions) {
const node = path.getValue();
const consequentNode = node[operatorOptions.consequentNodePropertyName];
const alternateNode = node[operatorOptions.alternateNodePropertyName];
const parts = [];
// We print a ConditionalExpression in either "JSX mode" or "normal mode".
// See tests/jsx/conditional-expression.js for more info.
let jsxMode = false;
const parent = path.getParentNode();
const isParentTest =
parent.type === operatorOptions.conditionalNodeType &&
operatorOptions.testNodePropertyNames.some((prop) => parent[prop] === node);
let forceNoIndent =
parent.type === operatorOptions.conditionalNodeType && !isParentTest;
// Find the outermost non-ConditionalExpression parent, and the outermost
// ConditionalExpression parent. We'll use these to determine if we should
// print in JSX mode.
let currentParent;
let previousParent;
let i = 0;
do {
previousParent = currentParent || node;
currentParent = path.getParentNode(i);
i++;
} while (
currentParent &&
currentParent.type === operatorOptions.conditionalNodeType &&
operatorOptions.testNodePropertyNames.every(
(prop) => currentParent[prop] !== previousParent
)
);
const firstNonConditionalParent = currentParent || parent;
const lastConditionalParent = previousParent;
if (
operatorOptions.shouldCheckJsx &&
(isJSXNode(node[operatorOptions.testNodePropertyNames[0]]) ||
isJSXNode(consequentNode) ||
isJSXNode(alternateNode) ||
conditionalExpressionChainContainsJSX(lastConditionalParent))
) {
jsxMode = true;
forceNoIndent = true;
// Even though they don't need parens, we wrap (almost) everything in
// parens when using ?: within JSX, because the parens are analogous to
// curly braces in an if statement.
const wrap = (doc) =>
concat([
ifBreak("(", ""),
indent(concat([softline, doc])),
softline,
ifBreak(")", ""),
]);
// The only things we don't wrap are:
// * Nested conditional expressions in alternates
// * null
// * undefined
const isNil = (node) =>
node.type === "NullLiteral" ||
(node.type === "Literal" && node.value === null) ||
(node.type === "Identifier" && node.name === "undefined");
parts.push(
" ? ",
isNil(consequentNode)
? path.call(print, operatorOptions.consequentNodePropertyName)
: wrap(path.call(print, operatorOptions.consequentNodePropertyName)),
" : ",
alternateNode.type === operatorOptions.conditionalNodeType ||
isNil(alternateNode)
? path.call(print, operatorOptions.alternateNodePropertyName)
: wrap(path.call(print, operatorOptions.alternateNodePropertyName))
);
} else {
// normal mode
const part = concat([
line,
"? ",
consequentNode.type === operatorOptions.conditionalNodeType
? ifBreak("", "(")
: "",
align(2, path.call(print, operatorOptions.consequentNodePropertyName)),
consequentNode.type === operatorOptions.conditionalNodeType
? ifBreak("", ")")
: "",
line,
": ",
alternateNode.type === operatorOptions.conditionalNodeType
? path.call(print, operatorOptions.alternateNodePropertyName)
: align(2, path.call(print, operatorOptions.alternateNodePropertyName)),
]);
parts.push(
parent.type !== operatorOptions.conditionalNodeType ||
parent[operatorOptions.alternateNodePropertyName] === node ||
isParentTest
? part
: options.useTabs
? dedent(indent(part))
: align(Math.max(0, options.tabWidth - 2), part)
);
}
// We want a whole chain of ConditionalExpressions to all
// break if any of them break. That means we should only group around the
// outer-most ConditionalExpression.
const comments = flat([
...operatorOptions.testNodePropertyNames.map(
(propertyName) => node[propertyName].comments
),
consequentNode.comments,
alternateNode.comments,
]).filter(Boolean);
const shouldBreak = comments.some(
(comment) =>
handleComments.isBlockComment(comment) &&
hasNewlineInRange(
options.originalText,
options.locStart(comment),
options.locEnd(comment)
)
);
const maybeGroup = (doc) =>
parent === firstNonConditionalParent
? group(doc, { shouldBreak })
: shouldBreak
? concat([doc, breakParent])
: doc;
// Break the closing paren to keep the chain right after it:
// (a
// ? b
// : c
// ).call()
const breakClosingParen =
!jsxMode &&
(parent.type === "MemberExpression" ||
parent.type === "OptionalMemberExpression" ||
(parent.type === "NGPipeExpression" && parent.left === node)) &&
!parent.computed;
const result = maybeGroup(
concat(
[].concat(
((testDoc) =>
/**
* a
* ? b
* : multiline
* test
* node
* ^^ align(2)
* ? d
* : e
*/
parent.type === operatorOptions.conditionalNodeType &&
parent[operatorOptions.alternateNodePropertyName] === node
? align(2, testDoc)
: testDoc)(concat(operatorOptions.beforeParts())),
forceNoIndent ? concat(parts) : indent(concat(parts)),
operatorOptions.afterParts(breakClosingParen)
)
)
);
return isParentTest
? group(concat([indent(concat([softline, result])), softline]))
: result;
}
module.exports = printTernaryOperator;