Documentation
¶
Overview ¶
Package css tokenizes and parses CSS into compact tokens and a rule tree.
The lexer is github.com/tdewolff/parse/v2/css over parse.NewInputBytes; the parser follows the error recovery of CSS Syntax Level 3 §5 and never fails on malformed input: it drops the offending rule or declaration and reports it with budget.Warn, so a caller that must be strict (ExtraCSS, the UA sheet) only has to check that no warning was recorded.
Input is hostile. Text is valid UTF-8 without controls other than tab, LF and CR; nesting of blocks and functions is bounded by MaxNesting; the size of every source is charged to budget.CSSBytes before it is read.
Index ¶
- Constants
- func Fields(toks []Token) [][]Token
- func HasClampedLength(toks []Token) bool
- func LowerASCII(s string) string
- func ParseAngle(t Token) (float64, bool)
- func SkipBlock(toks []Token, i int) int
- type Color
- type ColorStop
- type Combinator
- type Corner
- type Declaration
- type Entry
- type Gradient
- type GradientShape
- type Index
- type KeyKind
- type Length
- type MediaEnv
- type MediaQuery
- type Origin
- type PseudoElement
- type Rule
- type RuleKind
- type Selector
- type Specificity
- type Stylesheet
- type Token
- type Type
- type Unit
Constants ¶
const ( // MaxCompounds is the number of compound selectors of a selector. MaxCompounds = 32 // MaxSimple is the number of simple selectors of a compound selector. MaxSimple = 32 )
Limits of one selector (design §6.1).
const FlagID = 1
FlagID is set on a Hash token that is a valid identifier, usable as an id selector.
const FlagInt = 2
FlagInt is set on a Number token written as an integer: no fraction, no exponent (CSS Syntax 3 §4.3.12 "integer" type flag).
const MaxGradientStops = 64
MaxGradientStops bounds the color stops of a gradient.
const MaxLengthPx = 1e7
MaxLengthPx bounds every length, in CSS px: larger values are clamped, so layout arithmetic stays finite.
const MaxNesting = 64
MaxNesting is the maximum depth of nested blocks and functions inside one prelude or declaration value, and of nested @media rules. Deeper items are dropped with a warning.
Variables ¶
This section is empty.
Functions ¶
func Fields ¶
Fields splits toks at top-level whitespace, ignoring whitespace inside blocks. At most 128 fields are split: the rest comes back as one more field, so that a hostile value costs a bounded number of slices.
func HasClampedLength ¶
HasClampedLength reports whether a dimension or percentage token of toks, at any depth, is beyond ±MaxLengthPx once converted to px, so that ParseLength clamps it.
func LowerASCII ¶
LowerASCII lowercases the ASCII letters of s only. It is the one fold CSS keywords and names use: Unicode folding would read U+212A (Kelvin sign) as k.
func ParseAngle ¶
ParseAngle parses an angle token (deg, rad, grad, turn, or the unitless 0) and returns it in degrees, normalised to [0, 360).
Types ¶
type Color ¶
type Color struct{ R, G, B, A float64 }
Color is a non-premultiplied sRGB color with every component in [0, 1].
func ParseColor ¶
ParseColor parses a hex color (#rgb, #rgba, #rrggbb, #rrggbbaa), rgb() and rgba() in the comma and the space/slash syntaxes, a named color or transparent. Components are clamped to their range. Anything else, currentcolor and var() included, is rejected.
type Combinator ¶
type Combinator uint8
Combinator links a compound selector to the one on its left.
const ( CombNone Combinator = iota // CombDescendant is " ". CombDescendant // CombChild is ">". CombChild // CombNext is "+": the next sibling. CombNext // CombLater is "~": any later sibling. CombLater )
Combinators; CombNone is the first compound of a selector.
type Declaration ¶
type Declaration struct {
Name string
Value []Token
Important bool
// contains filtered or unexported fields
}
Declaration is a property declaration. Name is lowercase except for custom properties ("--x"), which keep their case. Value is trimmed of whitespace and of "!important".
func ParseDeclarations ¶
func ParseDeclarations(src []byte, b *budget.Budget) ([]Declaration, error)
ParseDeclarations parses a declaration list such as a style attribute, charging len(src) to CSSBytes and one unit of Work per lexer token.
type Gradient ¶
type Gradient struct {
// Shape is GradientLinear for every linear gradient.
Shape GradientShape
// Angle is the direction in degrees, CSS convention: 0 points up and
// angles grow clockwise. It is in [0, 360) and unused when Corner is set or
// Shape is not linear.
Angle float64
Corner Corner
// Stops has 2 to MaxGradientStops entries with non-decreasing positions.
Stops []ColorStop
}
Gradient is a linear-gradient() or a radial-gradient().
func ParseGradient ¶
ParseGradient parses linear-gradient() or radial-gradient(). A linear one has an optional angle (deg, rad, grad, turn or the unitless 0) or "to <side|corner>", then at least two color stops with optional percentage positions. A radial one has an optional "[circle | ellipse] [farthest-corner] [at center]" (other sizes and positions are rejected), then the stops. Colors may be translucent. Missing positions are spread as in CSS Images §3.5.3 and positions are made non-decreasing. Lengths as positions, interpolation hints, repeating gradients and other gradient types are rejected.
type GradientShape ¶
type GradientShape uint8
GradientShape tells a linear gradient from a radial one.
const ( GradientLinear GradientShape = iota GradientCircle GradientEllipse )
Gradient shapes. Radial gradients are always "farthest-corner at center".
type Index ¶
type Index[T any] struct { // contains filtered or unexported fields }
Index files selectors by the key of their rightmost compound, so that an element is only tested against the selectors that can match it. It is built once and only read afterwards: concurrent Candidates calls are safe.
func (*Index[T]) Candidates ¶
func (ix *Index[T]) Candidates(d *dom.Document, e int32, dst []Entry[T], b *budget.Budget) ([]Entry[T], error)
Candidates appends to dst the entries whose key matches element e of d: those are the only selectors that can match e. They still have to be matched, and Match charges for it; their order is not specified. Every class looked up is charged workStep and the entries appended one unit per appendBatch, both before the append. On a budget error dst holds what was appended before it.
type Length ¶
Length is a CSS length. Token numbers are float32, so Value carries float32 precision (1234.5678px is 1234.56775). Absolute units are converted to px at parse time; Em, Rem and Percent keep their unit until the computed style knows the font sizes and the percentage base.
func ParseLength ¶
ParseLength parses a length or percentage: a dimension in px, pt, pc, in, cm, mm, Q, em or rem, a percentage, or the unitless number 0. Other units, functions such as calc() and anything else are rejected. The value is clamped to ±MaxLengthPx.
type MediaEnv ¶
type MediaEnv struct {
// Print is true for the print medium, false for screen.
Print bool
// Width and Height are the viewport size in px.
Width, Height float64
}
MediaEnv describes the medium a document is rendered for: the PDF is always paged ("print") and its page area gives the viewport size, in CSS px.
type MediaQuery ¶
type MediaQuery struct {
// contains filtered or unexported fields
}
MediaQuery is a parsed media query list. The zero value, like an empty prelude, matches every medium.
func ParseMediaQuery ¶
func ParseMediaQuery(prelude []Token, b *budget.Budget) MediaQuery
ParseMediaQuery parses the prelude of an @media rule: a comma-separated list of [not|only] type [and (feature: value)]* or (feature: value) [and ...]*, with the types all, print and screen and the features width, min-width, max-width, height, min-height, max-height and orientation. A query that is malformed or uses anything else evaluates to false, as the specification requires, and is reported with an invalid-value warning whose detail is the query text; the others of the list still count. An unknown media type is valid and matches nothing, without a warning.
func (MediaQuery) Match ¶
func (q MediaQuery) Match(env MediaEnv) bool
Match reports whether the query list matches env.
type PseudoElement ¶
type PseudoElement uint8
PseudoElement is the pseudo-element a selector targets, if any. A selector with a pseudo-element is matched against the originating element: the style stage applies the rule to the generated box.
const ( PseudoNone PseudoElement = iota PseudoBefore PseudoAfter )
Pseudo-elements.
type Rule ¶
type Rule struct {
Kind RuleKind
Name string
Prelude []Token
Decls []Declaration
Rules []Rule
// contains filtered or unexported fields
}
Rule is a style rule, an @media rule, an @page rule or a margin box.
type RuleKind ¶
type RuleKind uint8
RuleKind is the kind of a Rule.
const ( // RuleStyle is a qualified rule: Prelude holds the selector tokens. RuleStyle RuleKind = iota + 1 // RuleMedia is an @media rule: Prelude holds the query tokens, Rules its body. RuleMedia // RulePage is an @page rule: Prelude holds the page selector tokens, Decls // its declarations and Rules its margin boxes. RulePage // RuleMarginBox is a margin at-rule of an @page rule; Name is its name // without "@", lowercase. RuleMarginBox )
Rule kinds.
type Selector ¶
type Selector struct {
// contains filtered or unexported fields
}
Selector is a parsed complex selector. It is immutable and shared by concurrent renders.
func ParseSelectors ¶
ParseSelectors parses the prelude of a style rule: a comma separated list of selectors. Each member is charged to budget.Selectors before it is read, and a budget error is returned. A list with a member that is malformed or outside the supported subset is dropped as a whole, as CSS requires: the result is nil and an unsupported-selector warning is recorded.
Type selectors are matched in lowercase against HTML tag names; foreign (SVG, MathML) subtrees are skipped by box.Build in M1, so their case-adjusted names need no folding.
Supported: type, *, #id, .class, [attr], [attr=value] and the operators ~= |= ^= $= *= with the i and s flags, :root, :first-child, :last-child, :nth-child(an+b | odd | even), the interaction pseudo-classes that never match on paper (:hover, :focus, :active, :visited, :focus-within, :focus-visible, :target), the pseudo-elements ::before and ::after, and the combinators " ", ">", "+" and "~".
func (*Selector) Key ¶
Key returns the key under which the rule index files the selector: the id, else the first class, else the type name of its rightmost compound, else KeyUniversal with an empty string.
func (*Selector) Match ¶
Match reports whether element e of d matches the selector. When the selector has a pseudo-element, it is the element the pseudo-element belongs to that is tested.
Match charges budget.Work before every step: workCandidate for the call, workCombinator and workStep along combinators, and an amount proportional to the bytes it is about to scan for classes and attributes. :first-child, :last-child, :nth-child and + cost O(1) thanks to the sibling index of the DOM; ~ visits the previous siblings. A *budget.LimitError, or the context error, aborts the match.
func (*Selector) NeverMatches ¶
NeverMatches reports whether the selector holds an interaction pseudo-class (:hover...), which never matches.
func (*Selector) Pseudo ¶
func (s *Selector) Pseudo() PseudoElement
Pseudo returns the pseudo-element s targets.
func (*Selector) Specificity ¶
func (s *Selector) Specificity() Specificity
Specificity returns the specificity of s.
type Specificity ¶
type Specificity uint32
Specificity is the (a, b, c) specificity of a selector packed as a<<20 | b<<10 | c with every field saturated at 1023, so that integer comparison orders selectors.
func (Specificity) Classes ¶
func (s Specificity) Classes() int
Classes returns the second field: classes, attributes and pseudo-classes.
func (Specificity) Types ¶
func (s Specificity) Types() int
Types returns the third field: types and pseudo-elements.
type Stylesheet ¶
Stylesheet is an immutable parsed stylesheet.
func ParseStylesheet ¶
ParseStylesheet parses src. It charges len(src) to CSSBytes and one unit of Work per lexer token, and returns only budget errors: malformed input is dropped, each dropped rule or declaration recorded with b.Warn. Preludes are raw tokens; selectors and media queries are parsed by the callers. Empty style rules are omitted.
type Token ¶
Token is one CSS token, 32 bytes.
- Ident, Function, AtKeyword, Hash, String, URL, Delim, UnicodeRange, Match: Text is the unescaped value without delimiters ("rgb" for "rgb(", "id" for "#id", the target of url(...)). Hash has FlagID in Flags when it is a valid id.
- Number, Percentage, Dimension: Num is the value (finite, clamped to the float32 range); Dimension carries Unit, and Text only for UnitOther.
- Opening tokens: End is the number of tokens from this one to just after the matching closer (or to the end of the slice when unclosed).
type Type ¶
type Type uint8
Type is the kind of a Token.
const ( TIdent Type = iota + 1 TFunction TAtKeyword THash TString TBadString TURL TBadURL TDelim TNumber TPercentage TDimension TUnicodeRange TMatch TWhitespace TCDO TCDC TColon TSemicolon TComma TLBracket TRBracket TLParen TRParen TLBrace TRBrace )
Token types. Brackets and parentheses are kept as tokens; for every opening token (TFunction, TLParen, TLBracket, TLBrace) Token.End gives the extent of the block.
type Unit ¶
type Unit uint8
Unit is the unit of a TDimension or TPercentage token.
const ( UnitNone Unit = iota UnitPx UnitPt UnitPc UnitIn UnitCm UnitMm UnitQ UnitEm UnitRem UnitEx UnitCh UnitVw UnitVh UnitVmin UnitVmax UnitPercent UnitDeg UnitRad UnitGrad UnitTurn UnitS UnitMs UnitFr UnitDpi UnitDpcm UnitDppx UnitOther )
Units. UnitOther keeps the original spelling in Token.Text.