@stylistic/stylelint-plugin
Version:
A collection of stylistic/formatting Stylelint rules
95 lines (73 loc) • 2.75 kB
JavaScript
import stylelint from "stylelint"
import { addNamespace } from "../../utils/addNamespace/index.js"
import { declarationValueIndex } from "../../utils/declarationValueIndex/index.js"
import { getDeclarationValue } from "../../utils/getDeclarationValue/index.js"
import { getRuleDocUrl } from "../../utils/getRuleDocUrl/index.js"
import { setDeclarationValue } from "../../utils/setDeclarationValue/index.js"
import { valueListCommaWhitespaceChecker } from "../../utils/valueListCommaWhitespaceChecker/index.js"
import { whitespaceChecker } from "../../utils/whitespaceChecker/index.js"
let { utils: { ruleMessages, validateOptions } } = stylelint
let shortName = `value-list-comma-space-after`
export let ruleName = addNamespace(shortName)
export let messages = ruleMessages(ruleName, {
expectedAfter: () => `Expected single space after ","`,
rejectedAfter: () => `Unexpected whitespace after ","`,
expectedAfterSingleLine: () => `Expected single space after "," in a single-line list`,
rejectedAfterSingleLine: () => `Unexpected whitespace after "," in a single-line list`,
})
export let meta = {
url: getRuleDocUrl(shortName),
fixable: true,
}
/** @type {import('stylelint').Rule} */
function rule (primary) {
let checker = whitespaceChecker(`space`, primary, messages)
return (root, result) => {
let validOptions = validateOptions(result, ruleName, {
actual: primary,
possible: [`always`, `never`, `always-single-line`, `never-single-line`],
})
if (!validOptions) {
return
}
/** @type {Map<import('postcss').Declaration, number[]> | undefined} */
let fixData
valueListCommaWhitespaceChecker({
root,
result,
locationChecker: checker.after,
checkedRuleName: ruleName,
fix: (declNode, index) => {
let valueIndex = declarationValueIndex(declNode)
if (index <= valueIndex) {
return false
}
fixData = fixData || (new Map)
let commaIndices = fixData.get(declNode) || []
commaIndices.push(index)
fixData.set(declNode, commaIndices)
return true
},
})
if (fixData) {
for (let [decl, commaIndices] of fixData.entries()) {
for (let index of commaIndices.sort((a, b) => b - a)) {
let value = getDeclarationValue(decl)
let valueIndex = index - declarationValueIndex(decl)
let beforeValue = value.slice(0, valueIndex + 1)
let afterValue = value.slice(valueIndex + 1)
if (primary.startsWith(`always`)) {
afterValue = afterValue.replace(/^\s*/, ` `)
} else if (primary.startsWith(`never`)) {
afterValue = afterValue.replace(/^\s*/, ``)
}
setDeclarationValue(decl, beforeValue + afterValue)
}
}
}
}
}
rule.ruleName = ruleName
rule.messages = messages
rule.meta = meta
export default rule