Documentation
¶
Overview ¶
Package css is the CSS side of onehtml that does not need a document: the CSS Syntax tokenizer and parser with exact source ranges, canonical serialization, and the conditions of conditional rules (media query lists and @supports).
Syntax ¶
ParseStylesheet, ParseBlockContents and ParseDeclarations return a Tree: the tokens, the comments between them and the rules and declarations found in them. ParseRule, ParseDeclaration, ParseValue and ParseValues parse one item or a list of component values. Malformed CSS never fails: constructs the specification drops stay in the tree as NodeInvalid nodes, so every byte of the input belongs to some construct and a tree always re-serializes to its source (Tree.Source). The only errors are limits (ErrLimit), and the three outcomes of the single-item entry points (ErrEmpty, ErrInvalid, ErrExtraInput).
All offsets are byte offsets into the UTF-8 source text. Nothing recurses on nesting depth: blocks deeper than WithMaxNesting stay unparsed and Tree.NestingLimitReached reports it.
A stylesheet that arrives as bytes is decoded by onehtml.ParseStylesheet (byte order mark, Content-Type charset, @charset, UTF-8); its decoded text goes to ParseStylesheet when a syntax tree is wanted.
Conditions ¶
ParseMediaQueries parses a media query list, canonicalizes it and evaluates it against an Environment. ParseSupports does the same for the condition of an @supports rule, and DeclarationSupported asks whether a property accepts a value.
The package is pure computation: it fetches nothing and runs nothing.
Index ¶
- Constants
- Variables
- func DeclarationSupported(property, value string) bool
- func ExpandShorthand(property, value string) ([]Longhand, ExpandStatus)
- func Properties() iter.Seq[Property]
- func ResolveCustomProperties(custom map[string]string) map[string]string
- func SerializeIdent(s string) string
- func SerializeString(s string) string
- func SubstituteVars(text string, custom map[string]string) (string, error)
- func ValidDeclaration(property, value string) bool
- type Accept
- type AnPlusB
- type AtRuleKind
- type Color
- func (c Color) Alpha() (a float64, none bool)
- func (c Color) Component(i int) (v float64, none bool)
- func (c Color) Convert(to ColorSpace) (Color, error)
- func (c Color) IsCurrentColor() bool
- func (c Color) NRGBA() color.NRGBA
- func (c Color) RGBA() (r, g, b, a uint32)
- func (c Color) Space() ColorSpace
- func (c Color) String() string
- func (c Color) SystemName() string
- type ColorOption
- type ColorSpace
- type ComponentValue
- type ComponentValues
- func (l ComponentValues) All() iter.Seq[ComponentValue]
- func (l ComponentValues) IsEmpty() bool
- func (l ComponentValues) Len() int
- func (l ComponentValues) Raw() string
- func (l ComponentValues) Span() Span
- func (l ComponentValues) Split() []ComponentValues
- func (l ComponentValues) String() string
- func (l ComponentValues) Trim() ComponentValues
- type ContainerRule
- type Dimension
- type Environment
- type ExpandStatus
- type ImportRule
- type Inheritance
- type LayerRule
- type LengthContext
- type LimitError
- type Longhand
- type MediaQuery
- type MediaQueryList
- type NamespaceRule
- type Node
- func (n Node) AtRuleKind() AtRuleKind
- func (n Node) Block() ComponentValues
- func (n Node) BlockClosed() bool
- func (n Node) BlockSpan() Span
- func (n Node) Charset() (string, bool)
- func (n Node) Children() iter.Seq[Node]
- func (n Node) ColonSpan() Span
- func (n Node) Container() (ContainerRule, bool)
- func (n Node) ContentSpan() Span
- func (n Node) Custom() bool
- func (n Node) HasBlock() bool
- func (n Node) Import() (ImportRule, bool)
- func (n Node) Important() bool
- func (n Node) ImportantSpan() (Span, bool)
- func (n Node) Kind() NodeKind
- func (n Node) Layer() (LayerRule, bool)
- func (n Node) Name() string
- func (n Node) NameSpan() Span
- func (n Node) Namespace() (NamespaceRule, bool)
- func (n Node) Parent() (Node, bool)
- func (n Node) Prelude() ComponentValues
- func (n Node) PreludeSpan() Span
- func (n Node) PreludeText() string
- func (n Node) Raw() string
- func (n Node) SemicolonSpan() (Span, bool)
- func (n Node) Span() Span
- func (n Node) Value() ComponentValues
- func (n Node) ValueSpan() Span
- func (n Node) ValueText() string
- type NodeKind
- type ParseOption
- type Property
- type Quantity
- type QuantityOption
- type Span
- type SupportsCondition
- type SupportsOption
- type Token
- type TokenKind
- type Tree
- type ValueKind
Examples ¶
- Color.Convert
- ExpandShorthand
- LookupProperty
- NewColor
- ParseAnPlusB
- ParseColor
- ParseDeclaration
- ParseMediaQueries
- ParseQuantity
- ParseStylesheet
- ParseStylesheet (AtRules)
- ParseSupports
- ParseValues
- Properties
- ResolveCustomProperties
- SerializeIdent
- SubstituteVars
- Tree.Tokens
- ValidDeclaration
- WithMaxTokens
Constants ¶
const ( // LimitInputSize is the size of the source in bytes ([WithMaxInput]; the // functions that take no options hold the default of 16 MiB). LimitInputSize = "input size" // LimitTokens is the number of tokens in the source ([WithMaxTokens]). LimitTokens = "token count" )
The names a LimitError.Limit can hold.
const ( TokenIdent = TokenKind(icss.Ident) TokenFunction = TokenKind(icss.Function) // a name and "(" TokenAtKeyword = TokenKind(icss.AtKeyword) TokenHash = TokenKind(icss.Hash) TokenString = TokenKind(icss.String) TokenBadString = TokenKind(icss.BadString) TokenURL = TokenKind(icss.URL) TokenBadURL = TokenKind(icss.BadURL) TokenDelim = TokenKind(icss.Delim) TokenNumber = TokenKind(icss.Number) TokenPercentage = TokenKind(icss.Percentage) TokenDimension = TokenKind(icss.Dimension) TokenUnicodeRange = TokenKind(icss.UnicodeRange) TokenWhitespace = TokenKind(icss.Whitespace) TokenCDO = TokenKind(icss.CDO) TokenCDC = TokenKind(icss.CDC) TokenColon = TokenKind(icss.Colon) TokenSemicolon = TokenKind(icss.Semicolon) TokenComma = TokenKind(icss.Comma) TokenLBracket = TokenKind(icss.LBracket) TokenRBracket = TokenKind(icss.RBracket) TokenLParen = TokenKind(icss.LParen) TokenRParen = TokenKind(icss.RParen) TokenLBrace = TokenKind(icss.LBrace) TokenRBrace = TokenKind(icss.RBrace) )
Token kinds, one per token type of CSS Syntax.
Variables ¶
var ( // ErrEmpty means the input holds nothing but whitespace and comments. ErrEmpty = errors.New("css: empty input") // ErrInvalid means the input is not the item asked for: not a rule, a // declaration or one component value, or text that is not a valid number, // colour, colour space or substitution. ErrInvalid = errors.New("css: invalid input") // ErrExtraInput means the item is followed by more input. ErrExtraInput = errors.New("css: extra input after the item") )
The outcomes other than success of the single-item parsers (ParseRule, ParseDeclaration, ParseValue), and of the value functions (ParseColor, ParseQuantity, NewColor, Color.Convert, SubstituteVars). The first three follow CSS Syntax 5.4.
var ErrLimit = limit.Err
ErrLimit matches (with errors.Is) every error that reports input beyond a limit; the concrete error is a *LimitError. It is the same value as onehtml.ErrLimit and encoding.ErrLimit.
Functions ¶
func DeclarationSupported ¶
DeclarationSupported reports whether the library knows the property and the value matches its grammar, as "@supports (property: value)" asks. A value that is beyond the input limit is not supported. ValidDeclaration asks the question of a declaration in a style rule.
func ExpandShorthand ¶
func ExpandShorthand(property, value string) ([]Longhand, ExpandStatus)
ExpandShorthand splits the value of a shorthand into its leaf longhands (nested shorthands flattened, reset-only longhands "initial"), in table order. A CSS-wide keyword gives every longhand that keyword. Shorthands with a grammar here: the box-edge shorthands (margin, padding, inset, border-color and the like), border and its sides, outline, column-rule, text-decoration, list-style, font (with the system font keywords), font-variant, font-synthesis, background, transition, animation, columns, grid-area, grid-row, grid-column and the two-longhand pairs including place-content, place-items and place-self; for the others the status is ExpandUnsupported.
The longhands are nil unless the status is ExpandDone. Input over 16 MiB is ExpandInvalid.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/css"
)
func main() {
lh, status := css.ExpandShorthand("margin", "1px 2px")
fmt.Println(status)
for _, l := range lh {
fmt.Println(l.Name, l.Value)
}
_, status = css.ExpandShorthand("margin", "var(--m)")
fmt.Println(status)
}
Output: expanded margin-top 1px margin-right 2px margin-bottom 1px margin-left 2px pending-substitution
func Properties ¶
Properties iterates over the whole property table in alphabetical order, aliases included.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/css"
)
func main() {
n := 0
for p := range css.Properties() {
if p.AliasOf != "" {
n++
}
}
fmt.Println(n > 0)
}
Output: true
func ResolveCustomProperties ¶
ResolveCustomProperties computes the custom properties of a set: each value with its own var() references substituted. A property in a cycle, or one whose references fail, is left out of the result.
Example ¶
package main
import (
"fmt"
"sort"
"recursiveai.org/go/onehtml/css"
)
func main() {
got := css.ResolveCustomProperties(map[string]string{"--a": "1px", "--b": "var(--a) 2px", "--x": "var(--y)", "--y": "var(--x)"})
keys := make([]string, 0, len(got))
for k := range got {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Println(k, got[k])
}
}
Output: --a 1px --b 1px 2px
func SerializeIdent ¶
SerializeIdent returns s as a CSS identifier, escaped as the CSSOM requires ("serialize an identifier").
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/css"
)
func main() {
fmt.Println(css.SerializeIdent("1a b"), css.SerializeString("say \"hi\"\n"))
}
Output: \31 a\ b "say \"hi\"\a "
func SerializeString ¶
SerializeString returns s as a double-quoted CSS string, escaped as the CSSOM requires ("serialize a string").
func SubstituteVars ¶
SubstituteVars replaces the var() references in text using custom properties, a map from name ("--gap") to value text, following CSS Variables 1: fallbacks, nested references, and cycles (a property in a cycle is invalid, even where a fallback exists). It returns ErrInvalid when the result is invalid at computed-value time. The substitution never recurses on nesting depth.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/css"
)
func main() {
props := map[string]string{"--gap": "4px", "--pad": "calc(var(--gap) * 2)"}
s, err := css.SubstituteVars("var(--pad) var(--missing, 1px)", props)
fmt.Println(s, err)
_, err = css.SubstituteVars("var(--missing)", props)
fmt.Println(err)
}
Output: calc(4px * 2) 1px <nil> css: invalid input
func ValidDeclaration ¶
ValidDeclaration reports whether "property: value" is a valid declaration of a known property or a custom property, under the property's value definition (CSS Syntax §5). A name that is not in the property table, and is not a custom property, is not valid. It is the check a style rule's declaration gets; DeclarationSupported is the same grammar check as "@supports (property: value)" evaluates it.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/css"
)
func main() {
fmt.Println(css.ValidDeclaration("display", "grid"), css.ValidDeclaration("display", "grd"),
css.ValidDeclaration("width", "calc(1px + 2%)"))
}
Output: true false true
Types ¶
type Accept ¶
type Accept uint16
Accept is a set of the kinds of quantity a property takes. Combine them with |; for example a property taking a length or a percentage accepts AcceptLength | AcceptPercentage, also written AcceptLengthPercentage.
const ( AcceptNumber Accept = 1 << iota // AcceptInteger accepts a number that has no fractional part and // refuses the others; without [AcceptNumber] it is the only number form. AcceptInteger AcceptLength AcceptPercentage AcceptAngle AcceptTime AcceptFrequency AcceptResolution AcceptFlex // AcceptNonNegative refuses values below zero. AcceptNonNegative // AcceptUnitlessZero reads a bare 0 as a length. AcceptUnitlessZero // AcceptLengthPercentage is a length or a percentage. AcceptLengthPercentage = AcceptLength | AcceptPercentage )
The kinds a quantity may be, and two refinements.
type AnPlusB ¶
type AnPlusB struct{ A, B int }
AnPlusB is the value of an <an+b> microsyntax (CSS Syntax 6): the step A and the offset B of "An+B".
func ParseAnPlusB ¶
ParseAnPlusB parses text as <an+b> in any of its spellings: "odd", "even", an integer, or An+B. Whitespace around the value is allowed. It reports false for anything else, and for text beyond the input limit.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/css"
)
func main() {
v, ok := css.ParseAnPlusB(" 2n + 1 ")
fmt.Println(v, ok)
v, ok = css.ParseAnPlusB("odd")
fmt.Println(v, ok)
}
Output: 2n+1 true 2n+1 true
type AtRuleKind ¶
type AtRuleKind string
AtRuleKind names a kind of at-rule: the lower-cased name for the at-rules the package knows, AtUnknown for any other.
const ( AtMedia AtRuleKind = "media" AtSupports AtRuleKind = "supports" AtLayer AtRuleKind = "layer" AtImport AtRuleKind = "import" AtContainer AtRuleKind = "container" AtNamespace AtRuleKind = "namespace" AtCharset AtRuleKind = "charset" AtFontFace AtRuleKind = "font-face" AtKeyframes AtRuleKind = "keyframes" AtPage AtRuleKind = "page" AtScope AtRuleKind = "scope" AtProperty AtRuleKind = "property" AtCounterStyle AtRuleKind = "counter-style" AtFontFeatureValues AtRuleKind = "font-feature-values" AtFontPaletteValues AtRuleKind = "font-palette-values" AtStartingStyle AtRuleKind = "starting-style" AtPositionTry AtRuleKind = "position-try" AtViewTransition AtRuleKind = "view-transition" AtViewport AtRuleKind = "viewport" AtDocument AtRuleKind = "document" AtCustomMedia AtRuleKind = "custom-media" AtUnknown AtRuleKind = "unknown" )
The at-rule kinds. Those with typed accessors on Node are Charset, Import, Layer, Namespace and Container; the prelude of Media and Supports goes to ParseMediaQueries and ParseSupports.
type Color ¶
type Color struct {
// contains filtered or unexported fields
}
Color is a parsed CSS colour: three coordinates in a colour space and an alpha, any of which may be "missing" (the keyword none). Hue angles are in degrees; the coordinates are as CSS Color 4 writes them for the space (percentages as 0..100 for lab, hsl and hwb lightness and so on).
The zero Color is transparent black in sRGB. A colour keeps whether it was written in a legacy syntax (hex, named, rgb(), hsl(), hwb()), which decides how Color.String serializes it.
func NewColor ¶
func NewColor(space ColorSpace, c0, c1, c2, alpha float64) (Color, error)
NewColor builds a colour from coordinates in a space. A NaN coordinate or alpha is a missing component (none). It returns ErrInvalid for an unknown space. The result is not in a legacy syntax.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/css"
)
func main() {
c, _ := css.NewColor(css.SRGB, 0.2, 0.4, 0.6, 1)
fmt.Println(c)
}
Output: color(srgb 0.2 0.4 0.6)
func ParseColor ¶
func ParseColor(text string, opts ...ColorOption) (Color, error)
ParseColor parses text as one colour: named colours, hex in 3, 4, 6 and 8 digits, rgb(), rgba(), hsl(), hsla(), hwb(), lab(), lch(), oklab(), oklch(), color() with the predefined spaces, color-mix(), relative colours, light-dark(), system colours and currentcolor (CSS Color 4 and 5). Keywords match ASCII case-insensitively and surrounding white space is ignored.
currentcolor has no value of its own: the colour returned reports Color.IsCurrentColor and has no meaningful coordinates. It returns ErrInvalid for anything else that is not one colour, and an error matching ErrLimit for text over 16 MiB.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/css"
)
func main() {
c, _ := css.ParseColor("#ff8000")
fmt.Println(c.Space(), c, c.NRGBA())
c, _ = css.ParseColor("oklch(70% 0.2 none / 0.5)")
h, none := c.Component(2)
a, _ := c.Alpha()
fmt.Println(c.Space(), h, none, a)
dark, _ := css.ParseColor("light-dark(white, black)", css.WithDarkScheme())
fmt.Println(dark.NRGBA())
}
Output: srgb rgb(255, 128, 0) {255 128 0 255} oklch 0 true 0.5 {0 0 0 255}
func (Color) Alpha ¶
Alpha returns the alpha, 0 to 1 as written (not clamped), and whether it is missing (none).
func (Color) Component ¶
Component returns coordinate i (0 to 2) and whether it is missing (none); a missing coordinate is returned as 0. Out-of-range i returns 0, false.
func (Color) Convert ¶
func (c Color) Convert(to ColorSpace) (Color, error)
Convert returns the colour in another space (CSS Color 4 §12). A conversion to a polar space marks the hue missing when the colour has no chroma. It returns ErrInvalid for an unknown space or for currentcolor.
Example ¶
package main
import (
"fmt"
"image/color"
"recursiveai.org/go/onehtml/css"
)
func main() {
red, _ := css.ParseColor("color(display-p3 1 0 0)")
lab, _ := red.Convert(css.Lab)
l, _ := lab.Component(0)
fmt.Printf("%s %.1f\n", lab.Space(), l)
// Out of the sRGB gamut: mapped by reducing chroma.
fmt.Println(red.NRGBA())
var _ color.Color = red
}
Output: lab 56.2 {255 11 12 255}
func (Color) IsCurrentColor ¶
IsCurrentColor reports that the colour was the keyword currentcolor.
func (Color) NRGBA ¶
NRGBA returns the colour as 8-bit non-premultiplied sRGB, mapped into the sRGB gamut by the CSS Color 4 §14 algorithm (chroma reduction in OKLCH until the clipped colour is within a just noticeable difference of 0.02). A missing coordinate counts as zero. currentcolor gives transparent black.
func (Color) RGBA ¶
RGBA implements color.Color, through Color.NRGBA.
func (Color) Space ¶
func (c Color) Space() ColorSpace
Space returns the space the coordinates are in, as written (a colour written as hex or rgb() is in SRGB). It is "" for currentcolor.
func (Color) String ¶
String serializes the colour as CSSOM does for a computed value: rgb() or rgba() with 8-bit channels for a legacy colour, otherwise the colour's own function (color(display-p3 ...), oklch(...)). It is "currentcolor" for that keyword.
func (Color) SystemName ¶
SystemName returns the system colour keyword (Canvas, ButtonText, ...) the colour was written as, in lower case, or "".
type ColorOption ¶
type ColorOption func(*colorConfig)
ColorOption configures ParseColor.
func WithDarkScheme ¶
func WithDarkScheme() ColorOption
WithDarkScheme resolves light-dark() and the system colours for the dark colour scheme; the default is the light scheme.
type ColorSpace ¶
type ColorSpace string
ColorSpace names a colour space by its CSS Color 4 name.
const ( SRGB ColorSpace = "srgb" SRGBLinear ColorSpace = "srgb-linear" DisplayP3 ColorSpace = "display-p3" DisplayP3Linear ColorSpace = "display-p3-linear" A98RGB ColorSpace = "a98-rgb" ProPhotoRGB ColorSpace = "prophoto-rgb" Rec2020 ColorSpace = "rec2020" XYZD50 ColorSpace = "xyz-d50" XYZD65 ColorSpace = "xyz-d65" Lab ColorSpace = "lab" LCH ColorSpace = "lch" OKLab ColorSpace = "oklab" OKLCH ColorSpace = "oklch" HSL ColorSpace = "hsl" HWB ColorSpace = "hwb" )
The colour spaces a Color can be in and converted to. HSL and HWB are the legacy cylinder forms of sRGB.
type ComponentValue ¶
type ComponentValue struct {
// contains filtered or unexported fields
}
ComponentValue is a preserved token, a function or a simple block. It is a small handle on a Tree; the zero value is empty.
func ParseValue ¶
func ParseValue(src string, opts ...ParseOption) (ComponentValue, error)
ParseValue parses src as exactly one component value (CSS Syntax 5.4.8).
func (ComponentValue) Children ¶
func (v ComponentValue) Children() ComponentValues
Children returns the values inside a function or block, which is empty for a token.
func (ComponentValue) Closed ¶
func (v ComponentValue) Closed() bool
Closed reports whether a function or block has its closing token; one cut off by the end of the input does not. It is true for a token.
func (ComponentValue) Kind ¶
func (v ComponentValue) Kind() ValueKind
Kind returns what the value is. The zero value is a ValueToken.
func (ComponentValue) Raw ¶
func (v ComponentValue) Raw() string
Raw returns the value as written in the source.
func (ComponentValue) Span ¶
func (v ComponentValue) Span() Span
Span returns the source range of the value, a whole block included.
func (ComponentValue) String ¶
func (v ComponentValue) String() string
String returns the canonical serialization of the value (CSS Syntax 9): comments dropped, runs of whitespace as one space, anything left open closed.
func (ComponentValue) Token ¶
func (v ComponentValue) Token() Token
Token returns the token: the token itself, or the opening token of a function or block.
type ComponentValues ¶
type ComponentValues struct {
// contains filtered or unexported fields
}
ComponentValues is a list of component values: the prelude or value of a rule, the inside of a block, or a whole source. It is a view on a Tree; the zero value is empty.
func (ComponentValues) All ¶
func (l ComponentValues) All() iter.Seq[ComponentValue]
All returns the values in order. Whitespace is a value.
func (ComponentValues) IsEmpty ¶
func (l ComponentValues) IsEmpty() bool
IsEmpty reports whether the list has no values.
func (ComponentValues) Len ¶
func (l ComponentValues) Len() int
Len returns the number of top-level values (a function or block counts once, whatever it holds).
func (ComponentValues) Raw ¶
func (l ComponentValues) Raw() string
Raw returns the list as written in the source, comments included.
func (ComponentValues) Span ¶
func (l ComponentValues) Span() Span
Span returns the source range from the first value to the end of the last; for an empty list, an empty range where the list would start.
func (ComponentValues) Split ¶
func (l ComponentValues) Split() []ComponentValues
Split cuts the list at its top-level commas (CSS Syntax 5.4.10). An empty list has no parts, and a final comma adds none.
func (ComponentValues) String ¶
func (l ComponentValues) String() string
String returns the canonical serialization of the list (CSS Syntax 9): every token in canonical form, one space for a run of whitespace, no comments, open blocks closed. Parsing the result gives the same tokens, and serializing those again gives the same text.
func (ComponentValues) Trim ¶
func (l ComponentValues) Trim() ComponentValues
Trim returns the list without whitespace at both ends.
type ContainerRule ¶
type ContainerRule struct {
// Name is the container name, valid when HasName.
Name string
HasName bool
// Condition is the container condition as written.
Condition string
}
ContainerRule is a @container rule (CSS Containment 3).
type Dimension ¶
type Dimension uint8
Dimension is what a quantity measures.
type Environment ¶
type Environment struct {
// Print selects the print media type; otherwise it is screen.
Print bool
// Width and Height are the viewport in CSS pixels; zero means 1280 x 720.
Width, Height float64
// DevicePixelRatio is the resolution in dots per px; zero means 1.
DevicePixelRatio float64
// ColorScheme is prefers-color-scheme: "light" or "dark".
ColorScheme string
// ReducedMotion, ReducedTransparency and ReducedData make the matching
// prefers-reduced-* feature "reduce".
ReducedMotion, ReducedTransparency, ReducedData bool
// Contrast is prefers-contrast: "no-preference", "more", "less" or "custom".
Contrast string
// ForcedColors makes forced-colors "active".
ForcedColors bool
// Hover and AnyHover are "hover" or "none"; Pointer and AnyPointer are
// "fine", "coarse" or "none". Empty means a mouse: "hover" and "fine".
Hover, AnyHover string
Pointer, AnyPointer string
// ColorBits is the bits per colour component, zero meaning 8. Monochrome
// makes the display monochrome (color is 0, monochrome is 8).
ColorBits int
Monochrome bool
// Scripting makes scripting "enabled"; otherwise it is "none".
Scripting bool
}
Environment describes the output a media query list is evaluated against (Media Queries 5). The zero value is a 1280 x 720 light-scheme screen with no preferences set, a mouse and 8-bit colour. Fields hold the keyword the feature takes; an unknown keyword leaves the default.
type ExpandStatus ¶
type ExpandStatus uint8
ExpandStatus says how ExpandShorthand fared.
const ( // ExpandNotShorthand: the property is not a shorthand (or unknown). ExpandNotShorthand ExpandStatus = iota // ExpandDone: the longhands were found. ExpandDone // ExpandUnsupported: the shorthand has no grammar here; keep its value as // written. ExpandUnsupported // ExpandInvalid: the value does not match the shorthand's grammar. ExpandInvalid // ExpandPending: the value holds var() and cannot be split until // the variables are known. ExpandPending )
The outcomes of expanding a value.
func (ExpandStatus) String ¶
func (s ExpandStatus) String() string
String returns "not-shorthand", "expanded", "not-expanded", "invalid" or "pending-substitution".
type ImportRule ¶
type ImportRule struct {
// URL is the url as a string, from a string, a url token or url("...");
// HasURL is false when the rule has none.
URL string
HasURL bool
// HasLayer is set for "layer" and "layer(name)"; LayerName is the name
// as written, empty for the anonymous layer.
HasLayer bool
LayerName string
// Supports is the text inside supports(...), valid when HasSupports.
Supports string
HasSupports bool
// Media is the media query list text that follows, to give to
// [ParseMediaQueries]; it may be empty.
Media string
}
ImportRule is the prelude of an @import rule (CSS Cascade 5, "@import"): a url, then optionally layer, supports() and a media query list.
type Inheritance ¶
type Inheritance uint8
Inheritance says whether a property inherits by default.
const ( // InheritanceUnstated: the property table does not say (shorthands // whose longhands differ, or a source that is silent). InheritanceUnstated Inheritance = iota Inherited NotInherited )
The values of Property.Inheritance.
type LayerRule ¶
type LayerRule struct {
// Statement is true for "@layer a, b;" and false for a block "@layer a { }".
Statement bool
// Names are the layer names as written, in order; a block rule has at
// most one, and none for an anonymous layer.
Names []string
}
LayerRule is a @layer rule (CSS Cascade 5).
type LengthContext ¶
type LengthContext struct {
FontSize, RootFontSize float64
LineHeight, RootLineHeight float64
ExRatio, CapRatio float64
RootExRatio, RootCapRatio float64
ViewportWidth, ViewportHeight float64
LargeWidth, LargeHeight float64
SmallWidth, SmallHeight float64
DynamicWidth, DynamicHeight float64
ContainerWidth, ContainerHeight float64
// VerticalWritingMode swaps the inline and block axes of vi, vb and the
// container-relative units.
VerticalWritingMode bool
}
LengthContext supplies what relative lengths measure when a quantity is resolved. The library never measures fonts or windows: the caller says. A zero field takes its default: a 16px font and root font, an em of 0.5 for ex and ch, 0.7 for cap, a 1280 x 720 viewport; the large, small and dynamic viewports follow the viewport and the container follows the small viewport. A zero line height leaves lh and rlh unresolved.
type LimitError ¶
type LimitError struct {
// Limit names the limit: one of the Limit constants.
Limit string
// Max is the value that was exceeded.
Max int
}
LimitError reports input that exceeds a limit: one set with WithMaxInput or WithMaxTokens, or the default input limit. It matches ErrLimit.
type Longhand ¶
type Longhand struct {
Name, Value string
}
Longhand is one longhand of an expanded shorthand.
type MediaQuery ¶
type MediaQuery struct {
// contains filtered or unexported fields
}
MediaQuery is one comma-separated query of a MediaQueryList.
func (MediaQuery) Matches ¶
func (q MediaQuery) Matches(env Environment) bool
Matches reports whether the query matches env.
func (MediaQuery) Negated ¶
func (q MediaQuery) Negated() bool
Negated reports whether a media type is preceded by "not".
func (MediaQuery) Only ¶
func (q MediaQuery) Only() bool
Only reports whether a media type is preceded by "only".
func (MediaQuery) String ¶
func (q MediaQuery) String() string
String returns the query as CSSOM serializes it, or "not all" when it is not valid.
func (MediaQuery) Type ¶
func (q MediaQuery) Type() string
Type returns the lower-case media type a valid query names ("screen", "print", "all", ...), and is empty for a query that is only a condition.
type MediaQueryList ¶
type MediaQueryList struct {
// contains filtered or unexported fields
}
MediaQueryList is a parsed media query list (Media Queries 5, as CSSOM reads it). A query that does not parse is "not all" and the others still count; an empty list matches everything. The zero value is the empty list.
func ParseMediaQueries ¶
func ParseMediaQueries(text string, opts ...ParseOption) (MediaQueryList, error)
ParseMediaQueries parses a media query list, such as the value of a media attribute or the prelude of @media. Malformed queries never fail the parse; the only error is a limit (ErrLimit).
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/css"
)
func main() {
l, _ := css.ParseMediaQueries("SCREEN and (min-width:600px), print")
fmt.Println(l)
for _, q := range l.Queries() {
fmt.Println(q.Type(), q.Matches(css.Environment{Width: 800}))
}
fmt.Println(l.Matches(css.Environment{Width: 400}), l.Matches(css.Environment{Print: true}))
}
Output: screen and (min-width: 600px), print screen true print false false true
func (MediaQueryList) Len ¶
func (l MediaQueryList) Len() int
Len returns the number of queries; an empty list has none.
func (MediaQueryList) Matches ¶
func (l MediaQueryList) Matches(env Environment) bool
Matches reports whether the list matches env: true for an empty list, otherwise whether any of its queries does.
func (MediaQueryList) Queries ¶
func (l MediaQueryList) Queries() []MediaQuery
Queries returns the queries of the list in order.
func (MediaQueryList) String ¶
func (l MediaQueryList) String() string
String returns the list as CSSOM serializes a media query list: queries joined by ", ", keywords and feature names in lower case, one space around ":" and range operators, and "not all" for a query that does not parse.
type NamespaceRule ¶
type NamespaceRule struct {
// Prefix is the namespace prefix, valid when HasPrefix (the default
// namespace has none).
Prefix string
HasPrefix bool
// URI is the namespace, from a string or url(), valid when HasURI.
URI string
HasURI bool
}
NamespaceRule is a @namespace rule (CSS Namespaces).
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node is a rule or a declaration of a Tree. It is a small handle; the zero value is a NodeInvalid node that answers empty values.
func ParseDeclaration ¶
func ParseDeclaration(src string, opts ...ParseOption) (Node, error)
ParseDeclaration parses src as exactly one declaration (CSS Syntax 5.4.7). The value ends at the first semicolon; text after it is ErrExtraInput.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/css"
)
func main() {
d, err := css.ParseDeclaration("Color : red ! important")
fmt.Println(d.Name(), d.ValueText(), d.Important(), err)
_, err = css.ParseDeclaration("color: red; x")
fmt.Println(err)
}
Output: Color red true <nil> css: extra input after the item
func ParseRule ¶
func ParseRule(src string, opts ...ParseOption) (Node, error)
ParseRule parses src as exactly one rule (CSS Syntax 5.4.6). The error is ErrEmpty, ErrInvalid, ErrExtraInput or a limit.
func (Node) AtRuleKind ¶
func (n Node) AtRuleKind() AtRuleKind
AtRuleKind returns the kind of an at-rule node, matching its name without regard to ASCII case; it is empty for other nodes.
func (Node) Block ¶
func (n Node) Block() ComponentValues
Block returns the component values inside the braces of the block (the rule's contents as a flat list), or an empty list without a block.
func (Node) BlockClosed ¶
BlockClosed reports whether the rule's block has its closing brace.
func (Node) BlockSpan ¶
BlockSpan returns the source range of the block from "{" to "}" inclusive, or to the end of the source when it is not closed. It is empty without a block.
func (Node) Charset ¶
Charset reads a @charset rule and returns its encoding label, with false when the node is not one or the rule has no string. A @charset rule is not a rule of the stylesheet: it only sets the encoding of the bytes (CSS Syntax 3.2).
func (Node) Children ¶
Children returns the nodes nested in the node's block, declarations and rules interleaved in source order.
func (Node) Container ¶
func (n Node) Container() (ContainerRule, bool)
Container reads a @container rule. It reports false for any other node.
func (Node) ContentSpan ¶
ContentSpan returns the source range inside the braces of the block, comments included, or an empty range without a block.
func (Node) Custom ¶
Custom reports whether a declaration is a custom property: its name starts with "--".
func (Node) HasBlock ¶
HasBlock reports whether a rule has a {} block (an at-rule may end with a semicolon instead).
func (Node) Import ¶
func (n Node) Import() (ImportRule, bool)
Import reads an @import rule. It reports false for any other node.
func (Node) ImportantSpan ¶
ImportantSpan returns the range from the "!" to the end of "important", and false when the declaration has none.
func (Node) Name ¶
Name returns the name of an at-rule (without "@") or a declaration, with escapes resolved and the case as written. It is empty for other nodes.
func (Node) NameSpan ¶
NameSpan returns the source range of the name token; for an at-rule it includes the "@".
func (Node) Namespace ¶
func (n Node) Namespace() (NamespaceRule, bool)
Namespace reads a @namespace rule. It reports false for any other node.
func (Node) Prelude ¶
func (n Node) Prelude() ComponentValues
Prelude returns the component values between the start of a rule and its block or semicolon, whitespace included (use ComponentValues.Trim). It is empty for a declaration.
func (Node) PreludeSpan ¶
PreludeSpan returns the source range of the prelude without the whitespace around it.
func (Node) PreludeText ¶
PreludeText returns the prelude as written, without the whitespace around it.
func (Node) SemicolonSpan ¶
SemicolonSpan returns the range of the semicolon that ends an at-rule that has no block, and false when there is none.
func (Node) Span ¶
Span returns the source range of the node, including its terminating semicolon or closing brace when there is one.
func (Node) Value ¶
func (n Node) Value() ComponentValues
Value returns the component values of a declaration's value: without the whitespace after the colon, a trailing !important and the whitespace before it. The value of a unicode-range declaration may hold unicode-range tokens (CSS Syntax 5.5.11). It is empty for other nodes.
type NodeKind ¶
type NodeKind uint8
NodeKind is the type of a rule or declaration node.
const ( // NodeInvalid is a construct the specification drops: a declaration without // a colon, a stray token, a rule that cannot be parsed. It stays in the // tree so its bytes still belong to something. The zero Node is invalid. NodeInvalid NodeKind = iota // NodeAtRule is an at-rule: "@name prelude;" or "@name prelude { ... }". NodeAtRule // NodeQualifiedRule is a rule with a prelude and a block, such as a style rule. NodeQualifiedRule // NodeDeclaration is "name: value" with an optional !important. NodeDeclaration )
type ParseOption ¶
type ParseOption func(*parseConfig)
ParseOption configures a parse function. Limits follow the root package's rule: zero means the default and a negative value means no limit.
func WithMaxInput ¶
func WithMaxInput(n int) ParseOption
WithMaxInput limits the input to n bytes (default 16 MiB). Larger input is a *LimitError. Zero keeps the default; a negative n lifts the limit as far as the parser can go, 2 GiB less one byte.
func WithMaxNesting ¶
func WithMaxNesting(n int) ParseOption
WithMaxNesting sets the deepest nesting of blocks and functions that is paired and parsed (default 256). Deeper input is not an error: the block that crosses the limit, and what follows, stay unparsed, and Tree.NestingLimitReached is set. Zero keeps the default; a negative n pairs every block, which costs memory in proportion to the input but never recursion.
func WithMaxTokens ¶
func WithMaxTokens(n int) ParseOption
WithMaxTokens limits the input to n tokens. More tokens is a *LimitError, reported as soon as the limit is passed. Zero (the default) or a negative n means only the input limit applies.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/css"
)
func main() {
_, err := css.ParseStylesheet("a{b:c}", css.WithMaxTokens(3))
fmt.Println(err)
}
Output: css: token count exceeds the limit of 3
type Property ¶
type Property struct {
// Name is the property's name in lower case.
Name string
// AliasOf is the property this legacy alias (-webkit-box-shadow) stands
// for, or "".
AliasOf string
// Longhands are the properties a shorthand sets, in table order; nested
// shorthands appear as themselves. Empty for a longhand.
Longhands []string
// ResetLonghands are the longhands a shorthand resets without a way to
// set them (for example font-size-adjust in font).
ResetLonghands []string
// LogicalGroup names the group of logical and physical counterparts the
// property belongs to ("margin", "inset"), or "".
LogicalGroup string
// Inheritance says whether the property inherits by default.
Inheritance Inheritance
// Initial is the initial value as the specification writes it: a value
// where the source gives one, otherwise prose or "" (shorthands, and
// properties such as font-family whose initial value depends on the
// user agent).
Initial string
}
Property is a row of the property table, generated from the CSS specifications' property definitions (W3C webref).
func LookupProperty ¶
LookupProperty reads the property table by name, ASCII case-insensitively. A legacy alias answers with its own row (see Property.AliasOf). Custom properties are not in the table.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/css"
)
func main() {
p, _ := css.LookupProperty("margin-inline-start")
fmt.Println(p.Name, p.LogicalGroup, p.Inheritance == css.NotInherited, p.Initial)
m, _ := css.LookupProperty("margin")
fmt.Println(m.IsShorthand(), m.Longhands)
}
Output: margin-inline-start margin true 0 true [margin-top margin-right margin-bottom margin-left]
func (Property) IsShorthand ¶
IsShorthand reports whether the property sets other properties.
type Quantity ¶
type Quantity struct {
// CSS is the serialization: a number or dimension with its unit in the
// case CSSOM writes it, a math function as calc(...).
CSS string
// Dimension is what the value measures.
Dimension Dimension
// Value is the value in the dimension's canonical unit (px, deg, s, Hz,
// dppx, fr). Percentages are resolved against the base given by
// [WithPercentBase]; HasValue is false, and Value zero, when there is a
// percentage and no base.
Value float64
HasValue bool
// HasPercentage reports a percentage anywhere in the value.
HasPercentage bool
}
Quantity is a number, percentage or dimension as CSS Values 4 defines it, or the folded result of a math function such as calc().
func ParseQuantity ¶
func ParseQuantity(text string, accept Accept, opts ...QuantityOption) (Quantity, error)
ParseQuantity parses text as one number, percentage, dimension or math function (calc, min, max, clamp, round, mod, rem, the trigonometric, exponential and sign functions) and checks it against what accept allows, by the rules of CSS Values and Units 4: units match ASCII case-insensitively, a calculation is type-checked and folded, and a percentage in a calculation is refused where accept has no percentage. Surrounding white space is ignored.
It returns ErrInvalid for text that is no such value or is not allowed, and an error matching ErrLimit for text over 16 MiB.
Example ¶
package main
import (
"errors"
"fmt"
"recursiveai.org/go/onehtml/css"
)
func main() {
q, err := css.ParseQuantity("calc(1em + 4px)", css.AcceptLength,
css.WithLengthContext(css.LengthContext{FontSize: 20}))
fmt.Println(q.CSS, q.Dimension, q.Value, err)
q, _ = css.ParseQuantity("calc(50% + 10px)", css.AcceptLengthPercentage, css.WithPercentBase(200))
fmt.Println(q.CSS, q.Value, q.HasPercentage)
_, err = css.ParseQuantity("10deg", css.AcceptLength)
fmt.Println(errors.Is(err, css.ErrInvalid))
}
Output: calc(24px) length 24 <nil> calc(50% + 10px) 110 true true
type QuantityOption ¶
type QuantityOption func(*quantityConfig)
QuantityOption configures ParseQuantity.
func WithLengthContext ¶
func WithLengthContext(c LengthContext) QuantityOption
WithLengthContext sets what em, rem, vw and the other relative units measure. The default is the zero LengthContext.
func WithPercentBase ¶
func WithPercentBase(base float64) QuantityOption
WithPercentBase resolves percentages, in a plain value and inside math functions, as a share of base (in the canonical unit of the quantity).
type Span ¶
type Span struct{ Start, End int }
Span is a half-open range [Start, End) of byte offsets into the source.
type SupportsCondition ¶
type SupportsCondition struct {
// contains filtered or unexported fields
}
SupportsCondition is a parsed @supports condition (CSS Conditional 3 and 4): "not", "and", "or" and parentheses around (property: value) and selector(...); a bare "property: value" is accepted as one declaration, as the supports() of an @import rule takes it.
func ParseSupports ¶
func ParseSupports(text string, opts ...ParseOption) (SupportsCondition, error)
ParseSupports parses the condition of an @supports rule. A malformed condition is not an error: it parses, reports SupportsCondition.Valid false and evaluates to false. The only error is a limit (ErrLimit).
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/css"
)
func main() {
c, _ := css.ParseSupports("(display: grid) and (not (frobnicate: yes))")
fmt.Println(c.Valid(), c.Evaluate())
fmt.Println(css.DeclarationSupported("color", "#fff"), css.DeclarationSupported("color", "12px"))
s, _ := css.ParseSupports("selector(a > b) or selector(:made-up)")
fmt.Println(s.Evaluate(css.WithSelectorSupport(func(sel string) bool { return sel == "a > b" })))
}
Output: true true true false true
func (SupportsCondition) Evaluate ¶
func (c SupportsCondition) Evaluate(opts ...SupportsOption) bool
Evaluate reports whether the condition holds: whether the library supports the properties and values, and the selectors, it names. A property is supported when it is known and the value matches its grammar; a value with var() is checked for var() syntax only. An invalid condition is false.
func (SupportsCondition) String ¶
func (c SupportsCondition) String() string
String returns the condition as written, without the whitespace around it.
func (SupportsCondition) Valid ¶
func (c SupportsCondition) Valid() bool
Valid reports whether the text is a well-formed condition, whatever it evaluates to.
type SupportsOption ¶
type SupportsOption func(*supportsConfig)
SupportsOption configures SupportsCondition.Evaluate.
func WithSelectorSupport ¶
func WithSelectorSupport(fn func(selector string) bool) SupportsOption
WithSelectorSupport decides the selector() terms of a condition: fn receives the selector text and reports whether the engine supports it. By default a selector is supported when it is one valid complex selector of Selectors 4.
type Token ¶
type Token struct {
Kind TokenKind
Span Span
// Raw is the token as written in the source.
Raw string
// Value is the decoded text of an ident, function name, at-keyword, hash,
// string or url token (escapes resolved), and the character of a delim.
Value string
// Number is the numeric value of a number, percentage or dimension; the
// percentage's value is not divided by 100. Repr is the numeric part as
// written, Integer reports the "integer" type flag, and Unit is a
// dimension's decoded unit.
Number float64
Repr string
Integer bool
Unit string
// ID is the "id" type flag of a hash token: its value is an identifier.
ID bool
// Terminated is false for a string or url token that ran into the end of
// the input; it is true for every other token.
Terminated bool
// First and Last are the code points of a unicode-range token.
First, Last rune
}
Token is one CSS token with the facts its kind carries. Fields that do not apply to the kind are zero.
type Tree ¶
type Tree struct {
// contains filtered or unexported fields
}
Tree is a parsed source: its tokens, its comments and the rules and declarations found in it. It is immutable and safe for concurrent reads. A nil *Tree answers like an empty one.
func ParseBlockContents ¶
func ParseBlockContents(src string, opts ...ParseOption) (*Tree, error)
ParseBlockContents parses src as the contents of a {} block (CSS Syntax 5.5.5): declarations and nested rules interleaved, as in the style attribute and CSS nesting.
func ParseDeclarations ¶
func ParseDeclarations(src string, opts ...ParseOption) (*Tree, error)
ParseDeclarations parses src as a list of declarations (CSS Syntax 5.4.5). At-rules are kept as nodes; anything else that is not a declaration, a qualified rule included, is a NodeInvalid node.
func ParseStylesheet ¶
func ParseStylesheet(src string, opts ...ParseOption) (*Tree, error)
ParseStylesheet parses src as the contents of a stylesheet (CSS Syntax 5.5.1): rules and at-rules, with the tokens CDO and CDC between rules ignored. A rule's block is parsed as block contents, so nested rules and declarations appear as its children in source order.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/css"
)
func main() {
src := "/* theme */ a:hover { color: red !important; }\n@media (min-width: 40em) { p { margin: 0 } }"
tree, err := css.ParseStylesheet(src)
if err != nil {
panic(err)
}
for n := range tree.Nodes() {
fmt.Println(n.Kind(), n.PreludeText(), n.Span())
for c := range n.Children() {
fmt.Printf(" %v %q %q %v\n", c.Kind(), c.Name(), c.ValueText(), c.Important())
}
}
}
Output: qualified-rule a:hover {12 46} declaration "color" "red" true at-rule (min-width: 40em) {47 91} qualified-rule "" "" false
Example (AtRules) ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/css"
)
func main() {
tree, _ := css.ParseStylesheet(`@import url("a.css") layer(base) supports(display: grid) screen; @layer base, theme;`)
for n := range tree.Nodes() {
switch n.AtRuleKind() {
case css.AtImport:
r, _ := n.Import()
fmt.Printf("import %s layer=%s supports=%s media=%s\n", r.URL, r.LayerName, r.Supports, r.Media)
case css.AtLayer:
r, _ := n.Layer()
fmt.Println("layer", r.Names, r.Statement)
}
}
}
Output: import a.css layer=base supports=display: grid media=screen layer [base theme] true
func ParseValues ¶
func ParseValues(src string, opts ...ParseOption) (*Tree, error)
ParseValues tokenizes src and returns the tree whose Tree.Values are its component values (CSS Syntax 5.4.9). It has no nodes. The tree is returned, not the list, because it also holds the tokens and comments of the source (see Tree.Tokens); ParseValue returns the one value it asks for.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/css"
)
func main() {
tree, _ := css.ParseValues("rgb(1 2 3 / 50%) , 10px")
for _, part := range tree.Values().Split() {
for v := range part.Trim().All() {
fmt.Println(v.Kind(), v.Raw())
}
}
fmt.Println(tree.Values())
}
Output: 1 rgb(1 2 3 / 50%) 0 10px rgb(1 2 3 / 50%) , 10px
func (*Tree) Comments ¶
Comments returns the ranges of the comments, in source order. An unclosed comment runs to the end of the source.
func (*Tree) NestingLimitReached ¶
NestingLimitReached reports whether blocks nested deeper than the limit were left unparsed (WithMaxNesting).
func (*Tree) Source ¶
Source returns the text the tree was parsed from. Tokens and comments together cover it exactly, so a tree never loses a byte.
func (*Tree) Tokens ¶
Tokens returns the tokens in source order, whitespace included and comments excluded.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/css"
)
func main() {
tree, _ := css.ParseValues("a /* c */ 12px")
for t := range tree.Tokens() {
fmt.Printf("%v %v %q %q\n", t.Kind, t.Span, t.Value, t.Unit)
}
for c := range tree.Comments() {
fmt.Println("comment", c)
}
}
Output: ident {0 1} "a" "" whitespace {1 2} "" "" whitespace {9 10} "" "" dimension {10 14} "" "px" comment {2 9}
func (*Tree) Values ¶
func (t *Tree) Values() ComponentValues
Values returns the top-level component values of the whole source (CSS Syntax 5.4.9). For a tree of rules these are the tokens as a flat list.