Skip to content

Commit

Permalink
fix (indentation): replace beforeStart with codeBefore
Browse files Browse the repository at this point in the history
  • Loading branch information
43081j committed Dec 20, 2021
1 parent 28978c2 commit b54e2bf
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
37 changes: 37 additions & 0 deletions lib/rules/indentation/__tests__/document-with-roots.js
@@ -0,0 +1,37 @@
'use strict';

const { parse: postcssParse, stringify, Document, Input } = require('postcss');
const { ruleName } = require('..');

const parse = (source, opts) => {
const doc = new Document();
const root = postcssParse(source, opts);

root.parent = doc;
root.document = doc;
doc.nodes.push(root);
doc.source = {
input: new Input(source, opts),
start: { line: 1, column: 1, offset: 0 },
};

return doc;
};

testRule({
ruleName,
config: [2],
fix: true,
customSyntax: {
parse,
stringify,
},

accept: [
{
code: '.foo {\n' + ' color: hotpink;\n' + '}',
},
],

reject: [],
});
8 changes: 5 additions & 3 deletions lib/rules/indentation/index.js
Expand Up @@ -93,7 +93,9 @@ const rule = (primary, secondaryOptions = {}, context) => {
// it is some other kind of separation, checked by some separate rule
if (
(lastIndexOfNewline !== -1 ||
(isFirstChild && (!getDocument(parent) || parent.raws.beforeStart.endsWith('\n')))) &&
(isFirstChild &&
(!getDocument(parent) ||
(parent.raws.codeBefore && parent.raws.codeBefore.endsWith('\n'))))) &&
before.slice(lastIndexOfNewline + 1) !== expectedOpeningBraceIndentation
) {
if (context.fix) {
Expand Down Expand Up @@ -607,7 +609,7 @@ function inferRootIndentLevel(root, baseIndentLevel, indentSize) {
let source = root.source.input.css;

source = source.replace(/^[^\r\n]+/, (firstLine) => {
const match = /(?:^|\n)([ \t]*)$/.exec(root.raws.beforeStart);
const match = root.raws.codeBefore && /(?:^|\n)([ \t]*)$/.exec(root.raws.codeBefore);

if (match) {
return match[1] + firstLine;
Expand All @@ -628,7 +630,7 @@ function inferRootIndentLevel(root, baseIndentLevel, indentSize) {
}

const indents = [];
const foundIndents = /(?:^|\n)([ \t]*)\S/m.exec(root.raws.beforeStart);
const foundIndents = root.raws.codeBefore && /(?:^|\n)([ \t]*)\S/m.exec(root.raws.codeBefore);

// The indent level of the CSS code block in non-CSS-like files is determined by the shortest indent of non-empty line.
if (foundIndents) {
Expand Down

0 comments on commit b54e2bf

Please sign in to comment.