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 onElementState, 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-spacingandtext-align, with their shorthands. SeeLonghandIdandShorthandIdfor the full list. - Values:
px,em,rem,ptand the other absolute units, percentages, every CSS colour syntax up tooklch()andcolor(display-p3 ...),!important, and theinherit,initialandunsetkeywords.
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); // currentcolorModules§
- 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. - Computed
Style - 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. - Declaration
Block - The
{ ... }part of a rule, or an inline style. - Element
State - The interactive state of an element, matched by pseudo-classes.
- Error
- Something in a stylesheet, declaration block or selector could not be parsed.
- Font
Family - A prioritised list of font family names.
- Font
Weight - A font weight from 1 to 1000, where 400 is normal and 700 is bold.
- Opaque
Element - Opaque representation of an Element, for identity comparisons.
- Selector
- One parsed selector, such as
button.primary:hover. - Selector
Impl - The type-level configuration handed to the
selectorscrate: which string types, pseudo-classes and pseudo-elements selectors are made of. - Selector
List - A comma-separated list of selectors, the prelude of a style rule.
- Sides
- One value per side of a box, in the CSS order.
- Style
Rule - 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§
- Border
Style - How a border is drawn.
- CssWide
Keyword - The keywords every property accepts in place of a value.
- Error
Kind - What went wrong.
- Font
Style - Length
Percentage - A length in pixels, or a percentage of something layout knows about.
- Length
Percentage OrAuto width,height,min-width,min-heightand the margins.- Length
Percentage OrNone max-widthandmax-height.- Line
Height line-height.- Longhand
Id - Every longhand property. Shorthands expand to these when parsed, so the cascade only ever deals with longhands.
- Property
Declaration - A parsed declaration: one longhand and its specified value.
- Property
Id - Any property name this crate accepts.
- Pseudo
Class - A pseudo-class answered by
Element::stateorElement::has_custom_staterather than by the shape of the tree. - Pseudo
Element - There are no pseudo-elements. This type has no values; it exists because
the
selectorscrate needs one. - Shorthand
Id - A shorthand property: a single declaration that sets several longhands.
- Text
Align
Traits§
- Element
- A handle to a node in the toolkit’s widget tree.
Functions§
- opaque_
element_ from_ index - An
OpaqueElementfor an element stored atindexin an arena.