Git Product home page Git Product logo

csstree's Introduction

NPM version Build Status Coverage Status

Related:

Install

> npm install css-tree

Usage

var csstree = require('css-tree');

csstree.walk(csstree.parse('.a { color: red; }'), function(node) {
  console.log(node.type);
});
// Class
// SimpleSelector
// Selector
// Property
// Identifier
// Value
// Declaration
// Block
// Ruleset
// StyleSheet

API

parse(source[, options])

Parse CSS to AST.

NOTE: Currenly parser omit redundant separators, spaces and comments (except exclamation comments, i.e. /*! comment */) on AST build.

Options:

  • context String – parsing context, useful when some part of CSS is parsing (see below)
  • property String – make sense for declaration context to apply some property specific parse rules
  • positions Boolean – should AST contains node position or not, store data in info property of nodes (false by default)
  • filename String – filename of source that adds to info when positions is true, uses for source map generation (<unknown> by default)
  • line Number – initial line number, useful when parse fragment of CSS to compute correct positions
  • column Number – initial column number, useful when parse fragment of CSS to compute correct positions

Contexts:

  • stylesheet (default) – regular stylesheet, should be suitable in most cases
  • atrule – at-rule (e.g. @media screen, print { ... })
  • atruleExpression – at-rule expression (screen, print for example above)
  • ruleset – rule (e.g. .foo, .bar:hover { color: red; border: 1px solid black; })
  • selector – selector group (.foo, .bar:hover for ruleset example)
  • simpleSelector – selector (.foo or .bar:hover for ruleset example)
  • block – block content w/o curly braces (color: red; border: 1px solid black; for ruleset example)
  • declaration – declaration (color: red or border: 1px solid black for ruleset example)
  • value – declaration value (red or 1px solid black for ruleset example)
// simple parsing with no options
var ast = csstree.parse('.example { color: red }');

// parse with options
var ast = csstree.parse('.foo.bar', {
    context: 'simpleSelector',
    positions: true
});

clone(ast)

Make an AST node deep copy.

var orig = csstree.parse('.test { color: red }');
var copy = csstree.clone(orig);

csstree.walk(copy, function(node) {
    if (node.type === 'Class') {
        node.name = 'replaced';
    }
});

console.log(csstree.translate(orig));
// .test{color:red}
console.log(csstree.translate(copy));
// .replaced{color:red}

translate(ast)

Converts AST to string.

var ast = csstree.parse('.test { color: red }');
console.log(csstree.translate(ast));
// > .test{color:red}

translateWithSourceMap(ast)

The same as translate() but also generates source map (nodes should contain positions in info property).

var ast = csstree.parse('.test { color: red }', {
    filename: 'my.css',
    positions: true
});
console.log(csstree.translateWithSourceMap(ast));
// { css: '.test{color:red}', map: SourceMapGenerator {} }

walk(ast, handler)

Visit all nodes of AST and call handler for each one. handler receives three arguments:

  • node – current AST node
  • item – node wrapper when node is a list member; this wrapper contains references to prev and next nodes in list
  • list – reference to list when node is a list member; it's useful for operations on list like remove() or insert()

Context for handler an object, that contains references to some parent nodes:

  • root – refers to ast or root node
  • stylesheet – refers to closest StyleSheet node, it may be a top-level or at-rule block stylesheet
  • atruleExpression – refers to AtruleExpression node if current node inside at-rule expression
  • ruleset – refers to Ruleset node if current node inside a ruleset
  • selector – refers to Selector node if current node inside a selector
  • declaration – refers to Declaration node if current node inside a declaration
  • function – refers to closest Function or FunctionalPseudo node if current node inside one of them
// collect all urls in declarations
var csstree = require('./lib/index.js');
var urls = [];
var ast = csstree.parse(`
  @import url(import.css);
  .foo { background: url('foo.jpg'); }
  .bar { background-image: url(bar.png); }
`);

csstree.walk(ast, function(node) {
    if (this.declaration !== null && node.type === 'Url') {
        var value = node.value;

        if (value.type === 'Raw') {
            urls.push(value.value);
        } else {
            urls.push(value.value.substr(1, value.value.length - 2));
        }
    }
});

console.log(urls);
// [ 'foo.jpg', 'bar.png' ]

walkRules(ast, handler)

Same as walk() but visits Ruleset and Atrule nodes only.

walkRulesRight(ast, handler)

Same as walkRules() but visits nodes in reverse order (from last to first).

walkDeclarations(ast, handler)

Visit all declarations.

License

MIT

Template:CSSData by Mozilla Contributors is licensed under [CC-BY-SA 2.5]

csstree's People

Contributors

lahmatiy avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.