0.1.0 • Published 1 year ago

@hgargg-0710/selector v0.1.0

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

selector

selector is a CSS selector parsing/generation/construction library.

Installation

npm install @hgargg-0710/selector

Documentation

The following is the precise description of the library's exports (v0.1).

  1. parse (function)
  2. generate (function)
  3. parser (submodule)
  4. generator (submodule)
  5. tokens (submodule)
  6. tree (submodule)

NOTE: it is built on top of the parsers.js library for parser-making, so some of the terminology comes from there.

parse

This is one of the two primary functions of the library. Given a string with a syntactically correct CSS selector, it returns an Abstract Syntax Tree constructed using the library's AST API.

function parse(selector: string): Combinator | CompoundSelector | SelectorList

The result of parse can later be passed to generate to reverse the parsing operation.

generate

An inverse of parse. Provided an AST constructed with the usage of library's API, returns a string.

function generate(selector: Combinator | CompoundSelector | SelectorList): string

Funny note: the combination generate(parse(selector)) can be used as a kind of generally-inneficient-but-easy-to-make-with-the-library selector-formatter...

parser

This is a submodule, including all the exports of the parsing-dedicated modules. In particular, the mult-layered parse function is composed of the contents of the module. It also provides the parse function as the export (aliased as SelectorParser).

The layers of parsing of a selector employed by the library are (in order of their application):

  1. char (tokenization)
  2. escaped (escaped sequences)
  3. string (string character sequences)
  4. bracket (identifying of sub-selectors)
  5. list (identifying of selector-lists)
  6. simple (finalization of simple selectors)
    1. attribute (parsing of attribute selectors)
    2. identifier (parsing of identifiers - key elements of all simple selectors)
  7. compound (uniting simple selectors into compound ones)
  8. despace (elimination of undesired space tokens to simplify further descendant combinator identification)
  9. combinator (identifies combinators, and orders the compound results based on them)

The parser module exports are broken down into these submodules, which are the immidiate exports.

What follows is the enumeration of different submodules' exports and their meanings/uses within the parser.

char

exportdescription
SelectorTokenizerThe tokenization function (a PatternTokenizer). Accepts a Pattern<string, RegExp, RegExp> (example: StringPattern). Returns a PatternCollection
charMapThe IndexMap, on which the SelectorTokenizer is based. Keys are regular expressions, values - TokenTypes corresponding to them

escaped

exportdescription
EscapeParserThe main parsing function. Accepts Stream, returns an array. Converts Escape followed by something else into appropriate Escaped
isHexChecks whether the given string tests positive against /[0-9a-fA-F]/
readHexReads a hexidecimal from the given stream (up to 6 characters), altering the Stream passed
readEscapedReads a single character from a given Stream, altering it
HandleEscapedMain handler for the Escape token within the escapeMap IndexMap
escapedMapThe TypeMap, on which the EscapeParser is based

string

exportdescription
SelectorStringParserThe main parsing function. Accepts Stream, returns an array. Converts token sequences between pairs of " or ' to SelectorString tokens. Happens after Escaped
StringCharacterParserConverts a given Stream, which is a result of limiting another Stream to an array, in which SelectorSymbols were grouped into StringCharacters
quoteReadAn object containing cached functions for reading a string starting with ' and " respectively
readUntilEscapedReads from a given Stream, altering it, until an Escaped is met
stringMapA TypeMap, on which the SelectorStringParser is based
stringCharMapA TypeMap, on which the SelectorCharacterParser is based

bracket

exportdescription
EndParserThe "latter" part of the parse function. It unites BracketParser, list, simple, compound, despace and combinator. It also deals with recursive brackets
SelectorListParserAccepts Stream, puts the input through BracketParser and SelectorCommaParser (from list).
BracketParserRecursively applies EndParser on all encountered sub-selectors within the passed Stream.
recursiveBracketParserThe recursive component of the EndParser
flatBracketParserThe finite ("flat", non-recursive) component of the EndParser
SubSelectorHandlerThe handler of sub-selectors within the subSelectorMap
nestedBrackReturns the nested limitation of the given Stream to cover the entirety of the current sub-selector
subSelectorMapThe TypeMap, on which the BracketMap is based

list

exportdescription
SelectorCommaParserBreaks all the pieces of parsed Stream into arrays and eliminates all Commas

simple

exportdescription
SimpleSelectorParserThe main simple selectors' parser. Takes a Stream, returns an array of transformed tokens
HandleElementHandles an element selector
HandleIdHandles an id selector
HandleClassHandles a class selector
HandleAttributeHandles an attribute selector
HandlePseudoClassHandles a pseudo-class selector
HandlePseudoElementHandles a pseudo-element selector
HandleUniversalHandles a universal selector
HandleParentHandles a parent selector
readSimpleReads an identifier, optionally skipping an element of the passed Stream. Sub-routine used for defining some of the handlers
simpleMapThe TypeMap, on which the SimpleSelectorParser is based.

attribute

exportdescription
AttributeParserThe BasicParser for parsing attribute selectors.
AttributeHandlerHandler for attribute selectors.
attributeMapThe TypeMap, on which AttributeParser is based

identifier

exportdescription
IdentifierParserTakes in an array of tokens, returns a SelectorIdentifier. Parser for Identifiers
readSymbolReads from a Stream for as long as its current symbol is a SelectorSymbol
limitPartialLimits a given Stream, and moves it, to the point where the next identifier ends. Returns the limited portion.
parseIdentifierParses the identifier (a global sub-routine utilizing the IdentifierParser and limitPartial)
identifierMapA TypeMap, on which the IdentifierParser is based.

compound

exportdescription
CompoundSelectorParserMain parsing function. Combines different simple selectors into CompoundSelectors
CompoundHandlerThe handler for simple selectors
compoundMapThe TypeMap, on which CompoundSelectorParser is based

despace

exportdescription
DeSpacerReplaces sequences of Space tokens with a single one.
DeSpaceThe handler of Space
despaceMapThe TypeMap, off which DeSpacer is based
skipSpacesSkips spaces within the given Stream

combinator

exportdescription
SelectorCombinatorParserStructures compound selectors together using combinators. The main parser function of the module
HandleCombinatorCombinator handler.
HandleCompoundCompound handler.
combinatorMapTypeMap, off which the SelectorCombinatorParser is based

generator

This module provides functions for generation of selectors, relating to different package's AST-belonging tokens. In particular, it includes the generate function as an export (aliased as SelectorGenerator).

The abstractions work primarily with Streams , including those based off trees provided by the tree submodule.

exportdescription
SelectorGeneratorThe generate function
GenerateCombinatorGenerates the Combinator selector
GeneratePseudoClassGenerates the pseudo-class selector
GenerateAttributeGenerates the attribute selector
GenerateCompoundGenerates the compound selector
GenerateElementGenerates the element selector
GenerateIdGenerates the id selector
GenerateClassGenerates the class selector
GeneratePseudoElementGenerates the pseudo-element selector
GenerateCharactersGenerates the characters (those are StringCharacters and IdentifierCharacters)
GenerateEscapedGenerates the Escaped
GenerateChildCombinatorGenerates the child combinator (>)
GenerateDescendantCombinatorGenerates the descendant combinator ()
GenerateNextSiblingCombinatorGenerates the next sibling combinator (+)
GenerateNamespaceCombinatorGenerates the namespace combinator (\|)
GenerateSubseqSibilngCombinatorGenerates the subsequent sibling combinator (~)
GenerateEndsWithMatchGenerates the ends-with match $=
GenerateIncludesMatchGenerates the includes match ~=
GenerateHyphBeginMatchGenerates the hyphen-begin match \|=
GeneratePrefixMatchGenerates the prefix match ^=
GenerateFindMatchGenerates the find match *=
GenerateEqualityMatchGenerates the equality match =
GenerateUniversalSelectorGenerates the universal selector *
GenerateParentSelectorGenerates the parent selector &
GenerateStringGenerates a string (note: preserves the quotes used - either ', or ")
GenerateSubSelectorGenerates a sub-selector
GenerateSelectorListGenerates a selector-list
GenerateIdentifierGenerates an identifier
SelectorSourceGeneratorThe SourceGenerator, on which the generate function is based off
generatorMapThe TypeMap, on which the SelectorSourceGenerator is based off

tree

Provides exports related to TreeStream-building based off the parser-created AST.

exportdescription
SelectorStreamA function accepting the library's AST (result of parse, for instance), and transforming it into a Stream
SelectorTreeThe default export of the submodule. Converts the given library's AST into a tree that can be put through TreeStream to make a Stream (on it, teh SelectorStream is based)
SimpleTreeLike others below, a function for transforming a node of an AST into a TreeStream argument. Converts the .value to the tree, and makes [.value] the children array
ChildlessTreeThe tree without children
ValueTreeThe tree in which .value is the .children
AttributeTreeThe function that transforms an SelectorAttribute into a tree
PseudoClassTreeThe function that transforms a PseudoClassSelector into a tree
CombinatorTreeThe function that transforms a CombinatorToken into a tree
treeMapThe IndexMap, on which the SelectorTree is based

tokens

The tokens submodule includes various TokenTypes, used by the library to represent various classes of tokens.

Like, parser, tokens submodule is, too, broken down onto submodules itself:

  1. char (tokenization)
  2. escaped (escaped sequences)
  3. string (string character sequences)
  4. bracket (identifying of sub-selectors)
  5. list (identifying of selector-lists)
  6. simple (finalization of simple selectors)
    1. attribute (parsing of attribute selectors)
    2. identifier (parsing of identifiers - key elements of all simple selectors)
  7. compound (uniting simple selectors into compound ones)
  8. combinator (identifies combinators, and orders the compound results based on them)

The following is the enumeration of TokenTypes exported by the corresponding submodules.

char

TokenTyperepresentstype-word
SelectorHashThe hash (#) symbol"hash"
SelectorDotThe dot (.) symbol"dot"
SpaceOne of the space (/\s/) symbols"space"
RectOpThe opening square bracket ([) symbol"rop"
RectClThe closing square bracket (]) symbol"rcl"
DoubleColonThe double colon symbol sequence (::)"double-colon"
ColonThe single colon (:) symbol"colon"
PlusThe plus (+) symbol"plus"
ChildThe child combinator symbol (>)"child"
OpBrackThe opening bracket (() symbol"opbrack"
ClBrackThe closing bracket ()) symbol"clbrack"
EndsWithMatchThe ends-with match ($=) symbol-sequence"endswith"
IncludesMatchThe includes-match (~=) symbol-sequence"includes"
HyphenBeginMatchThe hyphen-beign match (\|=) symbol-sequence"hyphbeg"
PrefixMatchThe prefix-match (^=) symbol-sequence"prefix"
FindMatchThe find-match (*=) symbol-sequence"find"
EqMatchThe equality-match (*=) symbol"eq"
AnyThe universal selector (*) symbol"any"
NamespaceThe namespace combinator symbol (\|)"namespace"
SiblingThe sibling combinator symbol (~)"sibling"
QuoteOne of the quote symbols (' or ")"quote"
CommaThe comma (,) symbol"comma"
AmpersandThe ampersand (&) symbol"ampersand"
EscapeThe escape (\) symbol | "escape"
SelectorSymbolAny other symbol (not in the table already)"symbol"

These TokenTypes are used for initial tokenization of the given CSS selector.

escaped

const Escaped: TokenType

Represents an escaped character or a hex number up to 6 digits. Used inside identifiers and strings.

Type-word: "escaped"

const SelectorPartial: (x: any): boolean

Checks for whether a given item is one of SelectorSymbols or Escapeds.

string

TokenTyperepresentstype-word
SelectorStringA string"string"
StringCharactersA sequence of in-string characters"string-chars"

bracket

TokenTyperepresentstype-word
SubSelectorA sub-selector"sub-selector"

list

TokenTyperepresentstype-word
SelectorListA selector-list (..., ..., ...)"selector-list"

simple

TokenTyperepresentstype-word
SelectorElementAn element-selector (ex: h1)"selector-list"
SelectorIdAn id-selector (ex: #i-am-unique)"id"
SelectorClassA class-selector (ex: .we-are-many)"class"
SelectorAttributeAn attribute-selector (ex: [nom="valeur"])"attribute"
PseudoClassSelectorA pseudo-class selector (ex: :hover)"pseudo-class"
PseudoElementSelectorA pseudo-element selector (ex: ::after)"pseudo-element"
UniversalSelectorA universal selector ("*")"universal"
ParentSelectorParent-selector (&)"parent"

attribute

The only export is the isMatch predicate.

const isMatch: (x: any): boolean

Returns true only for one of EndsWithMatch, IncludesMatch, HyphenBegMatch, PrefixMatch, FindMatch, EqMatch.

identifier

TokenTyperepresentstype-word
SelectorIdentifierAn identifier"identifier"
IdentifierCharactersA sequence of in-identifier characters"id-chars"

compound

TokenTyperepresentstype-word
CompoundSelectorA compound selector, includes simple selectors"compound"

Also, contains the isSelector predicate

const isSelector: (x: any): boolean

Returns true only if the argument is one of SelectorElement, SelectorId, SelectorClass, SelectorAttribute, PseudoClassSelector, PseudoElementSelector, UniversalSelector, ParentSelector

combinator

TokenTyperepresentstype-word
CombinatorTokenA combinator, consists of a combinator token and arguments"compound"

Also, exports the isCombinator predicate.

const isCombinator: (x: any): boolean

Returns true only to one of the Child, Space, Plus, Namespace, Sibling.