|
1 | 1 | import { doc } from 'prettier'; |
| 2 | +import { createBinaryOperationPrinter } from './printers/create-binary-operation-printer.js'; |
| 3 | +import { createGroupIfNecessaryBuilder } from './printers/create-group-if-necessary-builder.js'; |
| 4 | +import { notIndentParentTypes } from './printers/create-indent-if-necessary-builder.js'; |
| 5 | +import { shouldGroupOrIndent } from './utils/should-group-or-indent.js'; |
2 | 6 |
|
3 | | -const { group, line, indent } = doc.builders; |
4 | | - |
5 | | -const groupIfNecessaryBuilder = (path) => (document) => |
6 | | - path.getParentNode().type === 'BinaryOperation' ? document : group(document); |
| 7 | +const { indent } = doc.builders; |
7 | 8 |
|
8 | 9 | const indentIfNecessaryBuilder = (path, options) => (document) => { |
9 | 10 | let node = path.getNode(); |
10 | 11 | for (let i = 0; ; i += 1) { |
11 | 12 | const parentNode = path.getParentNode(i); |
12 | | - if (parentNode.type === 'ReturnStatement') return document; |
13 | | - if (parentNode.type === 'IfStatement') return document; |
14 | | - if (parentNode.type === 'WhileStatement') return document; |
| 13 | + if (notIndentParentTypes.includes(parentNode.type)) return document; |
15 | 14 | if ( |
16 | 15 | options.experimentalTernaries && |
17 | 16 | parentNode.type === 'Conditional' && |
18 | 17 | parentNode.condition === node |
19 | 18 | ) |
20 | 19 | return document; |
21 | | - if (parentNode.type !== 'BinaryOperation') return indent(document); |
| 20 | + if (shouldGroupOrIndent(parentNode, [])) return indent(document); |
22 | 21 | if (node === parentNode.right) return document; |
23 | 22 | node = parentNode; |
24 | 23 | } |
25 | 24 | }; |
26 | 25 |
|
27 | 26 | export const logical = { |
28 | 27 | match: (op) => ['&&', '||'].includes(op), |
29 | | - print: (node, path, print, options) => { |
30 | | - const groupIfNecessary = groupIfNecessaryBuilder(path); |
31 | | - const indentIfNecessary = indentIfNecessaryBuilder(path, options); |
32 | | - |
33 | | - const right = [node.operator, line, path.call(print, 'right')]; |
34 | | - // If it's a single binary operation, avoid having a small right |
35 | | - // operand like - 1 on its own line |
36 | | - const shouldGroup = |
37 | | - node.left.type !== 'BinaryOperation' && |
38 | | - path.getParentNode().type !== 'BinaryOperation'; |
39 | | - return groupIfNecessary([ |
40 | | - path.call(print, 'left'), |
41 | | - ' ', |
42 | | - indentIfNecessary(shouldGroup ? group(right) : right) |
43 | | - ]); |
44 | | - } |
| 28 | + print: createBinaryOperationPrinter( |
| 29 | + createGroupIfNecessaryBuilder([]), |
| 30 | + indentIfNecessaryBuilder |
| 31 | + ) |
45 | 32 | }; |
0 commit comments