Skip to content

Commit

Permalink
format: implement more CSS selector formatting
Browse files Browse the repository at this point in the history
for IdSelector, HashToken, and PseudoClassSelector, and add test coverage.
  • Loading branch information
flavorjones committed Jun 4, 2024
1 parent c6848e2 commit c711ae3
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
17 changes: 17 additions & 0 deletions lib/syntax_tree/css/format.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ def visit_ident_token(node)
q.text(node.value)
end

# Visit a HashToken node.
def visit_hash_token(node)
q.text(node.value)
end

# Visit a StyleRule node.
def visit_style_rule(node)
q.group do
Expand Down Expand Up @@ -77,12 +82,24 @@ def visit_type_selector(node)
end
end

# Visit a Selectors::IdSelector node.
def visit_id_selector(node)
q.text("#")
node.value.format(q)
end

# Visit a Selectors::ClassSelector node.
def visit_class_selector(node)
q.text(".")
node.value.format(q)
end

# Visit a Selectors::PseudoClassSelector node.
def visit_pseudo_class_selector(node)
q.text(":")
node.value.format(q)
end

# Visit a Selectors::Combinator node.
def visit_combinator(node)
node.value.format(q)
Expand Down
30 changes: 27 additions & 3 deletions test/selectors_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,32 @@ class SelectorsTest < Minitest::Spec
end

describe "formatting" do
it "formats complex selectors" do
assert_selector_format(".outer section.foo>table.bar tr", ".outer section.foo > table.bar tr")
it "formats compound selector with an id selector" do
assert_selector_format(
"div#foo",
"div#foo",
)
end

it "formats compound selector with an pseudo-class selector" do
assert_selector_format(
"div:hover",
"div:hover",
)
end

it "formats compound selectors" do
assert_selector_format(
"div.flex.text-xl",
"div.flex.text-xl",
)
end

it "formats complex selectors with whitespace" do
assert_selector_format(
".outer section.foo>table.bar tr",
".outer section.foo > table.bar tr",
)
end

private
Expand All @@ -208,7 +232,7 @@ def assert_selector_format(selectors, expected)

io = StringIO.new
selectors.each do |selector|
selector.format(::PrettyPrint.new(io))
selector.format(::PP.new(io))
assert_equal(expected, io.string)
end
end
Expand Down

0 comments on commit c711ae3

Please sign in to comment.