GithubHelp home page GithubHelp logo

validator'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

validator's People

Contributors

lahmatiy avatar sideshowbarker avatar smelukov 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

Watchers

 avatar  avatar  avatar  avatar

validator's Issues

clamp() throwing an incorrect error

It seems that using clamp() as a value in both height and font-size both fail validation. This is likely a problem with clamp() across all properties.

Specifically, I'm using the basic examples from MDN as a test case:

height: clamp(1rem, 10vw, 2rem);
font-size: clamp(1rem, 10vw, 2rem);

Validator on max() and min()

CSStree-validator flags errors on usage of max() and min() on font-sizes and widths. Could you please explain why?

Content counters are not recognized as valid CSS

content: counters(...) does not work for me (csstree-validator v.1.6.0).

Example code:

.some-class {
  content: counters(list-counter, ".") "."
}

Output:

Mismatch
  syntax: normal | none | [ <content-replacement> | <content-list> ] [ / <string> ]?
   value: counters(list-counter,".") "."

support for `@layer`

currently, when using cascade layers, the csstree-validator extension shows this error:

[CSSTree] Unknown at-rule `@layer`

@layer has been supported in all modern browsers for about a year now, so it would be nice to have support for it.

i understand that it can be difficult to maintain compatibility with every new feature and i'm happy to help in any way. i also think that it would be nice to have some kind of "allowlist" to prevent errors on such new syntaxes.

Invalid Level 3 :not() selectors

The level 3 negation pseudo-class only support a single simple selector (ref), so all of the following css selectors should return errors (showing as valid in csstree-validator v1.3.1):

.foo:not(li, div) { color: red; }
.foo:not(li.bar) { color: red; }

/* Nestet: https://www.w3.org/TR/2018/CR-selectors-3-20180130/#negation */
.foo:not(:not(li)) { color: red; }

From my understanding, :not(li.bar) is allowed in level 4, but I'm not sure if nested :not()s will also be allowed.

Marking as invalid browser properties

csstree validator marks browser prefix properties values as invalid :

An example :

# target/webapp-compress/css/main.css
    * Invalid value for `display` property
      syntax: [ <display-outside> || <display-inside> ] | <display-listitem> | <display-internal> | <display-box> | <display-legacy> | <-non-standard-display>
       value: -ms-flexbox
      --------^
    * Invalid value for `display` property
      syntax: [ <display-outside> || <display-inside> ] | <display-listitem> | <display-internal> | <display-box> | <display-legacy> | <-non-standard-display>
       value: -ms-flexbox

At least, should be ignored by a option of the validator.

Attempted import error: 'validate' is not exported from 'csstree-validator'.

I have installed "csstree-validator": "^3.0.0", version and imported in react application
import { validate } from 'csstree-validator';
Trying to run it but getting following error
Attempted import error: 'validate' is not exported from 'csstree-validator'.
csstree_validator__WEBPACK_IMPORTED_MODULE_13__.default.validate is not a function

After changing import statement to import { validate } from 'csstree-validator/lib/validate'; the code is working fine. Is this a known issue ?

Note: version 2.0.1 is working fine.

Lack of semicolon is not detected as an error

Hi, thanks for building this! I'm trying to use it to validate user-input CSS in the browser before building Gatsby site with the result.

One thing that this does not seem to detect is lack of semicolons:

Say I have the following snippet

 :root {
    --header-font:"Lato", sans-serif;
    --body-font:"Open Sans", sans-serif;
    --page-color: rgba(255, 255, 255, 0.95)
    --text-color: #3f4758;
}

https://jigsaw.w3.org/css-validator/#validate_by_input would fail to validate that CSS and Gatsby/Webpack would fail when building the bundle with it. But csstree-validator does not seem to detect any issues with it 🙁

!important without whitespace considered invalid in some cases

Related to csstree/csstree/issues/155

Should we be using matchDeclaration() instead of matchProperty()?

const { validate } = require('csstree-validator');
console.log(validate('a { width: calc(100% - 10px)!important }'));
[
	SyntaxError [SyntaxMatchError]: Mismatch
		at matchSyntax (node_modules\css-tree\lib\lexer\Lexer.js:87:17)
		at Lexer.matchProperty (node_modules\css-tree\lib\lexer\Lexer.js:331:16)
		at validateDeclaration (node_modules\csstree-validator\lib\validate.js:103:45)
		at List.<anonymous> (node_modules\csstree-validator\lib\validate.js:120:32)
		at List.each (node_modules\css-tree\lib\common\List.js:158:12)
		at validateRule (node_modules\csstree-validator\lib\validate.js:118:29)
		at Object.enter (node_modules\csstree-validator\lib\validate.js:158:28)
		at Object.<anonymous> (node_modules\css-tree\lib\walker\create.js:11:16) {
	  message: 'Invalid value for `width` property',
	  rawMessage: 'Mismatch',
	  syntax: 'auto | <length> | <percentage> | min-content | max-content | fit-content( <length-percentage> )',
	  css: 'calc(100% - 10px)!important',
	  mismatchOffset: 17,
	  mismatchLength: 1,
	  offset: 28,
	  line: 1,
	  column: 29,
	  loc: { source: '<unknown>', start: [Object], end: [Object] },
	  property: 'width',
	  details: 'Mismatch\n' +
		'  syntax: auto | <length> | <percentage> | min-content | max-content | fit-content( <length-percentage> )\n' +
		'   value: calc(100% - 10px)!important\n' +
		'  -------------------------^'
	}
  ]

Add fix-suggestion

.some
{
   color: rgb(255, 0, 255, 1);
}

In this example, alpha component is excess and validator will tell about it: Mismatch syntax
But, will be cool if validator will suggesting some fixes for these (and similar) cases:

fixes: [
  'rgb(255, 0, 255);',
  'rgba(255, 0, 255, 1);'
]

Some other examples:

  • add missed unit
.some
{
   width: 10;
}
fixes: [
  '10px'
]
  • fix mistyped
.some
{
   coor: rgb(255, 0, 255, 1);
}
fixes: [
  'color'
]

support exit code

I am trying to do something like:

$ csstree-validator sample.css && ... || ...

Unfortunately, the exit code is always zero no matter whether it is valid.

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.