Tweak object destructuring in assignments (#10643)

This commit is contained in:
Georgii Dolzhykov authored and GitHub committed 2021-04-06 12:59:14 +03:00
1 parent 004ea98dc5
commit 7a5ccc581d
8 files changed
+174 -7

No files matched your search

+32 -1
View File
@@ -49,6 +49,9 @@ function printAssignment(
]);
}
case "break-lhs":
return group([leftDoc, operator, " ", group(rightDoc)]);
// Parts of assignment chains aren't wrapped in groups.
// Once one of them breaks, the chain breaks too.
case "chain":
@@ -96,7 +99,7 @@ function chooseLayout(path, options, leftDoc, rightPropertyName) {
const isTail = !isAssignment(rightNode);
const shouldUseChainFormatting = path.match(
isAssignment,
(node) => isAssignment(node) || node.type === "VariableDeclarator",
isAssignmentOrVariableDeclarator,
(node) =>
!isTail ||
(node.type !== "ExpressionStatement" &&
@@ -124,6 +127,10 @@ function chooseLayout(path, options, leftDoc, rightPropertyName) {
return "never-break-after-operator";
}
if (isComplexDestructuring(node)) {
return "break-lhs";
}
// wrapping object properties with very short keys usually doesn't add much value
const hasShortKey = isObjectPropertyWithShortKey(node, leftDoc, options);
@@ -195,10 +202,34 @@ function shouldNeverBreakAfterOperator(rightNode) {
);
}
// prefer to break destructuring assignment
// if it includes default values or non-shorthand properties
function isComplexDestructuring(node) {
if (isAssignmentOrVariableDeclarator(node)) {
const leftNode = node.left || node.id;
return (
leftNode.type === "ObjectPattern" &&
leftNode.properties.length > 2 &&
leftNode.properties.some(
(property) =>
(property.type === "ObjectProperty" ||
property.type === "Property") &&
(!property.shorthand ||
(property.value && property.value.type === "AssignmentPattern"))
)
);
}
return false;
}
function isAssignment(node) {
return node.type === "AssignmentExpression";
}
function isAssignmentOrVariableDeclarator(node) {
return isAssignment(node) || node.type === "VariableDeclarator";
}
function isMemberExpressionChainHead(node) {
return node.type === "Identifier" || node.type === "ThisExpression";
}
+10 -1
View File
@@ -225,7 +225,16 @@ function printObject(path, options, print) {
name === "this" ||
name === "rest") &&
number === 0
)
) ||
// Assignment printing logic (printAssignment) is responsible
// for adding a group if needed
(!shouldBreak &&
path.match(
(node) => node.type === "ObjectPattern",
(node) =>
node.type === "AssignmentExpression" ||
node.type === "VariableDeclarator"
))
) {
return content;
}