Documentation
¶
Overview ¶
Package simplecss is a port of the Rust crate simplecss 0.2.2, a simple CSS 2.1 parser and selector. usvg parses each style element with StyleSheet.ParseMore, matches each selector against the nodes of the XML tree through the interface Element, and reads each style attribute with DeclarationTokenizer (D8).
This is not a browser-grade CSS parser.
Limitations ¶
- At-rules are not supported. They will be skipped during parsing.
- Property values are not parsed. In CSS like `* { width: 5px }` you will get a `width` property with a `5px` value as a string.
- CDO/CDC comments are not supported.
- Parser is case sensitive. All keywords must be lowercase.
- Unicode escape, like `\26`, is not supported.
Features ¶
- Selector matching support.
- The rules are sorted by specificity.
- `!important` parsing support.
- Has a high-level parsers and low-level, zero-allocation tokenizers.
Upstream logs its warnings with the crate log. The port logs them to the *slog.Logger that WithLogger gives, with the text of upstream, and logs nothing without it (D20). The errors of upstream wrap the sentinel errors okage.ErrCSS..., so that errors.Is finds them (D21).
Example (Select) ¶
This example ports simplecss examples/select.rs. It matches selectors against a tree of roxmltree.
Port: upstream asserts the id of each element that it finds. Its first assertion panics, because of the fault in PrevSiblingElement. The example prints the id of each element instead, so that its output shows the result of upstream.
package main
import (
"fmt"
"github.com/xo/okage/internal/simplecss"
"github.com/xo/okage/roxmltree"
)
// xmlNode is XmlNode in simplecss examples/select.rs. It is an Element on a
// node of roxmltree.
type xmlNode struct {
node roxmltree.Node
}
// selectNode is XmlNode::select in simplecss examples/select.rs. It returns
// the first element in the subtree of n, n included, that matches text.
func (n xmlNode) selectNode(text string) (roxmltree.Node, bool) {
selector, ok := simplecss.ParseSelector(text)
if !ok {
return roxmltree.Node{}, false
}
for node := range n.node.Descendants() {
if node.IsElement() && selector.Matches(xmlNode{node}) {
return node, true
}
}
return roxmltree.Node{}, false
}
// ParentElement is Element::parent_element for XmlNode in simplecss
// examples/select.rs.
func (n xmlNode) ParentElement() (simplecss.Element, bool) {
parent, ok := n.node.ParentElement()
if !ok {
return nil, false
}
return xmlNode{parent}, true
}
// PrevSiblingElement is Element::prev_sibling_element for XmlNode in
// simplecss examples/select.rs.
//
// Port: upstream takes the first element of prev_siblings, and roxmltree
// starts that iterator at the node itself. So the method returns the node
// itself, and :first-child matches no element. The port keeps that fault.
func (n xmlNode) PrevSiblingElement() (simplecss.Element, bool) {
for node := range n.node.PrevSiblings() {
if node.IsElement() {
return xmlNode{node}, true
}
}
return nil, false
}
// HasLocalName is Element::has_local_name for XmlNode in simplecss
// examples/select.rs.
func (n xmlNode) HasLocalName(name string) bool {
return n.node.TagName().Name() == name
}
// AttributeMatches is Element::attribute_matches for XmlNode in simplecss
// examples/select.rs.
func (n xmlNode) AttributeMatches(localName string, operator simplecss.AttributeOperator) bool {
value, ok := n.node.Attribute(roxmltree.ExpandedNameFromStr(localName))
if !ok {
return false
}
return operator.Matches(value)
}
// PseudoClassMatches is Element::pseudo_class_matches for XmlNode in
// simplecss examples/select.rs. The XML is static, so it ignores the other
// pseudo-classes.
func (n xmlNode) PseudoClassMatches(class simplecss.PseudoClass) bool {
if class.Kind == simplecss.PseudoClassFirstChild {
_, ok := n.PrevSiblingElement()
return !ok
}
return false
}
func main() {
doc, err := roxmltree.Parse(`<svg>
<g>
<rect id='rect1' class='round blue'/>
<rect id='rect2' color='red'/>
</g>
</svg>`)
if err != nil {
fmt.Println(err)
return
}
root := xmlNode{doc.RootElement()}
for _, text := range []string{"rect:first-child", "[color=red]", "svg rect", "svg > g > rect", ".blue"} {
node, ok := root.selectNode(text)
if !ok {
fmt.Printf("%s: none\n", text)
continue
}
id, _ := node.Attribute(roxmltree.ExpandedNameFromStr("id"))
fmt.Printf("%s: %s\n", text, id)
}
}
Output: rect:first-child: none [color=red]: rect2 svg rect: rect1 svg > g > rect: rect1 .blue: rect1
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AttributeOperator ¶
type AttributeOperator struct {
Kind AttributeOperatorKind
// Value is the value of Matches, Contains and StartsWith.
Value string
}
AttributeOperator is AttributeOperator in simplecss src/selector.rs. It is an attribute selector operator.
Port: the Rust enum holds a value in each case but Exists, so it becomes a struct with a kind (D27).
func (AttributeOperator) Matches ¶
func (op AttributeOperator) Matches(value string) bool
Matches is AttributeOperator::matches in simplecss src/selector.rs. It checks that value is matching the operator.
type AttributeOperatorKind ¶
type AttributeOperatorKind uint8
AttributeOperatorKind is the case of an AttributeOperator.
const ( // AttributeOperatorExists is AttributeOperator::Exists, `[attr]`. AttributeOperatorExists AttributeOperatorKind = iota // AttributeOperatorMatches is AttributeOperator::Matches, // `[attr=value]`. AttributeOperatorMatches // AttributeOperatorContains is AttributeOperator::Contains, // `[attr~=value]`. AttributeOperatorContains // AttributeOperatorStartsWith is AttributeOperator::StartsWith, // `[attr|=value]`. AttributeOperatorStartsWith )
The cases of the enum AttributeOperator in simplecss src/selector.rs.
func (AttributeOperatorKind) String ¶
func (k AttributeOperatorKind) String() string
String returns the name of the case in upstream.
type Declaration ¶
Declaration is Declaration in simplecss src/lib.rs. It is a declaration.
type DeclarationTokenizer ¶
type DeclarationTokenizer struct {
// contains filtered or unexported fields
}
DeclarationTokenizer is DeclarationTokenizer in simplecss src/lib.rs. It is a declaration tokenizer.
Tokenizer will stop at the first invalid token.
Example ¶
This example ports the doc test of DeclarationTokenizer in simplecss src/lib.rs.
package main
import (
"fmt"
"github.com/xo/okage/internal/simplecss"
)
func main() {
t := simplecss.NewDeclarationTokenizer("background: url(\"img.png\"); color:red !important")
for d := range t.All() {
fmt.Printf("%s: %s important=%v\n", d.Name, d.Value, d.Important)
}
}
Output: background: url("img.png") important=false color: red important=true
func NewDeclarationTokenizer ¶
func NewDeclarationTokenizer(text string) DeclarationTokenizer
NewDeclarationTokenizer is From<&str> for DeclarationTokenizer in simplecss src/lib.rs.
func (DeclarationTokenizer) All ¶
func (t DeclarationTokenizer) All() iter.Seq[Declaration]
All returns an iterator over the remaining declarations, for use with range. It iterates over a copy of t, so it does not change t.
Port: it ports no upstream function. It is the Go form of the Rust Iterator impl of DeclarationTokenizer.
func (*DeclarationTokenizer) Next ¶
func (t *DeclarationTokenizer) Next() (Declaration, bool)
Next is Iterator::next of DeclarationTokenizer in simplecss src/lib.rs. It returns the next declaration, or false at the end.
type Element ¶
type Element interface {
// ParentElement returns a parent element.
ParentElement() (Element, bool)
// PrevSiblingElement returns a previous sibling element.
PrevSiblingElement() (Element, bool)
// HasLocalName checks that the element has a specified local name.
HasLocalName(name string) bool
// AttributeMatches checks that the element has a specified attribute.
AttributeMatches(localName string, operator AttributeOperator) bool
// PseudoClassMatches checks that the element matches a specified
// pseudo-class.
PseudoClassMatches(class PseudoClass) bool
}
Element is the trait Element in simplecss src/selector.rs. It queries an element node metadata.
Port: the Rust trait returns Option<Self>. The Go interface returns an Element and a bool.
type Option ¶
type Option func(*options)
Option is an option of ParseStyleSheet, StyleSheet.ParseMore and ParseSelector. It changes the configuration of one call.
func WithLogger ¶
WithLogger is an option that sets the logger of a parse. The warnings that simplecss logs with log::warn! go to l, with the text of upstream. Without this option, simplecss logs nothing.
type PseudoClass ¶
type PseudoClass struct {
Kind PseudoClassKind
// Lang is the language of PseudoClassLang.
Lang string
}
PseudoClass is PseudoClass in simplecss src/selector.rs. It is a pseudo-class.
Port: only the case Lang of the Rust enum holds a value, so it becomes a struct with a kind (D27).
func (PseudoClass) String ¶
func (c PseudoClass) String() string
String is fmt::Display for PseudoClass in simplecss src/selector.rs.
type PseudoClassKind ¶
type PseudoClassKind uint8
PseudoClassKind is the case of a PseudoClass.
const ( // PseudoClassFirstChild is PseudoClass::FirstChild. PseudoClassFirstChild PseudoClassKind = iota // PseudoClassLink is PseudoClass::Link. PseudoClassLink // PseudoClassVisited is PseudoClass::Visited. PseudoClassVisited // PseudoClassHover is PseudoClass::Hover. PseudoClassHover // PseudoClassActive is PseudoClass::Active. PseudoClassActive // PseudoClassFocus is PseudoClass::Focus. PseudoClassFocus // PseudoClassLang is PseudoClass::Lang. PseudoClassLang )
The cases of the enum PseudoClass in simplecss src/selector.rs.
func (PseudoClassKind) String ¶
func (k PseudoClassKind) String() string
String returns the name of the case in upstream.
type Rule ¶
type Rule struct {
// Selector is a rule selector.
Selector Selector
// Declarations are a rule declarations.
Declarations []Declaration
}
Rule is Rule in simplecss src/lib.rs. It is a rule.
type Selector ¶
type Selector struct {
// contains filtered or unexported fields
}
Selector is Selector in simplecss src/selector.rs. It is a selector.
func ParseSelector ¶
ParseSelector is Selector::parse in simplecss src/selector.rs. It parses a selector from a string.
Will log any errors as a warnings, to the logger that WithLogger gives.
Parsing will be stopped at EOF, `,` or `{`.
func (Selector) Matches ¶
Matches is Selector::matches in simplecss src/selector.rs. It checks that the provided element matches the current selector.
func (Selector) Specificity ¶
Specificity is Selector::specificity in simplecss src/selector.rs. It computes the selector's specificity.
type SelectorToken ¶
type SelectorToken struct {
Kind SelectorTokenKind
// Value is the identifier of TypeSelector, ClassSelector, IdSelector and
// PseudoClass, the name of AttributeSelector, and the language of
// LangPseudoClass.
Value string
// Operator is the operator of AttributeSelector.
Operator AttributeOperator
}
SelectorToken is SelectorToken in simplecss src/selector.rs. It is a selector token.
Port: the cases of the Rust enum hold a string, an attribute operator or nothing, so it becomes a struct with a kind (D27).
type SelectorTokenKind ¶
type SelectorTokenKind uint8
SelectorTokenKind is the case of a SelectorToken.
const ( // SelectorTokenUniversalSelector is SelectorToken::UniversalSelector, // `*`. SelectorTokenUniversalSelector SelectorTokenKind = iota // SelectorTokenTypeSelector is SelectorToken::TypeSelector, `div`. SelectorTokenTypeSelector // SelectorTokenClassSelector is SelectorToken::ClassSelector, `.class`. SelectorTokenClassSelector // SelectorTokenIDSelector is SelectorToken::IdSelector, `#id`. SelectorTokenIDSelector // SelectorTokenAttributeSelector is SelectorToken::AttributeSelector, // `[color=red]`. SelectorTokenAttributeSelector // SelectorTokenPseudoClass is SelectorToken::PseudoClass, // `:first-child`. SelectorTokenPseudoClass // SelectorTokenLangPseudoClass is SelectorToken::LangPseudoClass, // `:lang(en)`. SelectorTokenLangPseudoClass // SelectorTokenDescendantCombinator is // SelectorToken::DescendantCombinator, `a b`. SelectorTokenDescendantCombinator // SelectorTokenChildCombinator is SelectorToken::ChildCombinator, // `a > b`. SelectorTokenChildCombinator // SelectorTokenAdjacentCombinator is SelectorToken::AdjacentCombinator, // `a + b`. SelectorTokenAdjacentCombinator )
The cases of the enum SelectorToken in simplecss src/selector.rs.
func (SelectorTokenKind) String ¶
func (k SelectorTokenKind) String() string
String returns the name of the case in upstream.
type SelectorTokenizer ¶
type SelectorTokenizer struct {
// contains filtered or unexported fields
}
SelectorTokenizer is SelectorTokenizer in simplecss src/selector.rs. It is a selector tokenizer.
Example ¶
This example ports the doc test of SelectorTokenizer in simplecss src/selector.rs.
package main
import (
"fmt"
"github.com/xo/okage/internal/simplecss"
)
func main() {
t := simplecss.NewSelectorTokenizer("div > p:first-child")
for tok, err := range t.All() {
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%v(%q)\n", tok.Kind, tok.Value)
}
}
Output: TypeSelector("div") ChildCombinator("") TypeSelector("p") PseudoClass("first-child")
func NewSelectorTokenizer ¶
func NewSelectorTokenizer(text string) SelectorTokenizer
NewSelectorTokenizer is From<&str> for SelectorTokenizer in simplecss src/selector.rs.
func (SelectorTokenizer) All ¶
func (t SelectorTokenizer) All() iter.Seq2[SelectorToken, error]
All returns an iterator over the remaining tokens and their errors, for use with range. It iterates over a copy of t, so it does not change t.
Port: it ports no upstream function. It is the Go form of the Rust Iterator impl of SelectorTokenizer. An error is the item that upstream returns as Some(Err(e)), and it comes with a zero token.
func (*SelectorTokenizer) Next ¶
func (t *SelectorTokenizer) Next() (SelectorToken, bool, error)
Next is Iterator::next of SelectorTokenizer in simplecss src/selector.rs.
Upstream returns Option<Result<SelectorToken, Error>>. Next returns the token and true for Some(Ok(token)), a non-nil error for Some(Err(e)), and false with a nil error for None, at the end.
type StyleSheet ¶
type StyleSheet struct {
// Rules is a list of rules.
Rules []Rule
}
StyleSheet is StyleSheet in simplecss src/lib.rs. It is a style sheet.
The zero value is an empty style sheet, as Default for StyleSheet gives.
func NewStyleSheet ¶
func NewStyleSheet() StyleSheet
NewStyleSheet is StyleSheet::new in simplecss src/lib.rs. It creates an empty style sheet.
func ParseStyleSheet ¶
func ParseStyleSheet(text string, opts ...Option) StyleSheet
ParseStyleSheet is StyleSheet::parse in simplecss src/lib.rs. It parses a style sheet from text.
At-rules are not supported and will be skipped.
Doesn't produce any errors. In worst case scenario will return an empty stylesheet.
All warnings will be logged, to the logger that WithLogger gives.
Example ¶
This example parses a style sheet. The rules come out sorted by specificity.
package main
import (
"fmt"
"github.com/xo/okage/internal/simplecss"
)
func main() {
style := simplecss.ParseStyleSheet("#a { fill:red } rect, .b { stroke:blue !important } @media print { g {} }")
fmt.Println(style)
}
Output: rect { stroke:blue !important; } *[class~='b'] { stroke:blue !important; } *[id='a'] { fill:red; }
func (*StyleSheet) ParseMore ¶
func (ss *StyleSheet) ParseMore(text string, opts ...Option)
ParseMore is StyleSheet::parse_more in simplecss src/lib.rs. It parses a style sheet from a text to the current style sheet.
All warnings will be logged, to the logger that WithLogger gives.
func (StyleSheet) String ¶
func (ss StyleSheet) String() string
String is fmt::Display for StyleSheet in simplecss src/lib.rs.
type TextPos ¶
TextPos is TextPos in simplecss src/lib.rs. It is a position in text.
Position indicates a row/line and a column in the original text. Starting from 1:1.
func NewTextPos ¶
NewTextPos is TextPos::new in simplecss src/lib.rs. It constructs a new TextPos.
Should not be invoked manually, but rather via Stream::gen_text_pos.