1.0.3 • Published 2 years ago

boreas v1.0.3

Weekly downloads
9
License
-
Repository
github
Last release
2 years ago

Boreas: A CSS Parser in TypeScript

Boreas is a CSS parser written in TypeScript (which compiles to JavaScript). It can be used both in node.js projects and in the browser (work in progress).

The project was done because we needed a reliable, robust CSS parser for our synchronized Web testing tool Ghostlab.

This project comprises

  • a W3C compliant tokenizer (cf. the W3C CSS syntax module, http://www.w3.org/TR/css3-syntax),
  • a parser that can serialize the AST to an output identical to the input (i.e., it preserves non-significant whitespaces and comments) and can parse "disabled" properties (i.e., properties that are commented out),
  • AST classes allowing easy AST manipulations and AST construction,
  • AST classes and tokens that contain information about their occurrence within the source code,
  • AST traversal (tree walking).

Installation

To install Boreas, simply type

npm install boreas

Building

You only need to build Boreas if you want to change the code or if you got the package by cloning the git repository; i.e., if you're just planning to use it from the installed version, there is no need to build it.

Build Boreas by typing

npm install
grunt

on the command line. The modules will be compiled into the lib directory.

Usage

All examples here are written in plain JavaScript (as are the examples in the project).

Parsing

var Parser = require('boreas/lib/parser');

// some CSS source you want to parse
var src = '* { color: blue; }';

// parse the CSS
var ast = Parser.parse(src);

// do any AST manipulations/tree walkling...

// unparse the AST to stdout
console.log(ast.toString());

The parser offers a set of static convenience methods to parse different types of CSS structures:

FunctionsDescription
parseparses a complete style sheet.
parseRuleparses a single rule (either a qualified rule or an at-rule).
parseSelectorsparses a list of selectors.
parseSelectorparses a single selector.
parseDeclarationsparses a list of declarations (i.e., CSS properties).
parseDeclarationparses a single declaration.

All the parse functions take, apart from the mandatory CSS source as first argument, an optional "options" argument, which is a hash with the following (optional) properties:

PropertiesDescription
lineBaseThe number of the first line, defaults to 0.
columnBaseThe number of the first column, defaults to 0.
tokenizeCommentsFlag indicating whether start and end comment tokens should be parsed as individual tokens and the contents of the comment should also be parsed.

Unparsing

Every AST class and tokens have a toString() method, which returns the a string identical to the corresponding part of the input.

AST Manipulations

Given an AST structure, the AST objects have methods by means of which the AST can be manipulated. E.g., RuleLists or SelectorLists or DeclarationLists have methods to insert or delete rules, selectors, or declarations, respectively.

Example:

var AST = require('../lib/ast');

// construct an AST structure by parsing or constructing it programmatically
var ast = ...;

// insert a new rule
ast.insertRule(new AST.Rule(
    new AST.SelectorList([
        new AST.Selector('h1')
    ]),
    new AST.DeclarationList([
        new AST.Declaration('color', 'blue')
    ])
));

// insert a new selector at the first position of the first rule
ast.getRules()[0].getSelectors().insertSelector(new AST.Selector('tr.odd'), 0);

// insert a new declaration (property)
ast.getRules()[0].getDeclarations().insertDeclaration(new AST.Declaration('border', '1px solid gray'));

AST Construction

All the AST classes have convenience constructors which allow easy programmatic construction of an AST structure.

Example:

var AST = require('../lib/ast');

var styleSheet = new AST.StyleSheet(
    new AST.RuleList([
        new AST.AtImport('import.css'),
        new AST.Rule(
            new AST.SelectorList([
                new AST.Selector('html'),
                new AST.Selector('h1 + p')
            ]),
            new AST.DeclarationList([
                new AST.Declaration('color', 'blue'),
                new AST.Declaration('border', '1px solid purple', true),
                new AST.Declaration('padding', '1em', false, true)
            ])
        ),
        new AST.AtMedia(
            'screen and (max-width: 1000px)',
            new AST.RuleList([
                new AST.SelectorList([ new AST.Selector('body') ]),
                new AST.DeclarationList([
                    new AST.Declaration('background-color', 'pink')
                ])
            ])
        )
    ])
);
console.log(styleSheet.toString());

AST Walking

Tokenizer and Parser Reference

Tokenizer

Properties/MethodsDescription
constructor(src: string, options?: ITokenizerOptions)Constructs a tokenizer for tokenizing the source src. Optinonally, an options hash, as described below, can be passed.
nextToken():TokenReturns the next token in the token stream. Leading and trailing whitespaces and comments of a token are returned in the leadingTrivia and trailingTrivia properties of the token.

ITokenizerOptions is a hash which can have the following properties:

PropertiesDescription
lineBase?: numberThe number of the first line, defaults to 0.
columnBase?: numberThe number of the first column, defaults to 0.
tokenizeComments?: booleanFlag indicating whether start and end comment tokens should be parsed as individual tokens and the contents of the comment should also be parsed.

Parser

Properties/MethodsDescription
constructor(src: string, options?: ITokenizerOptions)Constructs a new parser object for parsing the source src. Optionally, an options hash (as described in the Tokenizer) can be passed.
parseStyleSheet():StyleSheetParses a style sheet.
parseRuleBlock():RuleListParses a block of rules, i.e., rules contained within curly braces, "{" (rules) "}".
parseRuleList(isBlock?: boolean):RuleListParses a list of rules. If isBlock is set to true, it is expected that the rules are enclosed in curly braces.
parseQualifiedRule():RuleParses a qualified rule.
parseAtRule():AtRuleParses an (arbitrary) @rule.
parseDeclarationList():DeclarationListParses a list of declarations (e.g., properties).
parseDeclaration(throwErrors: boolean = true, omitSemicolon?: boolean):DeclarationParses a single declaration.
parseTrailingTokensForDisabledDeclarations(token:Token):Declaration[]Parses the trailing tokens of the current token for disabled declarations (declarations which are commented out in the source code).
parseDisabledDeclaration(token:Token, throwErrors: boolean = true):DeclarationParses a single disabled (i.e., commented out) declaration.
parseDeclarationValue():DeclarationValueParses a declaration value (i.e., the part that comes after the ":" in a declaration).
parseSelectorList():SelectorListParses a list of selectors.
parseSelector():SelectorParses a single selector.
parseComponentValueList(...endTokens:EToken[]):ComponentValue[]Parses a list of component values.
parseBlock():BlockComponentValueParses a block component value (any block enclosed in parentheses, square brackets, or curly braces).
parseFunction():FunctionComponentValueParses a function.

AST Class Reference

Types

INode

This is a TypeScript interface which all AST classes and the Token class implement. It has the following members:

Properties/MethodsDescription
range:ISourceRangeThe start and end positions within the source code
getParent: () =>INodeReturns the parent node
getChildren: () =>INode[]Returns an array containing all the child nodes
isAncestorOf: (node:INode) => booleanDetermines if this node is an ancestor of "node"
getTokens: () =>Token[]Returns an array containing all the tokens that this node spans
walk: (walker:IASTWalker) => anyWalks the sub-tree using the tree walker "walker"
hasError: () => booleanReturns true iff there was an error while parsing this node
toString: () => stringUnparses this node and returns it's string representation (identical to the corresponding part of the input source code)

Defined in types.ts.

IComponentValue

Extends INode.

Properties/MethodsDescription
getValue: () => stringReturns a string representation of the component value.

ISourceRange

Properties/MethodsDescription
startLine: numberThe start line of the token/AST node.
startColumn: numberThe start column of the token/AST node.
endLine: numberThe end line of the token/AST node.
endColumn: numberThe end column (exclusive) of the token/AST node.

Defined in types.ts.

EToken

This enum defines the token types. The following enum values are defined (in accordance with the W3C specification):

PropertiesDescription
IDENTan identifier token
FUNCTIONa function token, i.e., an identifier followed by an opening parenthesis, "("
AT_KEYWORDan at-keyword, i.e., a identifier preceded by the at character, "@"
HASHa hash, i.e., an identifier preceded by the hash character, "#"
STRINGa string
BAD_STRINGa string with a syntax error
URLa URL
BAD_URLa URL with a syntax error
DELIMa delimiter token
NUMBERa number
PERCENTAGEa percentage token, i.e., a number followed by the percentage sign, "%"
DIMENSIONa dimension token, i.e., a number followed by a dimension such as "px", "em", etc.
UNICODE_RANGEa unicode range, i.e., something of the form U+0123?? or U+012345-ABCDEF
INCLUDE_MATCHan include match token, "~="
DASH_MATCHa dash match token, "="
PREFIX_MATCHa prefix match token, "^="
SUFFIX_MATCHa suffix match token, "$="
SUBSTRING_MATCHa substring match token, "*="
COLUMNa column token, ""
WHITESPACEa whitespace token, consisting of a sequence of space, tab, and newline characters
COMMENTa comment, i.e., a string enclosed in "/*", "*/"
CDOan opening HTML comment token, "<!--"
CDCa closing HTML comment token, "-->"
COLONa colon token, ":"
SEMICOLONa semicolon token, ";"
COMMAa comma token, ","
LBRACKETan opening square bracket token, "["
RBRACKETa closing square bracket token, "]"
LPARENan opening parenthesis token, "("
RPARENa closing parenthesis token, ")"
LBRACEan opening curly brace token, "{"
RBRACEa closing curly brace token, "}"
EOFthe "end of file" token

Defined in tokenizer.ts.

IASTWalker

Properties/MethodsDescription
(ast:INode, descend: () => any[], walker?: IASTWalker): any

AST Classes

Token

This class represents a single token.

Properties/MethodsDescription
token:ETokenThe token type.
src: stringThe original source string.
value: anyThe token's value, if applicable. The value is defined for the following token types: AT_KEYWORD (the identifier after the "@"),BAD_STRING (the string without the enclosing quotes),DIMENSION (the numeric value as a number),FUNCTION (the function name),HASH (the identifier after the "#"),NUMBER (the numeric value as a number),PERCENTAGE (the numberic value as a number),STRING (the string without the enclosing quotes),URL (the URL string without the "url(", ")").
unit: stringThe token's unit, if available. The unit is defined for the token type DIMENSION and contains strings like "px", "em", etc.
type: string
start: numberDefined for the token type UNICODE_RANGE. Contains the start of the unicode range.
end: numberDefined for the token type UNICODE_RANGE. Contains the end of the unicode range.
range:ISourceRangeThe range in which this token appears in the original source code
leadingTrivia:Token[]The leading trivia tokens (non-significant whitespaces and comments)
trailingTrivia:Token[]The trailing trivia tokens (non-significant whitespaces and comments)
parent:INodeThe token's parent node

Defined in tokenizer.ts.

ASTNode

This is the base class for all AST classes described below. It implements INode.

All the AST classes are defined in ast.ts.

Properties/MethodsDescription
getParent: () =>INodeReturns the node's parent node.
getChildren: () =>INode[]Returns an array of the node's children.
getTokens: () =>Token[]Returns all the tokens spanned by this node.
walk: (walker:IASTWalker) => anyWalks the sub-tree using the AST walker walker.
hasError: () => booleanReturns true iff there was an error while parsing this node.
toString: () => stringUnparses this node and returns it's string representation (identical to the corresponding part of the input source code).
errorTokensToString: () => stringReturns the source code when there was an error while parsing this node.
getRoot: () =>INodeReturns the root node of the AST.
isAncestorOf: (node:INode) => booleanDetermines if thi snode is an ancestor of node.

ASTNodeList\<U extends INode>

Extends ASTNode.

This is a generic class for encapsulating lists of AST nodes. It provides the base functionality for manipulating (replacing, inserting, deleting) its child nodes and a forEach method for iterating over its children.

Properties/MethodsDescription
constructor(nodes: U[])Constructs a new list, setting its items to the contents of the array nodes.
getLength(): numberReturns the number of nodes in this list.
replaceNodes(nodes: U[]): voidReplaces all the child nodes by the nodes in the array nodes.
insertNode(node: U, pos?: number): voidInserts a new node at position "pos" or at the end if no position is provided.
deleteNode(pos: number): voidDeletes the node at position "pos". If there is no node at this position, no node is deleted.
deleteAllNodes(): voidDeletes all nodes from the node list.
forEach(it: (elt: U) => void)Calls the function it on each element contained in the list.
walkChildren(walker:IASTWalker, result: any[] = []): any[]Walks the list's children using the AST walker walker.

StyleSheet

Extends ASTNode.

Properties/MethodsDescription
constructor(ruleList:RuleList, cdo?:Token, cdc?:Token)
insertRule: (rule:AbstractRule, pos?: number) => void
deleteRule: (pos: number) => void
deleteAllRules: () => void
getRules: () =>RuleList

AbstractRule

Extends ASTNode.

This class is the base class for Rule and AtRule.

Properties/MethodsDescription
id: stringA user-defined ID the user can assign to a rule.

RuleList

Extends ASTNodeList<AbstractRule>.

Properties/MethodsDescription
constructor(rules:AbstractRule[], lbrace?:Token, rbrace?:Token)
insertRule: (rule:AbstractRule, pos?: number) => void
deleteRule: (pos: number) => void
deleteAllRules: () => void
getLBrace: () =>Token
getRBrace: () =>Token

Rule

A qualified rule.

Extends AbstractRule.

Properties/MethodsDescription
constructor(selectors?:SelectorList, declarations?:DeclarationList)
getSelectors: () =>SelectorList
getDeclarations: () =>DeclarationList
setSelectors: (selectors:SelectorList) => void
insertSelector: (selector:Selector, pos?: number) => void
deleteSelector: (pos: number) => void
deleteAllSelectors: () => void
insertDeclaration: (declaration:Declaration, pos?: number) => void
deleteDeclaration: (pos: number) => void
deleteAllDeclarations: () => void

SelectorList

Extends ASTNodeList<Selector>.

Properties/MethodsDescription
constructor(selectors?:Selector[])
getSelector: (index: number) =>Selector
setSelectors: (selectors:Selector[]) => void
setSelectors: (selectors:SelectorList) => void
insertSelector: (selector:Selector, pos?: number) => void
deleteSelector: (pos: number) => void
deleteAllSelectors: () => void

Selector

Extends ComponentValueList.

Properties/MethodsDescription
constructor(values:IComponentValue[], separator?:Token)
constructor(selectorText: string)
getText: () => string
setText: (newText: string) => void
getSeparator: () =>Token

SelectorCombinator

Extends ComponentValue.

Properties/MethodsDescription
getCombinator: () => stringReturns the combinator token, i.e., a whitespace or a delimiter with source +, >, or ~.

SimpleSelector\<U extends INode>

Extends ASTNode, implements IComponentValue.

This class is the base class for the specialized selector classes described below.

Properties/MethodsDescription
constructor(value: U, namespace?:Token, pipe?:Token)
getNamespace: () =>TokenIf the selector has a namespace, this method returns the identifier token corresponding to the selector's namespace.
getPipe: () =>TokenIf the selector has a namespace (including the empty namespace), this method returns the pipe delimiter token separating the namespace identifier from the actual selector.

TypeSelector

Extends SimpleSelector<Token>.

Properties/MethodsDescription
constructor(type:Token, namespace?:Token, pipe?:Token)
constructor(type: string, namespace?: string)
getType: () =>TokenReturns the identifier token (corresponding to an HTML tag name).

UniversalSelector

Extends SimpleSelector<Token>.

Properties/MethodsDescription
constructor(asterisk:Token, namespace?:Token, pipe?:Token)
constructor(namespace?: string)
getType: () =>TokenReturns the * delimiter token.

AttributeSelector

Extends SimpleSelector<BlockComponentValue>.

Properties/MethodsDescription
getAttribute: () =>BlockComponentValue

ClassSelector

Extends SimpleSelector<Token>.

Properties/MethodsDescription
constructor(dot:Token, className:Token, namespace?:Token, pipe?:Token)
constructor(className: string, namespace?: string)
getClassName: () =>TokenReturns the class name identifier token.
getDot: () =>TokenReturns the delimiter token containing the dot preceding the class name identifier token.

IDSelector

Extends SimpleSelector<Token>.

Properties/MethodsDescription
constructor(id:Token, namespace?:Token, pipe?:Token)
constructor(id: string, namespace?: string)
getID: () =>TokenReturns the hash token containing the ID.

PseudoClass

Extends ASTNode, implements IComponentValue.

Properties/MethodsDescription
constructor(colon1:Token, colon2:Token, pseudoClassName:IComponentValue)
constructor(pseudoClass: string)
getPseudoClassName: () =>IComponentValue

DeclarationList

Extends ASTNodeList<Declaration>.

This class encapsulates a list of declaration, optionally enclosed in curly braces.

Properties/MethodsDescription
constructor(declarations:Declaration[], lbrace?:Token, rbrace?:Token)Constructs a DeclarationList from an array of declarations and optional opening and closing curly brace tokens.
getLBrace: () =>TokenReturns the opening curly brace if there is one.
getRBrace: () =>TokenReturns the closing curly brace if there is one.
insertDeclaration: (declaration:Declaration, pos?: number) => voidInserts a new declaration into the list. If the pos argument isn't specified, the new declaration will be appended to the list.
deleteDeclaration: (pos: number) => voidDeletes the declaration at position pos from this list.
deleteAllDeclarations: () => voidRemoves all declarations from this list.

Declaration

Extends ASTNode.

This class encapsulates a declaration (e.g., a CSS propery).

Example:

h1 {
	color: red;
	border: 1px solid yellow !important;
	/* padding: 0; */
}

In this example, "color: red;" and "border: 1px solid yellow !important;" are represented by Declarations.

The parser also supports disabled declarations, i.e., declarations which are commented out like "/ padding: 0; /" in the example. I.e., the parser will also parse such declarations and set the "disabled" flag to true.

Properties/MethodsDescription
constructor(name:ComponentValueList, colon:Token, value: DeclarationValue, semicolon:Token, lcomment?:Token, rcomment?:Token)Constructs a Declaration from a name ("color" and "border" in the above example), a colon token, a declaration value (representing "red" and "1px solid yellow !important" in the example), and a semicolon token. If the declaration is disabled, the lcomment and rcomment tokens are delimiter tokens with sources "/*" and "*/", respectively.
constructor(name: string, value: string, important?: boolean, disabled?: boolean)Constructs a DeclarationValue from a name, a value, an optional flag if this declaration has an appended !important and an optional flag if this declaration is disabled (i.e., commented out).
getName: () =>ComponentValueListReturn the name ("color", "border", or "padding" in the above example).
getNameAsString: () => stringReturns the name as a string.
setName: (newName: string) => voidReplaces the declaration's name by newName.
getColon: () =>TokenReturns the colon token.
getValue: () =>DeclarationValueReturns the declaration's value.
getValueAsString: (excludeImportant?: boolean) => stringReturns the declarations' value as a string.
setValue: (newValue: string) => voidReplaces the declaration's value by newValue.
getSemicolon: () =>TokenReturns the semicolon token.
getLComment: () =>TokenReturns the opening comment delimiter token, if this is a disabled declaration.
getRComment: () =>TokenReturns the closing comment delimiter token, if this is a disabled declaration.
getDisabled: () => booleanReturns true iff this declaration is disabled.
setDisabled: (isDisabled: boolean) => voidEnables/disables this declaration (i.e., removes/adds comment tokens).
getImportant: () => booleanReturns true iff the declaration's value contains !important.
getText: () => stringReturns a textual representation of the declaration.
setText: (newText: string) => voidParses newText and replaces the current declaration with the result.

DeclarationValue

Extends ComponentValueList.

This class encapsulates the value part of a declaration (e.g., a property).

Example:

h1 {
	color: red;
	border: 1px solid yellow !important;
}

In this example, "red" and "1px solid yellow !important" are represented by DeclarationValues.

Properties/MethodsDescription
constructor(values:IComponentValue[])Constructs a new DeclarationValue from an array of component values.
getText: (excludeImportant?: boolean) => stringReturns a textual representation of the value.
setText: (value: string) => voidReplaces the old value by the components contained in value after parsing the string.
getImportant: () => booleanReturns true iff the value contains !important.

AtRule

Extends AtRule.

This class encapsulates a generic @rule and is the base class for all the specialized @rule classes described below.

Properties/MethodsDescription
constructor(atKeyword:Token, prelude?:ComponentValueList, blockOrSemicolon?:INode)Constructs an AtRule from a (possibly vendor-prefixed) at-keyword token, a prelude (i.e., the part between the at-keyword and the body of the rule or the semicolon if the rule doesn't have a body), and its body (or the semicolon token if there is no body).
getAtKeyword: () =>TokenReturns the at-keyword token.
getPrelude: () =>ComponentValueListReturns the rule's prelude.
getDeclarations: () =>DeclarationListReturns the rule's list of declarations if this @rule has a body of declarations (e.g., @font-face or @page).
getRules: () =>RuleListReturns the rule's list of rules if this @rule has a body of rules (e.g., @media or @supports).
getSemicolon: () =>TokenReturns the semicolon token if this @rule has no body (e.g., @charset, @import, or @namespace).

AtCharset

Extends AtRule.

This class represents an @charset rule.

Example:

@charset 'utf-8';
Properties/MethodsDescription
constructor(atKeyword:Token, prelude:ComponentValueList, semicolon:Token)Constructs an AtCharset object from an at-keyword token with the source "@charset", a prelude, which is a string token representing the character encoding, and a semicolon token.
constructor(charset: string)Constructs an AtCharset object with the character encoding specified.
getCharset: () => stringReturns the charset.

AtCustomMedia

Extends AtRule.

This class represents an @custom-media rule.

Example:

Properties/MethodsDescription
constructor(atKeyword:Token, prelude:ComponentValueList, semicolon:Token)Constructs an AtCustomMedia object from an at-keyword token with the source "@custom-media" (possibly vendor-prefixed), a prelude XXXXX, and a semicolon token.
constructor(extensionName: string, media: string)
getExtensionName: () => string
getMedia: () =>ComponentValueList

AtDocument

Extends AtRule.

This class represents an @document rule.

Example:

@-moz-document url(http://localhost), domain(localhost), regexp("https:.*") {
	body {
		background: yellow;
	}
}

In this example, the CSS rules within the @document rule applies to

Properties/MethodsDescription
constructor(atKeyword:Token, prelude:ComponentValueList, block:RuleList)Constructs an AtDocument from an at-keyword token with the source "@document" (might be vendor-prefixed), a prelude containing URL tokens and function invocations, and a list of rules.
constructor(prelude: string, rules:RuleList)Constructs an AtDocument from a prelude string and a list of rules.
getUrl: () => stringReturns the URL if there is one.
getUrlPrefix: () => stringReturns the URL prefix if there is one.
getDomain: () => stringReturns the domain if there is one.
getRegexp: () => stringReturns the Regexp if there is one.

AtFontFace

Extends AtRule.

This class represents an @font-face rule.

Example:

@font-face {
	font-family: MyHelvetica;
	src: local("Helvetica Neue Bold"),
	local("HelveticaNeue-Bold"),
	url(MgOpenModernaBold.ttf);
	font-weight: bold;
}
Properties/MethodsDescription
constructor(atKeyword:Token, prelude:ComponentValueList, declarations:DeclarationList)Constructs an AtFontFace object from an at-keyword with the source "@font-face", an (empty) prelude, and a list of declarations.
constructor(declarations:DeclarationList)Constructs an AtFontFace object from a list of declarations.

AtHost

Extends AtRule.

This class represents an @host rule.

Example:

Properties/MethodsDescription
constructor(atKeyword:Token, prelude:ComponentValueList, rules:RuleList)
constructor(rules:RuleList)

AtImport

Extends AtRule.

This class represents an @import rule.

Example:

@import url('style1.css');
@import url('style2.css') screen and (min-width: 600px);
Properties/MethodsDescription
constructor(atKeyword:Token, prelude:ComponentValueList, semicolon:Token)Constructs an AtImport object from an at-keyword token with the source "@import", a prelude containing the reference to the imported stylesheet (either as a string or a URL token), and a semicolon token.
constructor(url: string, media?: string)Constructs an AtImport object from a URL (the stylesheet to import) and an optional media string.
getUrl: () => stringReturns the URL of the imported stylesheet.
getMedia: () =>ComponentValueListReturns the media if defined.

AtKeyframes

Extends AtRule.

This class represents an @keyframes rule.

Example:

@-webkit-keyframes moving-image {
	0%   { background-position: 0; }
	50%  { background-position: 100%; }
	100% { background-position: 0; }
}

@-moz-keyframes moving-image {
	0%   { background-position: 0; }
	50%  { background-position: 100%; }
	100% { background-position: 0; }
}
Properties/MethodsDescription
constructor(atKeyword:Token, prelude:ComponentValueList, rules:RuleList)Constructs an AtKeyframes object from a (possibly vendor-prefixed) at-keyword token, a prelude containing a single identifier token (the name of the animation), and a list of rules.
constructor(animationName: string, rules:RuleList)Constructs an AtKeyframes object from an animation name and a list of rules.
getAnimationName: () => stringReturns the animation name.

AtMedia

Extends AtRule.

This class represents an @media rule.

Example:

@media screen and (min-width: 800px) {
	body {
		padding: 1em
	}
}
Properties/MethodsDescription
constructor(atKeyword:Token, media:ComponentValueList, rules:RuleList)Constracts an AtMedia object from an at-keyword token with the source "@media", the media list (the component values making up screen and (min-width: 800px) in the above example), and a list of rules.
constructor(media: string, rules:RuleList)Constructs an AtMedia object from a media string (e.g., "screen and (min-width: 800px)") and a list of rules.
getMedia: () =>ComponentValueListReturns the media list.

AtNamespace

Extends AtRule.

This class represents an @namespace rule.

Example:

@namespace svg "http://www.w3.org/2000/svg";

In this example, "svg" is the (optional) namespace prefix, followed by the namespace URL.

Properties/MethodsDescription
constructor(atKeyword:Token, prelude:ComponentValueList, semicolon:Token)Constructs an AtNamespace object from an at-keyword token with the source "@namespace", a prelude comprising an identifier token for the namespace prefix (optional) and a string token for the namespace URL, and a semicolon token.
constructor(url: string, prefix?: string)Constructs an AtNamespace object from a namespace URL and an optional namespace prefix.
getUrl: () => stringReturns the namespace URL.
getPrefix: () => stringReturns the namespace prefix if there is one.

AtPage

Extends AtRule.

This class represents an @page rule.

Example:

@page {
	margin: 5cm;
}

@page :first {
	margin-left: 0.5cm;
}
Properties/MethodsDescription
constructor(atKeyword:Token, prelude:ComponentValueList, declarations:DeclarationList)Constructs an AtPage object from an at-keyword token with the source "@page", a prelude containing pseudo classes, and a list of declarations.
constructor(pseudoClass: string, declarations:DeclarationList)Constructs an AtPage object from a string specifying the pseudo class for the rule (e.g., :first in the second rule in the example), and a list of declarations.
getPseudoClass: () =>ComponentValueListReturns the prelude part, i.e., the pseudo class following the @page keyword of the rule, if there is one.

AtSupports

Extends AtRule.

This class represents an @supports rule.

Example:

@supports (display: flexbox) {
	body {
		display: flex;
	}
}

In this example, (display: flexbox) is the prelude part of the rule, which is followed by a list of rules enclosed in curly braces.

Properties/MethodsDescription
constructor(atKeyword:Token, supports:ComponentValueList, rules:RuleList)Constructs an AtSupports object from an at-keyword token with the source "@supports", a list of component values (the prelude), and a list of rules.
constructor(supports: string, rules:RuleList)Constructs an AtSupports object from a prelude string and a list of rules.
getSupports: () =>ComponentValueListReturns the prelude part (the components after the @supports keyword) of the rule.

ComponentValue

Extends ASTNode.

This class encapsulates a single token. ComponentValues are used as generic AST nodes when a token isn't further specialized by the parser.

Properties/MethodsDescription
constructor(token?:Token)Constructs a new ComponentValue.
getToken: () =>TokenReturns the encapsulated token.
getValue: () => stringReturns the value.
getType: () =>ETokenReturns the type of the token.

ComponentValueList

Extends ASTNodeList.

This class encapsulates a sequence of ComponentValues.

Properties/MethodsDescription
constructor(values:IComponentValue[])Constructs a new ComponentValueList.
getValue: () => stringReturns the value as a string.

BlockComponentValue

Extends ComponentValueList.

This class encapsulates a generic block, i.e., a portion of code starting with a opening parenthesis/square bracket/curly brace and ending with a closing parenthesis/square bracket/curly brace.

Properties/MethodsDescription
constructor(startToken:Token, endToken:Token, values:IComponentValue[])Constructs a new block from a start and an end token and value tokens contained between the start and the end tokens.
getStartToken: () =>TokenReturns the start token.
getEndToken: () =>TokenReturns the end token.

FunctionComponentValue

Extends BlockComponentValue.

This class encapsulates a function invocation, e.g., rgb(10, 20, 30).

Properties/MethodsDescription
constructor(name:Token, rparen:Token, args:IComponentValue[])Constructs a new FunctionComponentValue from a function token, the closing parenthesis and an array of function arguments.
getName: () =>TokenReturns the function token containing the function name (as per the W3C specification, the function token contains the name and the opening parenthesis.)
getArgs: () =>FunctionArgumentValue[]Returns the array of function arguments.

FunctionArgumentValue

Extends ComponentValueList.

This class represents an argument to a function, such as 10, , in rgb(10, 20, 30). Note that it also comprises the comma separator if there is one following the actual argument.

Properties/MethodsDescription
constructor(values:IComponentValue[], separator?:Token)Constructs a FunctionArgumentValue from an array of IComponentValues.
getSeparator: () =>TokenReturns the separator token (the comma) following the function argument, if there is one.

ImportantComponentValue

Extends ASTNode.

This class represents the !important part of a property value.

Properties/MethodsDescription
constructor(exclamationMark:Token, important:Token)Constructs an new ImportantComponentValue from an delimiter token with the source "!" and an identifier token with the source "important".
getExclamationMark: () =>TokenReturns the "!" delimiter token.
getImportant: () =>TokenReturns the "important" identifier.

License

MIT

Copyright (C) by Vanamco AG

1.0.3

2 years ago

1.0.1

8 years ago

1.0.0

8 years ago