eternal_styler/lib.rs
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! A small CSS engine for UI toolkits.
6//!
7//! Give it stylesheets and a tree of widgets; get back a
8//! [`ComputedStyle`] for each widget with its dimensions, spacing, colours,
9//! borders and typography resolved.
10//!
11//! The selector matching and CSS parsing come from Servo: the
12//! [`selectors`](https://crates.io/crates/selectors) and
13//! [`cssparser`](https://crates.io/crates/cssparser) crates that Stylo, the
14//! style system in Firefox and Servo, is built on. Everything above that
15//! (the property set, the cascade, computed values) is this crate's own, and
16//! it is deliberately small: it covers what a toolkit needs to style widgets
17//! and nothing a web page would.
18//!
19//! # What is supported
20//!
21//! - **Selectors**: types, classes, ids, attributes, the descendant, child
22//! and sibling combinators, `:not()`, `:is()`, `:where()`, `:has()`,
23//! `:root`, `:empty`, the `:nth-*` family and the other tree-structural
24//! pseudo-classes, the interactive pseudo-classes listed on
25//! [`ElementState`], and `:state(name)` for a toolkit's own states.
26//! - **Properties**: `width`, `height`, `min-*`, `max-*`, `margin`,
27//! `padding`, `gap`, `color`, `background-color`, `opacity`, the border
28//! width, style, colour and radius properties, `font-family`,
29//! `font-size`, `font-weight`, `font-style`, `line-height`,
30//! `letter-spacing` and `text-align`, with their shorthands. See
31//! [`LonghandId`] and [`ShorthandId`] for the full list.
32//! - **Values**: `px`, `em`, `rem`, `pt` and the other absolute units,
33//! percentages, every CSS colour syntax up to `oklch()` and
34//! `color(display-p3 ...)`, `!important`, and the `inherit`, `initial`
35//! and `unset` keywords.
36//!
37//! Not supported: at-rules (`@media`, `@import`, ...), nesting, pseudo-elements,
38//! `calc()`, custom properties, transitions, and every layout property.
39//! Layout is the toolkit's job; this crate only hands it numbers.
40//!
41//! # Example
42//!
43//! A toolkit implements [`Element`] for a handle to its nodes, parses its
44//! stylesheets, and asks a [`Styler`] for each node's style, top-down so
45//! that each parent's style is available for its children.
46//!
47//! ```
48//! use eternal_styler::{Element, ElementState, OpaqueElement, Styler, Stylesheet, Color};
49//! use eternal_styler::LengthPercentage;
50//!
51//! // A minimal widget tree: an arena of nodes.
52//! #[derive(Debug)]
53//! struct Node { name: &'static str, class: Option<&'static str>, hovered: bool, parent: Option<usize>, children: Vec<usize> }
54//! #[derive(Debug)]
55//! struct Tree(Vec<Node>);
56//!
57//! #[derive(Clone, Debug)]
58//! struct Handle<'a> { tree: &'a Tree, index: usize }
59//!
60//! impl<'a> Handle<'a> {
61//! fn node(&self) -> &'a Node { &self.tree.0[self.index] }
62//! fn at(&self, index: usize) -> Self { Handle { tree: self.tree, index } }
63//! }
64//!
65//! impl Element for Handle<'_> {
66//! fn opaque(&self) -> OpaqueElement { OpaqueElement::new(self.node()) }
67//! fn parent(&self) -> Option<Self> { self.node().parent.map(|i| self.at(i)) }
68//! fn first_child(&self) -> Option<Self> { self.node().children.first().map(|&i| self.at(i)) }
69//! fn prev_sibling(&self) -> Option<Self> { None } // a real toolkit would look these up
70//! fn next_sibling(&self) -> Option<Self> { None }
71//! fn local_name(&self) -> &str { self.node().name }
72//! fn classes(&self) -> impl Iterator<Item = &str> { self.node().class.into_iter() }
73//! fn state(&self) -> ElementState {
74//! if self.node().hovered { ElementState::HOVER } else { ElementState::empty() }
75//! }
76//! }
77//!
78//! let tree = Tree(vec![
79//! Node { name: "panel", class: None, hovered: false, parent: None, children: vec![1] },
80//! Node { name: "button", class: Some("primary"), hovered: true, parent: Some(0), children: vec![] },
81//! ]);
82//!
83//! let mut styler = Styler::new();
84//! styler.add_stylesheet(Stylesheet::parse(r#"
85//! panel { font-size: 20px; color: #333; }
86//! button { padding: 0.5em 1em; border: 1px solid; }
87//! button.primary:hover { background-color: #06f; color: white; }
88//! "#)?);
89//!
90//! let panel = Handle { tree: &tree, index: 0 };
91//! let panel_style = styler.compute(&panel, None);
92//! let button_style = styler.compute(&panel.at(1), Some(&panel_style));
93//!
94//! assert_eq!(button_style.font_size, 20.0); // inherited
95//! assert_eq!(button_style.padding.left, LengthPercentage::Px(20.0)); // 1em of 20px
96//! assert_eq!(button_style.background_color, Color::from_packed_rgba(0x0066ffff));
97//! assert_eq!(button_style.border_color.top, Color::WHITE); // currentcolor
98//! # Ok::<(), eternal_styler::Error>(())
99//! ```
100
101mod atom;
102mod cascade;
103mod computed;
104mod element;
105mod error;
106mod properties;
107mod selector;
108pub mod specified;
109mod styler;
110mod stylesheet;
111mod values;
112
113pub use selectors::OpaqueElement;
114
115pub use atom::Atom;
116pub use computed::{
117 ComputedStyle, LengthPercentage, LengthPercentageOrAuto, LengthPercentageOrNone, LineHeight,
118};
119pub use element::{Element, ElementState, opaque_element_from_index};
120pub use error::{Error, ErrorKind};
121pub use properties::{CssWideKeyword, LonghandId, PropertyDeclaration, PropertyId, ShorthandId};
122pub use selector::{PseudoClass, PseudoElement, Selector, SelectorImpl, SelectorList};
123pub use styler::Styler;
124pub use stylesheet::{Declaration, DeclarationBlock, StyleRule, Stylesheet};
125pub use values::{
126 BorderStyle, Color, Corners, FontFamily, FontStyle, FontWeight, Sides, TextAlign,
127};