Skip to content

Commit 8a29466

Browse files
committed
refactor(stringify): Simplify selectors
1 parent b3e5e59 commit 8a29466

File tree

1 file changed

+17
-8
lines changed

1 file changed

+17
-8
lines changed

src/stringify.ts

+17-8
Original file line numberDiff line numberDiff line change
@@ -34,27 +34,36 @@ const charsToEscapeInName = new Set(
3434
*/
3535
export function stringify(selector: Selector[][]): string {
3636
return selector
37-
.map((token) => token.map((t) => stringifyToken(t)).join(""))
37+
.map((token) => token.map(stringifyToken).join(""))
3838
.join(", ");
3939
}
4040

41-
function stringifyToken(token: Selector): string {
41+
function stringifyToken(
42+
token: Selector,
43+
index: number,
44+
arr: Selector[]
45+
): string {
4246
switch (token.type) {
4347
// Simple types
4448
case SelectorType.Child:
45-
return " > ";
49+
return index === 0 ? "> " : " > ";
4650
case SelectorType.Parent:
47-
return " < ";
51+
return index === 0 ? "< " : " < ";
4852
case SelectorType.Sibling:
49-
return " ~ ";
53+
return index === 0 ? "~ " : " ~ ";
5054
case SelectorType.Adjacent:
51-
return " + ";
55+
return index === 0 ? "+ " : " + ";
5256
case SelectorType.Descendant:
5357
return " ";
5458
case SelectorType.ColumnCombinator:
55-
return " || ";
59+
return index === 0 ? "|| " : " || ";
5660
case SelectorType.Universal:
57-
return `${getNamespace(token.namespace)}*`;
61+
// Return an empty string if the selector isn't needed.
62+
return token.namespace === "*" &&
63+
index + 1 < arr.length &&
64+
"name" in arr[index + 1]
65+
? ""
66+
: `${getNamespace(token.namespace)}*`;
5867

5968
case SelectorType.Tag:
6069
return getNamespacedName(token);

0 commit comments

Comments
 (0)