Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@tokey/css-selector-parser

Package Overview
Dependencies
Maintainers
3
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@tokey/css-selector-parser

selector parser for css

  • 0.3.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1.6K
decreased by-16.23%
Maintainers
3
Weekly downloads
 
Created
Source

@tokey/css-selector-parser

npm version npm bundle size

A flexible CSS selector parser with support for the latest syntax and features.

Features

  • safe - returns an AST that can always be stringified to its original source
  • track offset - start/end on every AST node
  • validations - applies validation flags to ast nodes marking their syntax correctness
  • spacing as decoration - visual spacing is represented in before/after and never affects selector meaning
  • extensive selector support
    • comments - comments parsed wherever they are placed 🤪
    • escaping - support escaped dots, slashes, quotation marks, etc.
    • An+B of - Nth selector AST with inner parts and validation flags for each part
    • combinators - correctly identify and mark spaces/combinators with validation flags
    • nesting - support future & selector
    • namespace - universal and type selectors namespace with validation flags on the AST
  • typed - built with Typescript
  • tested - thoroughly tested

Installation

Using NPM:

npm install @tokey/css-selector-parser

Using Yarn:

yarn add @tokey/css-selector-parser

Usage

Parsing

parseCssSelector - accepts a selector list string and returns an AST representation of that.

import { parseCssSelector } from '@tokey/css-selector-parser';

const selectorList = parseCssSelector(`.card, .box`);
/*
[
    {
        type: "selector",
        start: 0,
        end: 5,
        before: "",
        after: "",
        nodes: [
            {
                type: "class",
                value: "card",
                start: 0,
                end: 5,
                dotComments: [],
            },
        ],
    },
    {
        type: "selector",
        start: 6,
        end: 11,
        before: " ",
        after: "",
        nodes: [
            {
                type: "class",
                value: "box",
                start: 7,
                end: 11,
                dotComments: [],
            },
        ],
    }
]
*/
parsing config

offset - start AST offset from a given point, defaults to 0:

parseCssSelector(`ul`, { offset: 105 });

Stringify

stringifySelectorAst - converts an AST node back into its string representation.

import { stringifySelectorAst } from '@tokey/css-selector-parser';

stringifySelectorAst(
    parseCssSelector(`.class`);
); // ".class"

Traversing

walk - traverse each node of the selector AST from start to end.

The visit call is given:

  • node - the current node in the traversal
  • index - the index of the node withing its siblings
  • nodes - the node shallow sibling array
  • parents - the node parents array
import { walk } from '@tokey/css-selector-parser';

walk(
    parseCssSelector(`.one + three(#four, [five]), /*six*/ ::seven:eight`),
    (node: SelectorNode, index: number, nodes: SelectorNode[], parents: SelectorNode[]) => {
        // calling order:

        // selector:  .one + three(#four, [five])
        // .one
        // +
        // three
        // selector: #four
        // #four
        // selector:  [five]
        // [five]
        // selector:  /*six*/ ::seven:eight
        // /*six*/
        // ::seven
        // :eight
    }
);

Note: comments within class, pseudo-class and pseudo-element are not traversed at the moment

For example: ./*what?!*/a.

control traversal

The transversal can be controlled with the return value of each visit:

  • walk.skipNested - prevent farther nested traversal from the current node
  • walk.skipCurrentSelector - prevent visit on other nodes on the same selector
  • walk.stopAll - ends walk
import { walk } from '@tokey/css-selector-parser';

walk(
    parseCssSelector(`selector`),
    (node) => {
        // return walk.skipNested;
        // return walk.skipCurrentSelector;
        // return walk.stopAll;
    }
);
walk options

visitList/ignoreList - limits the types of AST calls to the visit function, but does not prevent traversal of nested nodes.

walk(
    parseCssSelector(`.one:is(:not(/*comment*/.two))`),
    (node) => {
        // .one
        // :is()
        // :not()
        // .two
    },
    {
        // visit will not be called on selector or comment nodes
        ignoreList: [`selector`, `comment`] 
    }
);

Design decisions

Escaping

The parser supports character escaping, but will not escape anything by itself. Make sure to escape any value before setting it manually into an AST node.

Functional selectors

The parser supports native pseudo-classes/pseudo-elements functional selectors, but also parses other selectors in the same way. So type/id/class/attribute/nesting selectors are all parsed with nodes in case they are followed by a pair of parentheses (e.g. element(nodeA, nodeB)). This syntax is not valid CSS and should be handled before served to a CSS consumer.

Nth selector

:nth-child, :nth-last-child, :nth-of-type and :nth-last-of-type are a set of special cases where An+B of syntax is expected.

Keywords

FAQs

Package last updated on 19 Jul 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc