Donner SVG main
0.8.0 ยท 766e862a0.8.0 main
SVG editor and embeddable C⁠+⁠+⁠20 engine.
Loading...
Searching...
No Matches
donner::css Namespace Reference

Donner CSS library, a standalone composable CSS parser. More...

Namespaces

namespace  parser
 Parsers for various CSS data types, such as the top-level StylesheetParser and SelectorParser, as well as internal details such as ColorParser.

Classes

struct  RGBA
 Represents as 32-bit RGBA color, with each component in the range [0, 255]. More...
struct  HSLA
 Represents an HSLA color. More...
struct  Color
 Represents a CSS color value, like a RGBA color from a #rrggbb or #rgb hex value, or the currentcolor keyword. More...
struct  Function
 A CSS function, such as rgb(255, 0, 0), parsed into a function name and a list of parameter values. More...
struct  SimpleBlock
 A CSS simple block, such as a rule block or a parenthesized expression. More...
struct  ComponentValue
 A CSS component value, which is either a token, or a parsed function or block. More...
class  CSS
 Public API for parsing CSS. More...
struct  Declaration
 A declaration is a CSS name/value pair, such as color: red;. More...
struct  DeclarationOrAtRule
 Return value of parsers that may return either a declaration or an AtRule, specifically donner::css::parser::DeclarationListParser::Parse. More...
struct  StyleDeclarationEofClosure
 The source edit that makes an implicitly closed declaration safe to extend. More...
struct  AnbValue
 An+B microsyntax value, which is parsed by parser::AnbMicrosyntaxParser. More...
struct  FontFaceSource
 A single entry listed in src:-either a local face, a URL, or inline data. More...
struct  FontFace
 In-memory representation of a single @font-face rule. More...
struct  AtRule
 Rules starting with an @ are called At-Rules, and are used to define CSS features such as @media, @font-face, @keyframes, etc. More...
struct  QualifiedRule
 A QualifiedRule has a list of component values and a block, this is the intermediate representation of a stylesheet rule. More...
struct  InvalidRule
 InvalidRule is used to represent a rule which could not be parsed, such as an invalid at-rule. More...
struct  Rule
 Holds a CSS rule which can either be a standard QualifiedRule, an AtRule, or an InvalidRule if there was a parse error. More...
struct  Selector
 A top-level Selector, which is a list of ComplexSelector. More...
struct  AttributeSelector
 Selectors which match against element attributes, such as a[href^="https://"] or h1[title]. More...
struct  ClassSelector
 Selector which match the element's class attribute, for example .foo matches an element with class foo. More...
struct  SelectorMatchResult
 Returned by Selector::matches to indicate whether the selector matched, and if so, the specificity of the match. More...
struct  ComplexSelector
 A complex selector is a sequence of one or more compound selectors, separated by combinators. More...
struct  CompoundSelector
 A compound selector is a sequence of simple selectors, which represents a set of conditions that are combined to match a single element. More...
struct  IdSelector
 Selector which match the element's id attribute, for example #foo matches an element with an id="foo" attribute. More...
struct  PseudoClassSelector
 Selectors which start with one colon, e.g. More...
struct  PseudoElementSelector
 Selectors which start with two colons are called pseudo-elements, e.g. More...
class  SelectorTraversalBudget
 Aggregate bound on selector work: element visits and bounded chunks of text inspection. More...
class  SelectorTraversalNavigation
 Navigation that charges both visible elements and adapter-specific skipped nodes. More...
struct  SelectorMatchOptions
 Options for matching a selector against an element. More...
struct  TypeSelector
 Selector which matches the element type, e.g. More...
class  Specificity
 A CSS specificity value (id, class, type), as defined in https://www.w3.org/TR/selectors-4/#specificity-rules, which is used during cascading to determine which style takes precedence. More...
struct  LayerNode
 A layer name segment, scoped to its parent in the same sheet. More...
struct  LayerEvent
 Source-order layer declarations and retained import positions. More...
struct  StylesheetLayers
 Immutable sheet-local layer syntax, allocated only for a sheet that uses layers. More...
struct  EditedRuleWindow
 Qualified rule indices replaced by a verified text splice. The two counts refer to the previous and updated stylesheet respectively; unaffected suffix rules may shift. More...
struct  SelectorRule
 A rule in a stylesheet, which consists of a selector and a list of declarations. More...
struct  ImportRule
 An unconditional @import rule retained by the stylesheet parser, such as @import url("theme.css");. More...
class  Stylesheet
 A CSS stylesheet, which is a list of rules. More...
struct  Token
 A CSS token, which are created as a first step when parsing a CSS string. More...
struct  VariableDefinition
 One winning local custom declaration. A missing value represents the initial, guaranteed-invalid value and masks an inherited value of the same name. Declarations that inherit unchanged can be omitted; the lookup supplies their already computed parent value. More...
struct  VariableOutputs
 The caller owns the canonical computed sequences. Publishing one result before evaluating its dependents permits retained-byte admission at allocation time, without keeping a second uncharged copy of every expanded value. More...
struct  VariableSubstitutionLimits
 Per-value limits in addition to any enclosing cascade work limits. More...
struct  VariableSubstitutionResult
struct  WqName
 A CSS qualified name, which is a name optionally associated with a namespace. More...

Typedefs

using LayerId = std::uint16_t
 One layer segment in the sheet's local layer tree.
using TokenIndex = size_t
 Type of the token unique identifier, which is returned by Token::tokenIndex() and Token::indexOf<T>().
using VariableLookup
 A lookup returns an already computed token sequence. Its storage must outlive substitution. An engaged empty span is a valid empty value; a missing name is guaranteed-invalid.

Enumerations

enum class  FontFaceDescriptor {
  Unknown ,
  Family ,
  Source ,
  Weight ,
  Width ,
  Style
}
 Descriptors supported by Donner's @font-face parser.
enum class  AttrMatcher {
  Includes ,
  DashMatch ,
  PrefixMatch ,
  SuffixMatch ,
  SubstringMatch ,
  Eq
}
 For attribute selectors, different match modes are available, which are specified by this enum. More...
enum class  Combinator {
  Descendant ,
  Child ,
  NextSibling ,
  SubsequentSibling ,
  Column
}
 Between two compound selectors, there can be a combinator, which specifies how the two elements are associated in the tree. More...
enum class  NumberType {
  Integer ,
  Number
}
 Indicates if a number is an integer or a floating point number, used for number-containing tokens such as Token::Number and Token::Dimension. More...
enum class  VariableReferences {
  None ,
  Valid ,
  Invalid
}
 Classification of variable references, including references nested in functions and blocks.
enum class  VariableSubstitutionStatus {
  Resolved ,
  Invalid ,
  LimitExceeded
}
 A rejected expansion has no partially substituted output.

Functions

constexpr Color RgbHex (uint32_t value)
 Construct a donner::css::Color from a 24-bit RGB hex literal.
constexpr Color RgbaHex (uint32_t value)
 Construct a donner::css::Color from a 32-bit RGBA hex literal.
StyleDeclarationEofClosure closeStyleDeclarationAtEof (const Declaration &declaration, std::string_view spelling)
 Finish the trailing constructs recovered at EOF before adding another declaration.
std::string mergeStyleDeclarations (std::span< const Declaration > existing, std::span< const Declaration > updates, std::span< const std::string_view > existingSpellings={}, std::span< const std::string_view > updateSpellings={})
 Merge two sets of CSS declarations, where updates override declarations in existing that have the same property name (case-insensitive).
FontFaceDescriptor IdentifyFontFaceDescriptor (std::string_view name)
 Look up an ASCII case-insensitive descriptor, including the font-stretch alias for font-width.
std::string FontFaceIdentityKey (const FontFace &face)
 Build a string that identifies an @font-face declaration.
std::ostream & operator<< (std::ostream &os, AttrMatcher matcher)
 Ostream output operator.
std::ostream & operator<< (std::ostream &os, Combinator combinator)
 Ostream output operator.
std::string SerializeIdentifier (std::string_view value)
 Serialize value as a CSS identifier, per CSSOM "serialize an identifier", so that it reads back as exactly value in selector or keyword position.
std::string SerializeStringContents (std::string_view value, char quote)
 Serialize value as the contents of a CSS string delimited by quote, per CSSOM "serialize a string" but without the surrounding quotes: the quote character, backslash and control characters are escaped.
std::string SerializeUrlTokenValue (std::string_view value)
 Serialize value as the value of an unquoted url(...) token, escaping every character that would end the token or make it a bad url (whitespace, quotes, parentheses, backslash, control characters).
bool ResolveVariableDefinitions (std::span< const VariableDefinition > local, const VariableLookup &inherited, const VariableOutputs &outputs, VariableSubstitutionLimits limits={}, const std::function< bool(std::size_t, std::size_t)> &admit={})
 Compute local values in selected dependency order. Each name occurs once, and all definition spans must stay alive throughout the call. The caller keeps already published and inherited values stable while an individual value is computed. Cycles invalidate exactly their participants; unused fallbacks create no dependency, while a selected fallback can. A dependent can use a fallback after a referenced cycle becomes guaranteed-invalid.
VariableReferences InspectVariableReferences (std::span< const ComponentValue > values)
 Inspect the token tree without substituting or looking up any name.
bool VisitVariableReferences (std::span< const ComponentValue > values, const std::function< void(std::string_view)> &visit)
 Visit every referenced custom property, including those in unused fallbacks, in token order. Returns false when a var() argument list is invalid.
VariableSubstitutionResult SubstituteVariables (std::span< const ComponentValue > values, const VariableLookup &lookup, VariableSubstitutionLimits limits={}, const std::function< bool(std::size_t, std::size_t)> &admit={})
 Substitute already computed variables and selected fallback token sequences. Token boundaries, nesting, and source locations are preserved. The optional callback admits actual output work (component count, source bytes) before each append, and may decline further work.

Variables

constexpr LayerId kUnlayered = std::numeric_limits<LayerId>::max()
 The implicit sheet root and layer identity of unlayered rules.

Detailed Description

Donner CSS library, a standalone composable CSS parser.

This library is designed to be used in other projects, and provides building blocks to add CSS parsing to any application. This is used by Donner itself to parse SVG stylesheets, but it can be used for HTML-based CSS as well.

This library includes support for parsing rules and declarations, as well as matching selectors against a DOM tree.

To get started, parse a Stylesheet using CSS::ParseStylesheet, and then use the returned Stylesheet object to match against a DOM tree:

auto stylesheet = CSS::ParseStylesheet("svg { fill: red; }", warnings);
for (const css::SelectorRule& rule : stylesheet.rules()) {
if (css::SelectorMatchResult match = rule.selector.matches(domNode)) {
applyDeclaration(rule.declarations, match.specificity);
}
}
Collects parse warnings during parsing.
Definition ParseWarningSink.h:30
static Stylesheet ParseStylesheet(std::string_view str, ParseWarningSink &warningSink)
Parse a CSS stylesheet into a list of selectors and their associated declarations,...
Returned by Selector::matches to indicate whether the selector matched, and if so,...
Definition ComplexSelector.h:32
A rule in a stylesheet, which consists of a selector and a list of declarations.
Definition Stylesheet.h:68

Class Documentation

◆ donner::css::StyleDeclarationEofClosure

struct donner::css::StyleDeclarationEofClosure

The source edit that makes an implicitly closed declaration safe to extend.

Class Members
bool removeTrailingEscape = false Drop a reverse solidus ignored at string EOF.
string suffix Explicit closers in innermost-to-outermost order.

◆ donner::css::SelectorMatchOptions

struct donner::css::SelectorMatchOptions
template<ElementLike T>
struct donner::css::SelectorMatchOptions< T >

Options for matching a selector against an element.

This is used to pass additional information to the matching algorithm, such as the element to match against for relative queries.

Template Parameters
TA type that fulfills the ElementLike concept, matching the Selector::matches method.
Class Members
bool allowScopeOnlyMatch = false Permit scope-only ancestor and filter matching.
const T * relativeToElement Enables relative querying and uses this element as the reference point. For example, > div will match div that is a child of relativeToElement.
const T * scopeElement = nullptr Element to match against :scope queries. Cannot be matched directly, but can be used for relative matching.
SelectorTraversalBudget * traversalBudget = nullptr Shared selector-work budget.

◆ donner::css::LayerNode

struct donner::css::LayerNode

A layer name segment, scoped to its parent in the same sheet.

Class Members
RcString name Exact decoded identifier. Empty denotes a new anonymous layer.
LayerId parent Sheet-local parent, or the implicit root.

◆ donner::css::StylesheetLayers

struct donner::css::StylesheetLayers

Immutable sheet-local layer syntax, allocated only for a sheet that uses layers.

Class Members
vector< LayerEvent > events
vector< LayerId > fontFaceLayers Sheet-local layer of each font face, populated only when a face is layered.
vector< LayerNode > nodes

◆ donner::css::EditedRuleWindow

struct donner::css::EditedRuleWindow

Qualified rule indices replaced by a verified text splice. The two counts refer to the previous and updated stylesheet respectively; unaffected suffix rules may shift.

Class Members
size_t newBegin
size_t newCount
size_t oldBegin
size_t oldCount

◆ donner::css::ImportRule

struct donner::css::ImportRule

An unconditional @import rule retained by the stylesheet parser, such as @import url("theme.css");.

Only imports that apply unconditionally are retained. Imports with supports() or media conditions other than all, and imports that appear after another rule, are diagnosed and dropped by the parser. The parser never resolves or fetches the URL; loading is the responsibility of the document that owns the stylesheet.

Class Members
LayerId layer = kUnlayered Optional named or anonymous import layer.
FileOffset sourceOffset = FileOffset::EndOfString() Source position of the @ token in the local CSS source.
RcString url URL of the imported stylesheet, exactly as authored (unresolved).

◆ donner::css::VariableDefinition

struct donner::css::VariableDefinition

One winning local custom declaration. A missing value represents the initial, guaranteed-invalid value and masks an inherited value of the same name. Declarations that inherit unchanged can be omitted; the lookup supplies their already computed parent value.

Class Members
string_view name
optional< span< const ComponentValue > > value

◆ donner::css::VariableOutputs

struct donner::css::VariableOutputs

The caller owns the canonical computed sequences. Publishing one result before evaluating its dependents permits retained-byte admission at allocation time, without keeping a second uncharged copy of every expanded value.

Class Members
function< optional< span< const ComponentValue > >(size_t)> lookup Read a previously published local result by its definition index.
function< bool(size_t, VariableSubstitutionResult)> publish Store one result by definition index. Return false on refusal.

◆ donner::css::VariableSubstitutionLimits

struct donner::css::VariableSubstitutionLimits

Per-value limits in addition to any enclosing cascade work limits.

Class Members
size_t bytes = 1024 * 1024
size_t components = 65'536

◆ donner::css::VariableSubstitutionResult

struct donner::css::VariableSubstitutionResult
Class Members
VariableSubstitutionStatus status
vector< ComponentValue > values

Typedef Documentation

◆ VariableLookup

Initial value:
std::function<std::optional<std::span<const ComponentValue>>(std::string_view)>

A lookup returns an already computed token sequence. Its storage must outlive substitution. An engaged empty span is a valid empty value; a missing name is guaranteed-invalid.

Enumeration Type Documentation

◆ AttrMatcher

enum class donner::css::AttrMatcher
strong

For attribute selectors, different match modes are available, which are specified by this enum.

See https://www.w3.org/TR/selectors-4/#attribute-selectors for the full definition.

These are used within square brackets on the selector list, such as a[href^="https://"] or h1[title], and AttrMatcher represents the separator between the attribute name and string, such as ^= or =.

Enumerator
Includes 

"~=", matches if the attribute value is a whitespace-separated list of values, and one of them exactly matches the matcher value.

DashMatch 

"|=", matches if the attribute value either exactly matches, or begins with the value immediately followed by a dash ("-").

PrefixMatch 

"^=", matches if the attribute value begins with the matcher value.

SuffixMatch 

"$=", matches if the attribute value ends with the matcher value.

SubstringMatch 

"*=", matches if the attribute value contains the matcher value.

Eq 

"=", matches if the attribute value exactly matches the matcher value.

◆ Combinator

enum class donner::css::Combinator
strong

Between two compound selectors, there can be a combinator, which specifies how the two elements are associated in the tree.

By default, a space between compound selectors is a descendant combinator, e.g. div span is a Combinator::Descendant combinator, while div > span is a Combinator::Child combinator.

Enumerator
Descendant 

Space-separated, finds descendants in the tree.

Child 

'>', finds direct children in the tree.

NextSibling 

'+', finds the next sibling in the tree.

SubsequentSibling 

'~', finds all subsequent siblings in the tree.

Column 

'||', finds the next column in the tree. Note that this is a new feature in CSS Selectors Level 4, but isn't applicable to SVG.

◆ NumberType

enum class donner::css::NumberType
strong

Indicates if a number is an integer or a floating point number, used for number-containing tokens such as Token::Number and Token::Dimension.

Enumerator
Integer 

Integer number (no decimal point).

Number 

Floating point number.

Function Documentation

◆ closeStyleDeclarationAtEof()

StyleDeclarationEofClosure donner::css::closeStyleDeclarationAtEof ( const Declaration & declaration,
std::string_view spelling )

Finish the trailing constructs recovered at EOF before adding another declaration.

Parameters
declarationParsed declaration whose trailing constructs were recovered.
spellingAuthored declaration text through EOF, starting at its source offset.
Returns
The minimal trailing edit, empty when no recovery is needed.

◆ FontFaceIdentityKey()

std::string donner::css::FontFaceIdentityKey ( const FontFace & face)

Build a string that identifies an @font-face declaration.

Two declarations produce the same key exactly when they would select the same face and resolve to the same bytes: the matching descriptors (family, compared case-insensitively, plus normalized weight range, style, and normalized width range) together with the ordered source list, including each source's kind, trust, format and technology hints, and payload identity. Inline data payloads are immutable and shared by pointer, so the pointer value identifies the bytes as long as something holds a reference to them; the key is only meaningful while its holder keeps that reference alive.

Weight endpoints use their normalized values, so a scalar and the equivalent single-point range share an identity. Width keywords and equivalent percentage ranges also share an identity. Every variable-length field is length-prefixed, so a separator character appearing inside a family name, hint, or URL cannot make two different declarations produce one key.

The intended use is deduplication: callers that re-announce a document's @font-face set (a style recompute does this on every pass) key on this so an unchanged declaration keeps whatever identity and cached state it already had.

Parameters
faceThe declaration to identify.

◆ mergeStyleDeclarations()

std::string donner::css::mergeStyleDeclarations ( std::span< const Declaration > existing,
std::span< const Declaration > updates,
std::span< const std::string_view > existingSpellings = {},
std::span< const std::string_view > updateSpellings = {} )

Merge two sets of CSS declarations, where updates override declarations in existing that have the same property name (case-insensitive).

Unrelated existing declarations are preserved. Duplicate property names within updates are deduplicated, keeping the last occurrence.

Parameters
existingExisting declarations.
updatesUpdated declarations to apply.
existingSpellingsOptional original text, in the same order as existing.
updateSpellingsOptional original text, in the same order as updates.
Returns
Merged style string with declarations separated by "; ".

◆ operator<<()

std::ostream & donner::css::operator<< ( std::ostream & os,
Combinator combinator )
inline

Ostream output operator.

Outputs the combinator character, e.g. ' ', '>', '+', '~' or '||'.

Parameters
osThe output stream.
combinatorThe combinator.

◆ ResolveVariableDefinitions()

bool donner::css::ResolveVariableDefinitions ( std::span< const VariableDefinition > local,
const VariableLookup & inherited,
const VariableOutputs & outputs,
VariableSubstitutionLimits limits = {},
const std::function< bool(std::size_t, std::size_t)> & admit = {} )

Compute local values in selected dependency order. Each name occurs once, and all definition spans must stay alive throughout the call. The caller keeps already published and inherited values stable while an individual value is computed. Cycles invalidate exactly their participants; unused fallbacks create no dependency, while a selected fallback can. A dependent can use a fallback after a referenced cycle becomes guaranteed-invalid.

Returns false on an invalid definition list, bounded graph-work exhaustion, aggregate admission refusal, or output refusal. No result is published after a refusal; the caller discards any earlier staged results. An invalid individual value, including one that exceeds a per-value limit, is published as such. Admission covers expanded values and each newly marked cycle participant. Cycle marking charges work without charging output bytes.

◆ RgbaHex()

Color donner::css::RgbaHex ( uint32_t value)
constexpr

Construct a donner::css::Color from a 32-bit RGBA hex literal.

For example, for 50% opacity red:

const Color red = RgbaHex(0xFF000080);
constexpr Color RgbaHex(uint32_t value)
Construct a donner::css::Color from a 32-bit RGBA hex literal.
Definition Color.h:256
Represents a CSS color value, like a RGBA color from a #rrggbb or #rgb hex value, or the currentcolor...
Definition Color.h:113
Parameters
valueInteger representation of the color value (0xRRGGBBAA).

◆ RgbHex()

Color donner::css::RgbHex ( uint32_t value)
constexpr

Construct a donner::css::Color from a 24-bit RGB hex literal.

For example:

const Color red = RgbHex(0xFF0000);
constexpr Color RgbHex(uint32_t value)
Construct a donner::css::Color from a 24-bit RGB hex literal.
Definition Color.h:242
Parameters
valueInteger representation of the color value (0xRRGGBB).

◆ SerializeIdentifier()

std::string donner::css::SerializeIdentifier ( std::string_view value)

Serialize value as a CSS identifier, per CSSOM "serialize an identifier", so that it reads back as exactly value in selector or keyword position.

For example a.b becomes a\.b and 1a becomes \31 a. Bytes 0x80 and above are copied unchanged, so UTF-8 input stays UTF-8.

Parameters
valueIdentifier text, without any # or . prefix.
Returns
Escaped identifier.

◆ SerializeStringContents()

std::string donner::css::SerializeStringContents ( std::string_view value,
char quote )

Serialize value as the contents of a CSS string delimited by quote, per CSSOM "serialize a string" but without the surrounding quotes: the quote character, backslash and control characters are escaped.

Parameters
valueString contents.
quoteDelimiter of the enclosing string, " or '.
Returns
Escaped contents.

◆ SerializeUrlTokenValue()

std::string donner::css::SerializeUrlTokenValue ( std::string_view value)

Serialize value as the value of an unquoted url(...) token, escaping every character that would end the token or make it a bad url (whitespace, quotes, parentheses, backslash, control characters).

Parameters
valueUrl text.
Returns
Escaped url token value.