Search


Search something to see results

Walk ast nodes

Parameters

  • node: any

    initial node

  • Optionalfilter: WalkerFilter | null

    control the walk process

  • Optionalreverse: boolean

    walk in reverse order


    import {walk} from '@tbela99/css-parser';

    const css = `
    body { color: color(from var(--base-color) display-p3 r calc(g + 0.24) calc(b + 0.15)); }

    html,
    body {
    line-height: 1.474;
    }

    .ruler {

    height: 10px;
    }
    `;

    for (const {node, parent, root} of walk(ast)) {

    // do something with node
    }

    Using a filter function to control the ast traversal. the filter function returns a value of type WalkerOption.

    import {EnumToken, transform, walk, WalkerOptionEnum} from '@tbela99/css-parser';

    const css = `
    body { color: color(from var(--base-color) display-p3 r calc(g + 0.24) calc(b + 0.15)); }

    html,
    body {
    line-height: 1.474;
    }

    .ruler {

    height: 10px;
    }
    `;

    function filter(node) {

    if (node.typ == EnumToken.AstRule && node.sel.includes('html')) {

    // skip the children of the current node
    return WalkerOptionEnum.IgnoreChildren;
    }
    }

    const result = await transform(css);
    for (const {node} of walk(result.ast, filter)) {

    console.error([EnumToken[node.typ]]);
    }

    // [ "StyleSheetNodeType" ]
    // [ "RuleNodeType" ]
    // [ "DeclarationNodeType" ]
    // [ "RuleNodeType" ]
    // [ "DeclarationNodeType" ]
    // [ "RuleNodeType" ]
    // [ "DeclarationNodeType" ]

Returns Generator<WalkResult>