Skip to content

Commit 05b25ec

Browse files
committed
fix: avoid unsafe jsx-sort-props line comment autofix
1 parent c9a2de7 commit 05b25ec

2 files changed

Lines changed: 35 additions & 4 deletions

File tree

lib/rules/jsx-sort-props.js

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -220,7 +220,7 @@ function getGroupsOfSortableAttributes(attributes, context) {
220220
} else if (firstComment.type === 'Block') {
221221
attributeMap.set(attribute, { end: firstComment.range[1], hasComment: true });
222222
} else {
223-
attributeMap.set(attribute, { end: firstComment.range[1], hasComment: false });
223+
attributeMap.set(attribute, { end: firstComment.range[1], hasComment: false, hasTrailingLineComment: true });
224224
}
225225
addtoSortableAttributeGroups(attribute);
226226
}
@@ -274,6 +274,16 @@ function generateFixerFunction(node, context, reservedList) {
274274
const sortedAttributeGroups = sortableAttributeGroups
275275
.slice(0)
276276
.map((group) => toSorted(group, (a, b) => contextCompare(a, b, options)));
277+
const hasUnsafeTrailingLineCommentFix = sortableAttributeGroups.some(
278+
(sortableGroup, groupIndex) => sortableGroup.some((attribute, attributeIndex) => {
279+
const sortedAttribute = sortedAttributeGroups[groupIndex][attributeIndex];
280+
const attr = attributeMap.get(sortedAttribute);
281+
return attr && attr.hasTrailingLineComment && attribute.loc.end.line === node.loc.end.line;
282+
})
283+
);
284+
if (hasUnsafeTrailingLineCommentFix) {
285+
return null;
286+
}
277287

278288
return function fixFunction(fixer) {
279289
const fixers = [];
@@ -364,10 +374,15 @@ function reportNodeAttribute(nodeAttribute, errorType, node, context, reservedLi
364374

365375
reportedNodeAttributes.set(nodeAttribute, errors);
366376

367-
report(context, messages[errorType], errorType, {
377+
const fix = generateFixerFunction(node, context, reservedList);
378+
const reportConfig = {
368379
node: nodeAttribute.name,
369-
fix: generateFixerFunction(node, context, reservedList),
370-
});
380+
};
381+
if (fix) {
382+
reportConfig.fix = fix;
383+
}
384+
385+
report(context, messages[errorType], errorType, reportConfig);
371386
}
372387

373388
/** @type {import('eslint').Rule.RuleModule} */

tests/lib/rules/jsx-sort-props.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1127,6 +1127,22 @@ ruleTester.run('jsx-sort-props', rule, {
11271127
},
11281128
],
11291129
} : [],
1130+
semver.satisfies(eslintPkg.version, '> 3') ? {
1131+
code: `
1132+
<div
1133+
onClick={() => console.log()} // Comment
1134+
className="flex">
1135+
<span>Problematic Component</span>
1136+
</div>
1137+
`,
1138+
output: null,
1139+
errors: [
1140+
{
1141+
messageId: 'sortPropsByAlpha',
1142+
line: 4,
1143+
},
1144+
],
1145+
} : [],
11301146
{
11311147
code: `
11321148
<Page

0 commit comments

Comments
 (0)