Skip to content

Commit e069f6f

Browse files
authored
fix: ParserContext type to have all methods (#57)
fix: ParserContext to have all methods
1 parent 846120b commit e069f6f

File tree

2 files changed

+44
-5
lines changed

2 files changed

+44
-5
lines changed

lib/index.d.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2729,10 +2729,13 @@ type ParseConfig = {
27292729
} & Pick<SyntaxConfig, 'features' | 'scope'>;
27302730

27312731
// https://github.com/csstree/csstree/blob/9de5189fadd6fb4e3a149eec0e80d6ed0d0541e5/lib/parser/create.js#L90
2732-
type ParserContext = TokenStream
2732+
type ParserContext<AvailableNodes extends CssNodeCommon = CssNode> = TokenStream
27332733
& ParseConfig
27342734
& { config: ParseConfig }
27352735
& Parser
2736+
& {
2737+
[K in AvailableNodes["type"]]: (this: ParserContext, ...args: unknown[]) => Extract<AvailableNodes, { type: K }>;
2738+
}
27362739
& {
27372740
// Anything else
27382741
[key: string]: unknown;

tests/types/types.test.ts

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -276,10 +276,13 @@ const customSyntax = csstree.fork({
276276
structure: {
277277
children: [[]]
278278
},
279-
parse: () => {
279+
parse() {
280+
281+
const dec = this.Declaration();
282+
280283
return {
281284
type: 'CustomNode3',
282-
value: 'hello'
285+
value: dec.property
283286
};
284287
},
285288
generate(node: csstree.CssNode) {
@@ -291,10 +294,13 @@ const customSyntax = csstree.fork({
291294
}
292295
},
293296
CustomNode4: {
294-
parse: () => {
297+
parse() {
298+
299+
const id = this.Identifier();
300+
295301
return {
296302
type: 'CustomNode3',
297-
value: 'hello'
303+
value: id.name
298304
};
299305
},
300306
},
@@ -308,6 +314,36 @@ const customSyntax = csstree.fork({
308314
}
309315
});
310316

317+
// Parsing with custom node types
318+
319+
interface CustomNode extends csstree.CssNodeCommon {
320+
type: 'CustomNode';
321+
value: string;
322+
}
323+
324+
type CustomNodes = csstree.CssNode | CustomNode;
325+
326+
function customParseFunction(this: csstree.ParserContext<CustomNodes>, value: string) {
327+
328+
const node = this.CustomNode();
329+
const id = this.Identifier();
330+
331+
return {
332+
type: 'CustomNode2',
333+
value: node.value
334+
};
335+
}
336+
337+
const partialNodeConfig: Partial<csstree.NodeSyntaxConfig> = {
338+
parse(this: csstree.ParserContext<CustomNodes>, value: string) {
339+
const node = this.CustomNode();
340+
return {
341+
type: 'CustomNode3',
342+
value: node.value
343+
};
344+
},
345+
}
346+
311347
const customAst = customSyntax.parse('.example { custom: value }');
312348
customSyntax.walk(customAst,
313349
(node) => {

0 commit comments

Comments
 (0)