css

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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).

View Source
const FlagID = 1

FlagID is set on a Hash token that is a valid identifier, usable as an id selector.

View Source
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).

View Source
const MaxGradientStops = 64

MaxGradientStops bounds the color stops of a gradient.

View Source
const MaxLengthPx = 1e7

MaxLengthPx bounds every length, in CSS px: larger values are clamped, so layout arithmetic stays finite.

View Source
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

func Fields(toks []Token) [][]Token

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

func HasClampedLength(toks []Token) bool

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

func LowerASCII(s string) string

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

func ParseAngle(t Token) (float64, bool)

ParseAngle parses an angle token (deg, rad, grad, turn, or the unitless 0) and returns it in degrees, normalised to [0, 360).

func SkipBlock

func SkipBlock(toks []Token, i int) int

SkipBlock returns the index of the token after toks[i], past the whole block when toks[i] opens one (a function, parenthesis, bracket or brace).

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

func ParseColor(toks []Token) (Color, bool)

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 ColorStop

type ColorStop struct {
	Color Color
	Pos   float64
}

ColorStop is a color at a position along the gradient line, in [0, 1].

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 Corner

type Corner uint8

Corner is the target corner of a "to <corner>" gradient direction.

const (
	CornerNone Corner = iota
	CornerTopRight
	CornerBottomRight
	CornerBottomLeft
	CornerTopLeft
)

Corners. The angle of a corner gradient depends on the box it paints, so it is left to layout.

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 Entry

type Entry[T any] struct {
	Selector *Selector
	Value    T
}

Entry is a selector with the value the caller associates to it.

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

func ParseGradient(toks []Token) (Gradient, bool)

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]) Add

func (ix *Index[T]) Add(sel *Selector, v T)

Add files sel. A selector that never matches is not kept.

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.

func (*Index[T]) Len

func (ix *Index[T]) Len() int

Len returns the number of selectors in the index.

type KeyKind

type KeyKind uint8

KeyKind is the kind of the index key of a selector.

const (
	KeyUniversal KeyKind = iota
	KeyID
	KeyClass
	KeyTag
)

Key kinds, from the most to the least selective.

type Length

type Length struct {
	Value float64
	// Unit is UnitPx, UnitEm, UnitRem or UnitPercent.
	Unit Unit
}

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

func ParseLength(toks []Token) (Length, bool)

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.

func (Length) Resolve

func (l Length) Resolve(fontSize, rootFontSize, percentBase float64) float64

Resolve returns the length in px. fontSize and rootFontSize are the em and rem bases and percentBase the base of a percentage, all in px. The result is finite and clamped to ±MaxLengthPx whatever the arguments.

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 Origin

type Origin uint8

Origin tells where a stylesheet comes from.

const (
	OriginUA Origin = iota
	OriginDocument
	OriginExtra
)

Origins, from lowest to highest priority of the cascade.

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

func ParseSelectors(prelude []Token, b *budget.Budget) ([]*Selector, error)

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

func (s *Selector) Key() (KeyKind, string)

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

func (s *Selector) Match(d *dom.Document, e int32, b *budget.Budget) (bool, error)

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

func (s *Selector) NeverMatches() bool

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.

func (*Selector) String

func (s *Selector) String() string

String returns the canonical text 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) IDs

func (s Specificity) IDs() int

IDs returns the first field: id selectors.

func (Specificity) Types

func (s Specificity) Types() int

Types returns the third field: types and pseudo-elements.

type Stylesheet

type Stylesheet struct {
	Origin Origin
	Rules  []Rule
	// contains filtered or unexported fields
}

Stylesheet is an immutable parsed stylesheet.

func ParseStylesheet

func ParseStylesheet(src []byte, origin Origin, b *budget.Budget) (*Stylesheet, error)

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

type Token struct {
	Type  Type
	Unit  Unit
	Flags uint8
	Num   float32
	End   int32
	Text  string
}

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).

func TrimSpace

func TrimSpace(toks []Token) []Token

TrimSpace returns toks without its leading and trailing whitespace tokens.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL