|
1 |
| -import type { Node, Parser, Root } from "postcss"; |
| 1 | +import type { Node, Parser, Root, Rule } from "postcss"; |
2 | 2 | import postcss from "postcss";
|
3 | 3 | import { parse as SCSSparse } from "postcss-scss";
|
| 4 | +import { |
| 5 | + default as selectorParser, |
| 6 | + type Node as SelectorNode, |
| 7 | + type Root as SelectorRoot, |
| 8 | +} from "postcss-selector-parser"; |
4 | 9 |
|
5 | 10 | import type { Context } from "../context/index.js";
|
6 | 11 | import type { SourceLocation, SvelteStyleElement } from "../ast/index.js";
|
@@ -77,10 +82,25 @@ export function parseStyleContext(
|
77 | 82 | return { status: "parse-error", sourceLang, error };
|
78 | 83 | }
|
79 | 84 | fixPostCSSNodeLocation(sourceAst, styleElement);
|
80 |
| - sourceAst.walk((node) => fixPostCSSNodeLocation(node, styleElement)); |
| 85 | + sourceAst.walk((node) => { |
| 86 | + fixPostCSSNodeLocation(node, styleElement); |
| 87 | + }); |
81 | 88 | return { status: "success", sourceLang, sourceAst };
|
82 | 89 | }
|
83 | 90 |
|
| 91 | +/** |
| 92 | + * Parses a PostCSS Rule node's selector and returns its AST. |
| 93 | + */ |
| 94 | +export function parseSelector(rule: Rule): SelectorRoot { |
| 95 | + const processor = selectorParser(); |
| 96 | + const root = processor.astSync(rule.selector); |
| 97 | + fixSelectorNodeLocation(root, rule); |
| 98 | + root.walk((node) => { |
| 99 | + fixSelectorNodeLocation(node, rule); |
| 100 | + }); |
| 101 | + return root; |
| 102 | +} |
| 103 | + |
84 | 104 | /**
|
85 | 105 | * Extracts a node location (like that of any ESLint node) from a parsed svelte style node.
|
86 | 106 | */
|
@@ -144,3 +164,32 @@ function fixPostCSSNodeLocation(node: Node, styleElement: SvelteStyleElement) {
|
144 | 164 | node.source.end.column += styleElement.startTag.loc.end.column;
|
145 | 165 | }
|
146 | 166 | }
|
| 167 | + |
| 168 | +/** |
| 169 | + * Fixes selector AST locations to be relative to the whole file instead of relative to their parent rule. |
| 170 | + */ |
| 171 | +function fixSelectorNodeLocation(node: SelectorNode, rule: Rule) { |
| 172 | + if (node.source === undefined) { |
| 173 | + return; |
| 174 | + } |
| 175 | + const ruleLoc = styleNodeLoc(rule); |
| 176 | + |
| 177 | + if (node.source.start !== undefined && ruleLoc.start !== undefined) { |
| 178 | + if (node.source.start.line === 1) { |
| 179 | + node.source.start.column += ruleLoc.start.column; |
| 180 | + } |
| 181 | + node.source.start.line += ruleLoc.start.line - 1; |
| 182 | + } else { |
| 183 | + node.source.start = undefined; |
| 184 | + } |
| 185 | + |
| 186 | + if (node.source.end !== undefined && ruleLoc.start !== undefined) { |
| 187 | + if (node.source.end.line === 1) { |
| 188 | + node.source.end.column += ruleLoc.start.column; |
| 189 | + } |
| 190 | + node.source.end.column += 1; |
| 191 | + node.source.end.line += ruleLoc.start.line - 1; |
| 192 | + } else { |
| 193 | + node.source.end = undefined; |
| 194 | + } |
| 195 | +} |
0 commit comments