Skip to content

Commit 24f1255

Browse files
committed
Child combinator
1 parent ee2da91 commit 24f1255

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

Sources/CSS/Selector.swift

+30-2
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,22 @@ public extension CSSSelector {
5656
for block in selectors {
5757
var select = Select()
5858
// Merge the selectors
59-
select.selector = selector + block.selector
59+
select.selector = "\(selector)\(block.selector)"
6060
select.children = block.children
6161
res += select.string()
6262
}
6363
}
64-
let root = children.filter { !($0 is CSSSelector || $0 is ConditionalDeclaration || $0 is Media || $0 is Group || $0 is Parent) }
64+
let childCombinators = children.filter { $0 is Child } as! [Child]
65+
for child in childCombinators {
66+
let selectors = child.children.filter { $0 is CSSSelector } as! [CSSSelector]
67+
for block in selectors {
68+
var select = Select()
69+
select.selector = "\(selector) > \(block.selector)"
70+
select.children = block.children
71+
res += select.string()
72+
}
73+
}
74+
let root = children.filter { !($0 is CSSSelector || $0 is ConditionalDeclaration || $0 is Media || $0 is Group || $0 is Parent || $0 is Child) }
6575
if root.count > 0 {
6676
res += """
6777
\(selector) {\(root.map { $0.string() }.reduce(into: "", { $0 += "\n \($1)" }))
@@ -146,3 +156,21 @@ public struct Parent: CSSBlock {
146156
children.map { $0.string() }.joined(separator: "\n")
147157
}
148158
}
159+
160+
/// The child combinator (a direct descendent of the parent)
161+
public struct Child: CSSBlock {
162+
public var children: [CSS]
163+
164+
public init(@StylesheetBuilder _ body: () -> CSSBlock) {
165+
let built = body()
166+
if let container = built as? CSSContainer {
167+
children = container.children
168+
} else {
169+
children = [built]
170+
}
171+
}
172+
173+
public func string() -> String {
174+
children.map { $0.string() }.joined(separator: "\n")
175+
}
176+
}

Tests/CSSTests/CSSTests.swift

+11
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,17 @@ final class CSSTests: XCTestCase {
136136
Parent {
137137
Class("blue") {
138138
background(.blue)
139+
Child {
140+
Paragraph { color(.green) }
141+
}
142+
}
143+
}
144+
Child {
145+
Class ("blue") {
146+
background(.blue)
147+
Parent {
148+
Id("myElement") { color(.white) }
149+
}
139150
}
140151
}
141152
}

0 commit comments

Comments
 (0)