Skip to main content

Crate eternal_styler

Crate eternal_styler 

Source
Expand description

A small CSS engine for UI toolkits.

Give it stylesheets and a tree of widgets; get back a ComputedStyle for each widget with its dimensions, spacing, colours, borders and typography resolved.

The selector matching and CSS parsing come from Servo: the selectors and cssparser crates that Stylo, the style system in Firefox and Servo, is built on. Everything above that (the property set, the cascade, computed values) is this crate’s own, and it is deliberately small: it covers what a toolkit needs to style widgets and nothing a web page would.

§What is supported

  • Selectors: types, classes, ids, attributes, the descendant, child and sibling combinators, :not(), :is(), :where(), :has(), :root, :empty, the :nth-* family and the other tree-structural pseudo-classes, the interactive pseudo-classes listed on ElementState, and :state(name) for a toolkit’s own states.
  • Properties: width, height, min-*, max-*, margin, padding, gap, color, background-color, opacity, the border width, style, colour and radius properties, font-family, font-size, font-weight, font-style, line-height, letter-spacing and text-align, with their shorthands. See LonghandId and ShorthandId for the full list.
  • Values: px, em, rem, pt and the other absolute units, percentages, every CSS colour syntax up to oklch() and color(display-p3 ...), !important, and the inherit, initial and unset keywords.

Not supported: at-rules (@media, @import, …), nesting, pseudo-elements, calc(), custom properties, transitions, and every layout property. Layout is the toolkit’s job; this crate only hands it numbers.

§Example

A toolkit implements Element for a handle to its nodes, parses its stylesheets, and asks a Styler for each node’s style, top-down so that each parent’s style is available for its children.

use eternal_styler::{Element, ElementState, OpaqueElement, Styler, Stylesheet, Color};
use eternal_styler::LengthPercentage;

// A minimal widget tree: an arena of nodes.
#[derive(Debug)]
struct Node { name: &'static str, class: Option<&'static str>, hovered: bool, parent: Option<usize>, children: Vec<usize> }
#[derive(Debug)]
struct Tree(Vec<Node>);

#[derive(Clone, Debug)]
struct Handle<'a> { tree: &'a Tree, index: usize }

impl<'a> Handle<'a> {
    fn node(&self) -> &'a Node { &self.tree.0[self.index] }
    fn at(&self, index: usize) -> Self { Handle { tree: self.tree, index } }
}

impl Element for Handle<'_> {
    fn opaque(&self) -> OpaqueElement { OpaqueElement::new(self.node()) }
    fn parent(&self) -> Option<Self> { self.node().parent.map(|i| self.at(i)) }
    fn first_child(&self) -> Option<Self> { self.node().children.first().map(|&i| self.at(i)) }
    fn prev_sibling(&self) -> Option<Self> { None } // a real toolkit would look these up
    fn next_sibling(&self) -> Option<Self> { None }
    fn local_name(&self) -> &str { self.node().name }
    fn classes(&self) -> impl Iterator<Item = &str> { self.node().class.into_iter() }
    fn state(&self) -> ElementState {
        if self.node().hovered { ElementState::HOVER } else { ElementState::empty() }
    }
}

let tree = Tree(vec![
    Node { name: "panel", class: None, hovered: false, parent: None, children: vec![1] },
    Node { name: "button", class: Some("primary"), hovered: true, parent: Some(0), children: vec![] },
]);

let mut styler = Styler::new();
styler.add_stylesheet(Stylesheet::parse(r#"
    panel { font-size: 20px; color: #333; }
    button { padding: 0.5em 1em; border: 1px solid; }
    button.primary:hover { background-color: #06f; color: white; }
"#)?);

let panel = Handle { tree: &tree, index: 0 };
let panel_style = styler.compute(&panel, None);
let button_style = styler.compute(&panel.at(1), Some(&panel_style));

assert_eq!(button_style.font_size, 20.0);                       // inherited
assert_eq!(button_style.padding.left, LengthPercentage::Px(20.0)); // 1em of 20px
assert_eq!(button_style.background_color, Color::from_packed_rgba(0x0066ffff));
assert_eq!(button_style.border_color.top, Color::WHITE);        // currentcolor

Modules§

specified
Values as written in a stylesheet, before the cascade resolves them.

Structs§

Atom
A cheaply cloneable string with a precomputed hash.
Color
A colour as gamma-encoded sRGB with straight (not premultiplied) alpha, each component in 0.0..=1.0.
ComputedStyle
Every property’s value for one element, after the cascade, inheritance and unit resolution.
Corners
One value per corner of a box, in the CSS order.
Declaration
One longhand declaration and whether it was marked !important.
DeclarationBlock
The { ... } part of a rule, or an inline style.
ElementState
The interactive state of an element, matched by pseudo-classes.
Error
Something in a stylesheet, declaration block or selector could not be parsed.
FontFamily
A prioritised list of font family names.
FontWeight
A font weight from 1 to 1000, where 400 is normal and 700 is bold.
OpaqueElement
Opaque representation of an Element, for identity comparisons.
Selector
One parsed selector, such as button.primary:hover.
SelectorImpl
The type-level configuration handed to the selectors crate: which string types, pseudo-classes and pseudo-elements selectors are made of.
SelectorList
A comma-separated list of selectors, the prelude of a style rule.
Sides
One value per side of a box, in the CSS order.
StyleRule
A selector list and the declarations that apply to what it matches.
Styler
Holds stylesheets and computes styles for elements against them.
Stylesheet
A list of style rules in source order.

Enums§

BorderStyle
How a border is drawn.
CssWideKeyword
The keywords every property accepts in place of a value.
ErrorKind
What went wrong.
FontStyle
LengthPercentage
A length in pixels, or a percentage of something layout knows about.
LengthPercentageOrAuto
width, height, min-width, min-height and the margins.
LengthPercentageOrNone
max-width and max-height.
LineHeight
line-height.
LonghandId
Every longhand property. Shorthands expand to these when parsed, so the cascade only ever deals with longhands.
PropertyDeclaration
A parsed declaration: one longhand and its specified value.
PropertyId
Any property name this crate accepts.
PseudoClass
A pseudo-class answered by Element::state or Element::has_custom_state rather than by the shape of the tree.
PseudoElement
There are no pseudo-elements. This type has no values; it exists because the selectors crate needs one.
ShorthandId
A shorthand property: a single declaration that sets several longhands.
TextAlign

Traits§

Element
A handle to a node in the toolkit’s widget tree.

Functions§

opaque_element_from_index
An OpaqueElement for an element stored at index in an arena.