From 64ff5c55b16851ed0dc186fda2772383673f464d Mon Sep 17 00:00:00 2001 From: Ulyanov Ivan Date: Fri, 1 Nov 2024 20:13:28 +0400 Subject: [PATCH] Fixed an incorrect nesting error (#167) * Fixed a bug that could cause regexp to issue an error * Tests have been changed * Fixed the error of incorrect processing of several rules * Added a test for several rules with comments --- index.js | 40 +++++++++++++++------------------------- index.test.js | 39 ++++++++++++++++++++------------------- 2 files changed, 35 insertions(+), 44 deletions(-) diff --git a/index.js b/index.js index d8652db..4b479b1 100644 --- a/index.js +++ b/index.js @@ -75,35 +75,25 @@ function mergeSelectors(parent, child) { /** * Move a child and its preceding comment(s) to after "after" */ -function breakOut(child, parent) { - let changeParent = true - let lastNode = parent - - for (let node of parent.nodes) { - if (!node.nodes) continue - - let prevNode = node.prev() - if (prevNode?.type !== 'comment') continue - - let parentRule = parent.toString() +function breakOut(child, currentNode) { + if (child.prev()?.type !== 'comment') { + currentNode.after(child) + return child + } - /* Checking that the comment "describes" the rule following. Like this: - /* comment about the rule below /* - .rule {} - */ - let regexp = /[*]\/ *\n.*{/ + let prevNode = child.prev() - if (parentRule.match(regexp)) { - changeParent = false - lastNode.after(node).after(prevNode) + /* Checking that the comment "describes" the rule following. Like this: + /* comment about the rule below *\ + .rule {} + */ + let regexp = /[*]\/ *\n.*{/ - lastNode = node - } + if (child.parent.toString().match(regexp)) { + currentNode.after(child).after(prevNode) } - - // It is necessary if the above child has never been moved - if (changeParent) { - parent.after(child) + else { + currentNode.after(child) } return child diff --git a/index.test.js b/index.test.js index c619935..afa9694 100644 --- a/index.test.js +++ b/index.test.js @@ -618,21 +618,20 @@ div { '/* Comment with ^ $ . | ? * + () */ div[data-roots-all^=1] * #id .class {}') }) -// ! -// test("Save the parent's comment with newline", () => { -// run( -// ` -// a { -// /*i*/ - -// /*i2*/ -// b {} -// /*i3*/ -// s {} -// }`, -// `a { /*i*/ } /*i2*/ a b {} /*i3*/ a s {}` -// ) -// }) +test("Save several rules with attached comments", () => { + run( + ` +a { + /*i*/ + + /*i2*/ + b {} + /*i3*/ + s {} +}`, + `a { /*i*/ } /*i2*/ a b {} /*i3*/ a s {}` + ) +}) test("Save the parent's comment with newline", () => { run( @@ -647,10 +646,12 @@ test("Save the parent's comment with newline", () => { test('Save the comments for the parent and child', () => { run( - `a { - /*i*/ - /*o*/ - b {} }`, + ` +a { + /*i*/ + /*o*/ + b {} +}`, `a { /*i*/ } /*o*/ a b {}` )