Skip to content

Commit

Permalink
fix: objects indent and line break
Browse files Browse the repository at this point in the history
  • Loading branch information
ahmadkzx committed Mar 12, 2023
1 parent a4d3836 commit 416e40a
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/rules/waterfall-objects.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { sortByLength, getReplaceRange, getNodesTexts } = require('../utils')
const { sortByLength, getReplaceRange, getNodesTexts, applyObjectPropertiesIndent } = require('../utils')

const WaterfallObjects = {
meta: {
Expand Down Expand Up @@ -48,7 +48,9 @@ const WaterfallObjects = {
const sortedPropertiesText = getNodesTexts(sortedProperties, src).join('')

if (sortedPropertiesText !== propertiesText) {
const text = getNodesTexts(sortedProperties, src)
let text = getNodesTexts(sortedProperties, src)
text = applyObjectPropertiesIndent(text, /*object node*/ node, src)
text = text.join(',\n')
const range = getReplaceRange(properties)

context.report({
Expand All @@ -74,7 +76,9 @@ const WaterfallObjects = {
const sortedPropertiesText = getNodesTexts(sortedProperties, src).join('')

if (sortedPropertiesText !== propertiesText) {
const text = getNodesTexts(sortedProperties, src)
let text = getNodesTexts(sortedProperties, src)
text = applyObjectPropertiesIndent(text, /*object node*/ node, src)
text = text.join(',\n')
const range = getReplaceRange(properties)

context.report({
Expand Down
30 changes: 30 additions & 0 deletions src/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,40 @@ function fixIndent(str) {
return lines.join('\n')
}

/**
* Get object properties indent by catch first property indent
* @param {string[]} properties
* @param objectNode - ESTree AST nodes
* @param src - Source context
* @returns {string}
*/
function applyObjectPropertiesIndent(properties, objectNode, src) {
const text = src.getText(objectNode)
/*
{
test: 1,
...
}
*/
const lines = text.split('\n') // => ['{', ' test: 1,', ...]
const indentStr = lines[1].match(/^\s*/)[0]

return properties.map((prop, i) => {
if (i === 0 /*first prop always has indent*/) {
return prop
} else {
return indentStr + prop
}
})
}



module.exports = {
fixIndent,
sortByLength,
getNodeLength,
getNodesTexts,
getReplaceRange,
applyObjectPropertiesIndent
}

0 comments on commit 416e40a

Please sign in to comment.