A CSS Syntax Level 3 tokenizer and parser in Elixir, with CSS Nesting and a Selectors Level 4 selector parser. It has no runtime dependencies.
Installation
def deps do
[
{:stylesheet_parser, "~> 0.1"}
]
endUsage
{:ok, stylesheet} =
StylesheetParser.parse_stylesheet("""
:root { --space-s: 6px; }
@media (prefers-color-scheme: dark) { :root { --text: #ececf0; } }
.card > .title { padding: var(--space-s) 12px; }
""")
%StylesheetParser.Stylesheet{rules: [root, media, card], errors: []} = stylesheet
%StylesheetParser.QualifiedRule{prelude: [%StylesheetParser.SimpleSelector{type: :pseudo_class, value: ":root"}]} = root
%StylesheetParser.AtRule{name: "@media", block: [%StylesheetParser.QualifiedRule{}]} = media
%StylesheetParser.QualifiedRule{
line: 3,
block: [%StylesheetParser.Declaration{name: "padding", value: [%StylesheetParser.Function{name: "var"}, {:whitespace, " "}, {:dimension, ["12", "px"]}]}]
} = card- Tokens are
{type, value, metadata}, like Elixir AST, with[line: l, column: c]metadata. Rules, declarations, functions and simple blocks carry thelineandcolumnwhere they start; the values inside them are{type, value}. - A token's value is its source text: strings keep their quotes, and escapes stay escaped.
- A qualified rule's
preludeis its selector list (in@keyframes, its component values, such as50%). A block, a style rule's or an at-rule's, is its declarations and rules in order, with nested style rules and&.:is(),:where(),:not()and the:nth-*()pseudo-classes are aStylesheetParser.PseudoClassof their parsed selectors and An+B,{a, b}. - Malformed input is dropped as the spec recovers from it, and each
%StylesheetParser.ParseError{message, line, column}is in the stylesheet'serrors: a declaration with no colon, a rule whose selectors don't parse, an unclosed block. StylesheetParser.prewalk/2,postwalk/2andtraverse/4walk the rules and declarations, to replace or drop them, such as to sanitize what can load or run code. Names keep their escapes as written (b\65haviorisbehaviorto a browser), so compare themStylesheetParser.unescape/1d.to_string/1serializes what it parsed. Comments are dropped (a/**/stays only where two tokens would otherwise run together) and whitespace normalized, so the output parses to the same rules again.
See the documentation for the parser entry points and the structs they return.