Skip to content

[Update] Make vue/max-attributes-per-line fixable #380

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 31 additions & 3 deletions lib/rules/max-attributes-per-line.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@
// ------------------------------------------------------------------------------
const utils = require('../utils')

const LT_CHAR = /[\r\n\u2028\u2029]/

module.exports = {
meta: {
docs: {
description: 'enforce the maximum number of attributes per line',
category: 'strongly-recommended',
url: 'https://github.com/vuejs/eslint-plugin-vue/blob/v4.2.2/docs/rules/max-attributes-per-line.md'
},
fixable: null,
fixable: 'whitespace', // or "code" or "whitespace"
schema: [
{
type: 'object',
Expand Down Expand Up @@ -70,6 +72,7 @@ module.exports = {
const multilineMaximum = configuration.multiline
const singlelinemMaximum = configuration.singleline
const canHaveFirstLine = configuration.allowFirstLine
const sourceCode = context.getSourceCode()

return utils.defineTemplateBodyVisitor(context, {
'VStartTag' (node) {
Expand Down Expand Up @@ -129,14 +132,24 @@ module.exports = {
}

function showErrors (attributes, node) {
attributes.forEach((prop) => {
attributes.forEach((prop, i) => {
context.report({
node: prop,
loc: prop.loc,
message: 'Attribute "{{propName}}" should be on a new line.',
data: {
propName: prop.key.name
}
},
fix: i === 0 ? (fixer) => {
let indent = getIndentText(prop)
const last = indent[indent.length - 1]
if (indent[indent.length - 1] === '\t') {
indent += '\t'
} else {
indent += last + last
}
return fixer.insertTextBefore(prop, `\n${indent}`)
} : undefined
})
})
}
Expand All @@ -155,5 +168,20 @@ module.exports = {

return propsPerLine
}

function getIndentText (node) {
const text = sourceCode.text
let indentStart = node.range[0] - 1
while (indentStart >= 0 && !LT_CHAR.test(text[indentStart])) {
indentStart -= 1
}
let indentEnd = indentStart + 1

while (!text[indentEnd].trim()) {
indentEnd += 1
}

return text.slice(indentStart + 1, indentEnd)
}
}
}