Giter VIP home page Giter VIP logo

csstree's Introduction

CSSTree logo

CSSTree

NPM version Build Status Coverage Status NPM Downloads Twitter

CSSTree is a tool set for CSS: fast detailed parser (CSS → AST), walker (AST traversal), generator (AST → CSS) and lexer (validation and matching) based on specs and browser implementations. The main goal is to be efficient and W3C spec compliant, with focus on CSS analyzing and source-to-source transforming tasks.

Features

  • Detailed parsing with an adjustable level of detail

    By default CSSTree parses CSS as detailed as possible, i.e. each single logical part is representing with its own AST node (see AST format for all possible node types). The parsing detail level can be changed through parser options, for example, you can disable parsing of selectors or declaration values for component parts.

  • Tolerant to errors by design

    Parser behaves as spec says: "When errors occur in CSS, the parser attempts to recover gracefully, throwing away only the minimum amount of content before returning to parsing as normal". The only thing the parser departs from the specification is that it doesn't throw away bad content, but wraps it in a special node type (Raw) that allows processing it later.

  • Fast and efficient

    CSSTree is created with focus on performance and effective memory consumption. Therefore it's one of the fastest CSS parsers at the moment.

  • Syntax validation

    The build-in lexer can test CSS against syntaxes defined by W3C. CSSTree uses mdn/data as a basis for lexer's dictionaries and extends it with vendor specific and legacy syntaxes. Lexer can only check the declaration values currently, but this feature will be extended to other parts of the CSS in the future.

Projects using CSSTree

  • Svelte – Cybernetically enhanced web apps
  • SVGO – Node.js tool for optimizing SVG files
  • CSSO – CSS minifier with structural optimizations
  • NativeScript – NativeScript empowers you to access native APIs from JavaScript directly
  • react-native-svg – SVG library for React Native, React Native Web, and plain React web projects
  • penthouse – Critical Path CSS Generator
  • Bit – Bit is the platform for collaborating on components
  • and more...

Documentation

Tools

Related projects

Usage

Install with npm:

npm install css-tree

Basic usage:

import * as csstree from 'css-tree';

// parse CSS to AST
const ast = csstree.parse('.example { world: "!" }');

// traverse AST and modify it
csstree.walk(ast, (node) => {
    if (node.type === 'ClassSelector' && node.name === 'example') {
        node.name = 'hello';
    }
});

// generate CSS from AST
console.log(csstree.generate(ast));
// .hello{world:"!"}

Syntax matching:

// parse CSS to AST as a declaration value
const ast = csstree.parse('red 1px solid', { context: 'value' });

// match to syntax of `border` property
const matchResult = csstree.lexer.matchProperty('border', ast);

// check first value node is a <color>
console.log(matchResult.isType(ast.children.first, 'color'));
// true

// get a type list matched to a node
console.log(matchResult.getTrace(ast.children.first));
// [ { type: 'Property', name: 'border' },
//   { type: 'Type', name: 'color' },
//   { type: 'Type', name: 'named-color' },
//   { type: 'Keyword', name: 'red' } ]

Exports

Is it possible to import just a needed part of library like a parser or a walker. That's might useful for loading time or bundle size optimisations.

import * as tokenizer from 'css-tree/tokenizer';
import * as parser from 'css-tree/parser';
import * as walker from 'css-tree/walker';
import * as lexer from 'css-tree/lexer';
import * as definitionSyntax from 'css-tree/definition-syntax';
import * as data from 'css-tree/definition-syntax-data';
import * as dataPatch from 'css-tree/definition-syntax-data-patch';
import * as utils from 'css-tree/utils';

Using in a browser

Bundles are available for use in a browser:

  • dist/csstree.js – minified IIFE with csstree as global
<script src="node_modules/css-tree/dist/csstree.js"></script>
<script>
  csstree.parse('.example { color: green }');
</script>
  • dist/csstree.esm.js – minified ES module
<script type="module">
  import { parse } from 'node_modules/css-tree/dist/csstree.esm.js'
  parse('.example { color: green }');
</script>

One of CDN services like unpkg or jsDelivr can be used. By default (for short path) a ESM version is exposing. For IIFE version a full path to a bundle should be specified:

<!-- ESM -->
<script type="module">
  import * as csstree from 'https://cdn.jsdelivr.net/npm/css-tree';
  import * as csstree from 'https://unpkg.com/css-tree';
</script>

<!-- IIFE with an export to global -->
<script src="https://cdn.jsdelivr.net/npm/css-tree/dist/csstree.js"></script>
<script src="https://unpkg.com/css-tree/dist/csstree.js"></script>

Top level API

API map

License

MIT

csstree's People

Contributors

abereghici avatar acconrad avatar blimmer avatar bramus avatar constgen avatar jbraithwaite avatar lahmatiy avatar life777 avatar philschatz avatar scripthunter7 avatar sergejmueller avatar silverwind avatar smelukov avatar strarsis avatar thybzi avatar valtlai avatar xfq avatar xiaoboost avatar xiaoluoboding avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

csstree's Issues

walkDeclarationsRight()

This would be really helpful.

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

Ability to merge AST trees

Perhaps this is an implementation issue and not a valuable feature request within csstree.

I would like to be able to merge AST trees. My context is to generate a minimal CSS payload based on what's used in a DOM, by different DOMs. If DOM1 needs p, b { X } footer { Y } and DOM2 needs p, i {X} header{ Z } then the combined CSS would be p, b, i { X } footer { Y } header { Z }.

Perhaps an option is to just concatenate them into one big string and use some postCSS plugin or somesuch that can merge/minify it to the minimal set.

Some parser false positives

As I know followed case are false positive

Mismatch
  syntax: [ <bg-layer> , ]* <final-bg-layer>
  background: linear-gradient(left,rgba(0,0,0,0) 0,rgba(0,0,0,.2) 50%,rgba(0,0,0,0) 100%)
  ------------^
Mismatch
  syntax: none | <transform-list>
  transform: rotate(0)
  -----------^
Unknown property
  tap-highlight-color: transparent
  ^
Unknown property
  -webkit-print-color-adjust: exact
  ^
Uncomplete match
  syntax: <single-transition>#
  transition: visibility 0 .3s, opacity .3s ease-out
  -----------------------^
Mismatch
  syntax: [ <bg-layer> , ]* <final-bg-layer>
  background: linear-gradient(top,#fff,#f2f2f2)
  ------------^

Error loading module when Array prototype is modified

The following code produces an error when loading css-tree:

"use strict";
Array.prototype.anything = function() { };
require("css-tree");

The error produced:

/tmp/node_modules/css-tree/lib/lexer/structure.js:112
                throw new Error('Wrong value in `' + name + '` structure definition');
                ^

Error: Wrong value in `CDC` structure definition
    at processStructure (/tmp/node_modules/css-tree/lib/lexer/structure.js:112:23)
    at getStructureFromConfig (/tmp/node_modules/css-tree/lib/lexer/structure.js:134:39)
    at Lexer (/tmp/node_modules/css-tree/lib/lexer/Lexer.js:125:35)
    at createSyntax (/tmp/node_modules/css-tree/lib/syntax/create.js:70:20)
    at Object.exports.create (/tmp/node_modules/css-tree/lib/syntax/create.js:81:12)
    at Object.<anonymous> (/tmp/node_modules/css-tree/lib/syntax/index.js:14:38)
    at Module._compile (module.js:573:30)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)

Some modules out there may add additional functions to the Array prototype and this then prevents the css-tree module from being loaded.

Can be fixed by adding this line to css-tree/lib/lexer/structure.js on line 102:

if(!structure.hasOwnProperty(key)) { continue; }

Not sure exactly what the structure.js code is doing here, so not sure if the proposed fix is safe for your code, but my hunch says it is.

Generate Flow typings out of CSS data

Hi, CSSTree looks nice and I want to use to generate & publish Flow typings for CSS data.

I found https://github.com/csstree/csstree/blob/master/data/mozilla-cssdata.json but it seems it syntax field uses BNF-like notation instead of being more structured and represented in JSON. Of course I can parse it myself but probably you can point me in the right direction of how you use it to generate parser / validator?

Sorry if I've abused GH issues—just wanted to start a discussion.

Roadmap 1.0

  • move !important from Value to Declaration
  • Braces -> Parentheses
  • Ruleset -> Rule
  • drop Unknown
  • replace Identifier -> Type/Universal selector
  • FunctionalPseudo -> PseudoClass
  • fix attribute name parsing
  • add Brackets since CSS Grid Layout introduces it
  • at-rule inside block (#24)
  • of clause for nth-child/nth-last-child e.g. nth-child(.. of <Selector>)
  • check number is integer for
    • UnicodeRange
    • Hash
    • Nth (an+b)
  • natural traversal order for walk() (current behaviour should be implemented as walkUp())
  • :matches() (#28)
  • :has()
  • ::slotted()
  • rename sequence -> children for node types
  • end line/column in node.info
  • rename Selector -> SelectorList, SimpleSelector -> Selector
  • fix Block positions (should include {})
  • fix positions for Selector/SimpleSelector to not include ws
  • rename StyleSheet inside at-rule to Block (when at-rule will be allowed inside block)
  • add loc to Nth
  • use balanced raw consumer for custom properties
  • DeclarationList instead of Block and add declarationList context (for <element style=""> context)
  • Atrule.expression should be null when no expression
  • split parser into modules (one per node type)
  • custom parsers for well-known at-rule expressions
  • add Selector suffix for Id, Class, Attribute, Type, PseudoClass and PseudoElement
  • options to parse Value, Selector and AtruleExpression as balanced Raw (parseValue, parseSelector, parseAtruleExpression)
  • option to parse custom property value/fallback as regular value (parseCustomProperty)
  • drop Progid
  • rename Space to WhiteSpace
  • rename Hash to HexColor
  • parse unknown parts of Value as balanced Raw

Under consideration:

  • Percentage -> Dimension
  • multiple Value (no parts comma operator, but list of Value)

    more convenient to work with Value in current form

  • explicit descendant combinator >>

    until any browser support

  • Column combinator ||

    until any browser support

  • convert name node to property in Attribute
    • q: where to store location?
  • namespaces for Type/Universal/Attribute (special case for :matches)
    • q: should we need store it separately?
  • rename loc -> meta (to store formatting info too)
  • rename Block -> {}-block, Parenthesis -> ()-block, Brackets -> []-block according to CSS Syntax Module Level 3 that's for tokens not ast node
  • should SelectorList to be omitted when have a single selector?
  • replace Rule.block to Rule.children and Atrule.block to Atrule.children

    bad idea, since block includes {} now

  • rename positions parse option to loc
  • store formatting info somehow
  • allow percent in @Keyframes selectors only (from/to/percent) should restrict by lexer not parser
  • better name for parse* options looks ok for now

Support for CSS Selectors Level 4

There can be really complex selectors in Selectors Level 4. For example, this is a valid selector (and there is already support for them in latest webkits like Safari 10):

:not(:not(.a), :not(.b), :not(.c), .d, :not(:matches([id=lol] > *))) {
}

Right now csstree throws an “Unexpected input” parsing error there.

No support for legacy background-clip values

From the MDN:

[1] Webkit also supports the prefixed version of this property, and in that case, in addition to the current keywords, the alternative synonyms are: padding, border, and content.

[3] Gecko supported, from version 1.1 to version 1.9.2, which corresponds to Firefox 1.0 to 3.6 included, a different and prefixed syntax: -moz-background-clip: padding | border.

So, for -webkit-background-clip there should be also | padding | border | content and -moz-background-clip had just padding | border (should be tested if that was the only supported by mozillla syntax)

vm instead of Function

Hi! What do you think about using vm-module instead of Function constructor (e.g. in here)?
The problem is that Atom Editor is using CSP and unsafe-eval is not enabled. As a result, we can't update csstree in our Atom plugin

Add missed property syntaxes

According to Microsoft's data of CSS usage on the web platform there are properties that missed in csstree, but used by various sites.
Need to add a definitions for those properties into data/patch.json and to mdn/data when appropriate.

  • -moz-control-character-visibility
  • -moz-window-dragging
  • -ms-content-zoom-chaining
  • -ms-content-zoom-limit-max
  • -ms-content-zoom-limit-min
  • -ms-content-zooming (https://msdn.microsoft.com/en-us/library/hh771891(v=vs.85).aspx)
  • -ms-flow-from
  • -ms-flow-into
  • -ms-grid-columns
  • -ms-hyphenate-limit-chars (https://www.w3.org/TR/css-text-4/)
  • -ms-hyphenate-limit-last (https://www.w3.org/TR/css-text-4/)
  • -ms-hyphenate-limit-lines (https://www.w3.org/TR/css-text-4/)
  • -ms-hyphenate-limit-zone (https://www.w3.org/TR/css-text-4/)
  • -ms-scroll-chaining
  • -ms-scroll-limit-x-max
  • -ms-scroll-limit-y-max
  • -ms-scroll-rails
  • -ms-scroll-translation
  • -ms-touch-select
  • -webkit-app-region
  • -webkit-border-after-color
  • -webkit-border-end-color
  • -webkit-border-horizontal-spacing
  • -webkit-border-start-color
  • -webkit-border-vertical-spacing
  • -webkit-font-size-delta
  • -webkit-highlight
  • -webkit-hyphenate-character (https://www.w3.org/TR/css-text-4/)
  • -webkit-logical-height
  • -webkit-logical-width
  • -webkit-margin-after
  • -webkit-margin-after-collapse
  • -webkit-margin-before
  • -webkit-margin-before-collapse
  • -webkit-margin-bottom-collapse
  • -webkit-margin-end
  • -webkit-margin-start
  • -webkit-margin-top-collapse
  • -webkit-mask-box-image-outset
  • -webkit-mask-box-image-repeat
  • -webkit-mask-box-image-slice
  • -webkit-mask-box-image-source
  • -webkit-mask-box-image-width
  • -webkit-max-logical-width
  • -webkit-min-logical-height
  • -webkit-min-logical-width
  • -webkit-padding-after
  • -webkit-padding-before
  • -webkit-padding-end
  • -webkit-padding-start
  • -webkit-perspective-origin-x
  • -webkit-perspective-origin-y
  • -webkit-rtl-ordering
  • -webkit-text-combine
  • -webkit-text-decorations-in-effect
  • -webkit-transform-origin-x
  • -webkit-transform-origin-y
  • -webkit-transform-origin-z
  • -webkit-user-modify
  • -x-system-font (looks like an internal Firefox thing)
  • background-repeat-x (no intent to spec, see w3c/csswg-drafts#116 for links to discussions at the thread ending)
  • background-repeat-y (no intent to spec, see w3c/csswg-drafts#116 for links to discussions at the thread ending)
  • buffered-rendering
  • color-adjust
  • color-interpolation
  • color-interpolation-filters
  • color-rendering
  • cx (svg)
  • cy (svg)
  • d (svg)
  • enable-background
  • flood-color (svg)
  • flood-opacity (svg)
  • justify-items
  • justify-self
  • layout-grid-char
  • layout-grid-line
  • layout-grid-mode
  • layout-grid-type
  • lighting-color
  • mask-position-x
  • mask-position-y
  • overflow-anchor
  • page
  • paint-order
  • r (svg)
  • ruby-overhang
  • rx (svg)
  • ry (svg)
  • size
  • stop-color
  • stop-opacity
  • text-justify
  • text-kashida
  • text-kashida-space
  • vector-effect
  • x (svg)
  • y (svg)

Lengths can be sometimes without pixels

SVG spec says that

One px unit is defined to be equal to one user unit. Thus, a length of "5px" is the same as a length of "5".

So, for example, stroke-width: 2; should be valid.

Maybe the could be parsed differently in different contexts (regular css/svg properties)?

[alpha20/22] Missing declaration name in declaration in media query

After updating css-tree to latest alpha (20/22),
declaration name in declaration in media query is missing in (svgo/inlineStyles plugin) tests,
see this pared-down test case: https://github.com/strarsis/svgo/tree/test-css-tree-alpha20

$ git clone https://github.com/strarsis/svgo
$ cd svgo
$ git checkout test-css-tree-alpha20
$ yarn install
$ npm test

Downgrading to older alpha (1.0.0-alpha18) resolves this issue,
see the working branch: https://github.com/strarsis/svgo/tree/inlineStyles.

Related issue?: #39

Serialize AST according to CSSOM

The CSS Object Model specification includes many rules on how to serialize CSS in a consistent way. For example, the current translate() output p{color:green} would become p { color: green; } using the CSSOM rules. It even covers parts like how to serialize a string.

I recently started working on an implementation of the CSSOM and would like to use CSSTree as the parser, thanks to the priority you put on parsing standard syntax. I'll probably write my own generate functions if you decline, but I figured I would ask if you want to make CSSTree serialize CSS according to CSSOM by default? Thanks!

Support additional pseudo-elements with arguments?

There are drafts for CSS extensions that use arguments to pseudo-element selectors (ie ::slotted(.foo) or ::before(2)) to allow additional information.

Rather than something like hardcoding lib/parser/type/PseudoElement.js#L20 what if:

  1. the parser allowed any pseudo-element to have optional arguments (instead of special-casing ::slotted(.foo)? or
  2. the css-tree constructor took an additional configuration option containing all the valid pseudoelements and whether arguments were forbidden, allowed, or required?

Thanks again for all the parsing work!

atruleExpression always null

The this.atruleExpression is always null, even with Atrule expressions, even not inside an Atrule expression.
There isn't any node of type 'atruleExpression' or of similar name either.
It would be very convenient if the atruleExpression is available for all its child nodes.

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

var testCss = '@media screen{.st1{fill:red;}}';
var cssAst = csstree.parse(testCss);
csstree.walk(cssAst, function(node, item, list) {
  // this.atruleExpression is always null, even inside node with type == 'Atrule'.
});

Get information about an At-rule

I convert a CSS string to an AST, then to a plain object. Now I want to decide which At-rule to keep. In particular I want to do different things if it's a print rule. I.e. I want to distinguish between media queries and print queries.

> text=`@media print { a { color: red} }
... @media (min-width:100px) { a { color: blue} }
... `
'@media print { a { color: red} }\n@media (min-width:100px) { a { color: blue} }\n'
> csstree.parse(text).children
List {
  cursor: null,
  head:
   { prev: null,
     next: { prev: [Circular], next: null, data: [Object] },
     data:
      { type: 'Atrule',
        loc: null,
        name: 'media',
        expression: [Object],
        block: [Object] } },
  tail:
   { prev: { prev: null, next: [Circular], data: [Object] },
     next: null,
     data:
      { type: 'Atrule',
        loc: null,
        name: 'media',
        expression: [Object],
        block: [Object] } } }

There is no information in each of these the values print or (min-width:100px).

PostCSS (css-loader, Stylelint, CSSModules)

👋 I'm watching this awesome project for a while now and wonder if it would be possible to use with PostCSS in some way or another, especially with the fresh alpha17 (extensibility) release? Would it basically be possible ?

Support for mixed rules and declarations inside at-rules

Some CSS modules have mixed rules and declarations inside at-rules. An example: Paged Media Module allowing stuff like this:

@page :first {
  color: green;

  @top-left {
    content: "foo";
    color: blue;
  }
  @top-right {
    content: "bar";
  }
}

Right now CSSTree returns Parse error: Identifier is expected error, while allowing either only declarations or only nested rules.

While this module is still in Editor's Draft, it is quite possible that other modules could allow this kind of syntax (and this could be helpful for external tools too of course).

stroke-dasharray

2016-09-13 11 41 50
Должно принимать значение none | <dasharray> | inherit, где <dasharray> — «It's a list of comma and/or white space separated <length>s and <percentage>s that specify the lengths of alternating dashes and gaps».

background: linear-gradient issue?

Hi!

First of all: really nice tool!

I think i have found a bug, maybe. The tool found a mismatch, which is no mismatch at all:

Unique properties: 93
Unique declarations: 550 (total: 1228)
✓ Valid: 548 (99.64%)
✗ Invalid: 2 (0.36%)
2 × Mismatch
Mismatch
syntax: [ , ]*
background: linear-gradient(top,rgba(255,255,255,0.9),rgba(255,255,255,1) 20%)
------------^
Mismatch
syntax: [ , ]*
background: linear-gradient(top,rgb(0,0,0),rgb(18,18,18) 100%)
------------^

css:
.site-footer { margin-top: 0rem; background: #121212; background: -webkit-linear-gradient(top, rgb(0, 0, 0), rgb(18, 18, 18) 100%); /* Chrome, Safari */ background: -moz-linear-gradient(top, rgb(0, 0, 0), rgb(18, 18, 18) 100%); /* Firefox */ background: linear-gradient(top, rgb(0, 0, 0), rgb(18, 18, 18) 100%); /* CSS3 */ }

Can you check that?

Cheers!
Patrick

Union with `css-values` and `known-css-properties` repos

Ref to repo: https://github.com/ben-eb/css-values
Ref to repo: https://github.com/betit/known-css-properties

Why:

  • I do not think that's a good idea to keep everything in the project, its code can be divided into independent modules(regards only csstree).
  • It allow open source community to have a good package.
  • I as a participant in the stylelint very interesting in supporting one well filled package, it will be convenient to all.
  • @ben-eb and @vio currently has a little time to contribute(judging by the number commits and frequency of their), all three (and maybe more 😄 ), you do it much faster and better.

@ben-eb @vio what do you think about this?

I would suggest creating a separate organization and hold union in her. It also would give impetus to the creation of new and stable rules for the stylelint and powerfull postcss plugins.

Support for the CSS Color Module Level 4 (Editor's Draft)

It's very exciting to watch so many of the 1.0 roadmap items get ticked-off!

I was wondering if support for the CSS Color Module Level 4 (Editor's Draft) was under consideration, in particular, the color() function (playground here)?

Currently the following CSS:

a { 
  color: color(#eef6f8 alpha(50%));
  border-bottom: 2px solid color(#eef6f8 alpha(30%));
}

Produces the following warnings:

2:2  ✖  Invalid value for `color`   csstree/validator
3:2  ✖  The rest part of value can't to be matched on `border-bottom` syntax   csstree/validator

@lahmatiy's response:

In short, it's a bit complicated and therefore postponed for a while (it's good to have an issue still). CSSTree supports things are supported by browsers first. As I know level 4 is not supported by any browser yet (correct me if I'm wrong). It may be an extension for default syntax still.
I read this module a while ago. While color() looks simple, I found a problem with color-mod syntax. In current form, it's unusual and requires improvements in lexer syntax matcher. Now it is not known exactly that the syntax will be the same in the future (it's a draft). So it's unclear should we do these improvements or not. Supporting for a part of the module looks odd. One more solution to rewrite a color-mod syntax in a regular way and then suggest those changes to the module. But this requires an unknown amount of time. That's why I decided to focus on more obvious things.


Migrated from csstree/stylelint-validator#8.

Make it possible to use e.g. `parse` and `walk` without requiring entire library

Hi — big fan of css-tree, I tried a lot of different CSS parsers to use with Svelte and this one was by far the best, in terms of the AST format and ease of use.

This is a follow-up to sveltejs/svelte#408. To recap: for various reasons, we bundle our dependencies, and until recently (up to 1.0.0-alpha16) we were able to selectively import parse and walk like so;

import parse from 'css-tree/lib/parser/index.js';
import walk from 'css-tree/lib/utils/walk.js';

As of 1.0.0-alpha17 that no longer seems to be possible — we have to import the whole of css-tree. The result is that our bundle size balloons in size, from 417kb (of which 103kb was css-tree) to 770kb.

We were wondering therefore if this is a use case you might consider supporting? Or does the new extensible architecture make that very difficult?

Thank you!

cc @Conduitry

Add tolerance

Related to issue: #16

One svgo test deliberately uses incorrect inline style declarations, css-tree currently aborts parsing it:

'use strict';
var csstree = require('css-tree');
var ast = csstree.parse("fill:#000; c\olor: #fff; /**/illegal-'declaration/*'; -webkit-blah: 123  ; -webkit-trolo: 'lolo'; illegal2*/");
[...]node_modules/css-tree/lib/tokenizer/Tokenizer.js:389
        throw new CssSyntaxError(
        ^

CssSyntaxError: Identifier is expected
    at new CssSyntaxError ([...]node_modules/css-tree/lib/tokenizer/error.js:54:17)
[...]

A tolerance mode would be great also for parsing stylesheet context styles.
It can help coping with broken/strange/exotic styles.

Add tolerance mode to parser

.a {
  display: block;
}.

Gives

Parse error: Identifier is expected
    1 |.a{
    2 |  display: block;
    3 |}.
---------^

I expect that lexer will notify me about this error, but ignore it and continue to consume tokens

"LeftCurlyBracket is expected" error when using parseSelector: false

Hi, I wanted to parse some styles with parseSelector: false, but when I do that I see following error:

Parse error: LeftCurlyBracket is expected
    1 |div {}
-------------^

Steps to reproduce:

$ mkdir css-test && cd css-test
$ npm install css-tree

Create index.js file with this code:

var parse = require('css-tree').parse;

try {
	var ast = parse('div {}', {
		parseSelector: false
	});

	console.log(ast);
} catch (e) {
	console.log(e.formattedMessage);
}

and run

$ node index.js

Interesting is that when I clone this repository and try to write the code above as test, it works just fine.

Versions: both 1.0.0-alpha22 and 171664a.

PostCSS + CSSTree

Do you want to integrate CSSTree into PostCSS?

You will get more user base because of Autoprefixer, CSS Modules, Stylelint. Also many tools will use same parser and AST — unification is best for all.

Right now I see this thing to fix:

  • Save all spaces in AST.
  • Parse non-standard CSS. Non-standard properties, values, at-rule. Allow at-rule and rules inside rules.
  • Is it possible to split validation and parsing?
  • We need AST compatibility. We can extend PostCSS AST. Or we could convert AST for old plugins. Do you have some new ideas in AST API? I recommend to extend PostCSS AST, because anyway we need “event based”/“visitor” API. So it will be better to change parser in PostCSS 6 and introduce some better AST API in 7.

This issue is just my thoughts, not real plan. What do you think about it?

Support for font-display

I am use CSSTree as a plugin for Gulp. And when I trying to use font-display property it fails with 'unknown property' error. Can you add support for that property?
MDN
Spec

Better way to get access to ancestor nodes on AST traversal

Currently, context is used for storing references to some upper nodes. It's good enough but doesn't work in some cases, e.g. reference to Parentheses node needed or check if current Atrule has a parent Atrule node.

We need a better solution to get access to ancestor nodes.

Cannot read property 'each' of undefined

When using css-tree walkDeclarations with a csso AST, a TypeError is thrown.

Sample code for reproducing this issue:

var csso = require('csso'),
    walkDeclarations = require('css-tree').walkDeclarations;

var css = '.test { color: red; }';
var ast = csso.parse(css);

walkDeclarations(ast, function(node, item, list) {
  console.log(node, item);
});

Dependencies for this sample:

$ npm install csso csstree/csstree

css-tree is actually used by csso internally, also for parsing, so there shouldn't be compatibility issues.

Unknown custom properties inside @media

In the following file --list-scale property is marked as unknown though it works fine in browsers:

.shower.list {

    position: absolute;
    clip: rect(0 auto auto 0);

    margin: 0;
    padding-top: calc(
        var(--slide-width) *
        var(--list-gutter) *
        var(--list-scale));
    padding-left: calc(
        var(--slide-width) *
        var(--list-gutter) *
        var(--list-scale));

    display: flex;
    flex-wrap: wrap;

    background: #666;

    }

/* Scale */

@media (min-width: 1120px) {
    .shower.list {
        --list-scale: 0.5;
        }
    }
@media (min-width: 2240px) {
    .shower.list {
        --list-scale: 1;
        }
    }

image

Implement at-rule validation

Lexer should be able to validate at-rules

  • @charset
  • @import
  • @namespace
  • @media
  • @supports
  • @document
  • @page
  • @font-face
  • @keyframes
  • @viewport
  • @counter-style
  • @font-feature-values

Parse error: Unexpected input

Parse error: Unexpected input
194 | font-size:.846em;
195 | text-shadow:0 -1px #000;
196 | filter:dropshadow(color=#000,offx=0,offy=-1);
-------------------------------^
197 | color:#fff;
198 | border:.091em solid #3e3e3e;

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.