Skip to main content

Stylesheet

Struct Stylesheet 

Source
pub struct Stylesheet { /* private fields */ }
Expand description

A parsed stylesheet containing styles keyed by element ID

Implementations§

Source§

impl Stylesheet

Source

pub fn new() -> Stylesheet

Create an empty stylesheet

Source

pub fn parse_with_errors(css: &str) -> CssParseResult

Parse CSS text into a stylesheet with full error collection

This is the recommended method for parsing CSS as it collects all errors and warnings during parsing, allowing you to report them to users in a human-readable format.

§Example
let css = "#card { opacity: 0.5; unknown: value; }";
let result = Stylesheet::parse_with_errors(css);

// Print any warnings to stderr
result.print_diagnostics();

// Use the stylesheet (partial results are still available)
let stylesheet = result.stylesheet;
Source

pub fn parse_with_variables( css: &str, external_vars: &HashMap<String, String>, ) -> Result<Stylesheet, ParseError>

Parse CSS with pre-seeded external variables (e.g. from theme or prior stylesheets).

var(--name) references in the CSS will resolve against both :root variables defined in this CSS and the provided external variables. CSS-defined variables take precedence over external ones.

Source

pub fn parse_with_errors_and_variables( css: &str, external_vars: &HashMap<String, String>, ) -> CssParseResult

Parse CSS with external variables and full error collection.

Source

pub fn parse(css: &str) -> Result<Stylesheet, ParseError>

Parse CSS text into a stylesheet

Parse errors are logged via tracing at DEBUG level with full context. When parsing fails, an error is returned but the application can fall back to built-in theme styles.

For full error collection, use parse_with_errors() instead.

§Example
let css = "#card { opacity: 0.5; }";
let stylesheet = Stylesheet::parse(css)?;
Source

pub fn parse_or_empty(css: &str) -> Stylesheet

Parse CSS text, logging errors and returning an empty stylesheet on failure

This is a convenience method for cases where you want to gracefully fall back to an empty stylesheet rather than handle errors explicitly.

Source

pub fn insert(&mut self, id: impl Into<String>, style: ElementStyle)

Insert a style for an element ID (without the # prefix)

This is the programmatic equivalent of parsing #id { ... } in CSS. If a style already exists for this ID, it is replaced.

Source

pub fn insert_with_state( &mut self, id: impl Into<String>, state: ElementState, style: ElementStyle, )

Insert a state-specific style for an element ID

This is the programmatic equivalent of parsing #id:hover { ... } in CSS.

Source

pub fn get(&self, id: &str) -> Option<&ElementStyle>

Get a style by element ID (without the # prefix)

Returns None if no style is defined for the given ID.

Source

pub fn get_with_state( &self, id: &str, state: ElementState, ) -> Option<&ElementStyle>

Get a style by element ID and state

Looks up #id:state in the stylesheet.

§Example
let css = "#button:hover { opacity: 0.8; }";
let stylesheet = Stylesheet::parse(css)?;
let hover_style = stylesheet.get_with_state("button", ElementState::Hover);
Source

pub fn get_placeholder_style(&self, id: &str) -> Option<&ElementStyle>

Get the ::placeholder pseudo-element style for an element ID

Looks up #id::placeholder in the stylesheet. The color property in a ::placeholder block maps to text_color on the returned style, and placeholder-color maps directly.

Source

pub fn get_all_states( &self, id: &str, ) -> (Option<&ElementStyle>, Vec<(ElementState, &ElementStyle)>)

Get all styles for an element, including state variants

Returns a tuple of (base_style, state_styles) where state_styles is a Vec of (ElementState, &ElementStyle) pairs.

§Example
let css = r#"
    #button { background: blue; }
    #button:hover { background: lightblue; }
    #button:active { background: darkblue; }
"#;
let stylesheet = Stylesheet::parse(css)?;
let (base, states) = stylesheet.get_all_states("button");
Source

pub fn contains(&self, id: &str) -> bool

Check if a style exists for the given ID

Source

pub fn contains_with_state(&self, id: &str, state: ElementState) -> bool

Check if a style exists for the given ID and state

Source

pub fn ids(&self) -> impl Iterator<Item = &str>

Get all style IDs in the stylesheet

Source

pub fn len(&self) -> usize

Get the number of styles in the stylesheet

Source

pub fn is_empty(&self) -> bool

Check if the stylesheet is empty

Source

pub fn complex_rules(&self) -> &[(ComplexSelector, ElementStyle)]

Get all complex selector rules

Source

pub fn has_complex_state_rules(&self) -> bool

Check if there are any complex rules that involve state changes

Source

pub fn svg_tag_rules( &self, ) -> Vec<(&str, &[(CompoundSelector, Option<Combinator>)], &ElementStyle)>

Returns complex rules whose rightmost compound selector targets an SVG tag name.

Each entry returns: (tag_name, ancestor_segments if any, style). For a bare path { fill: red; }, ancestor_segments is empty. For #my-svg path { fill: red; }, ancestor_segments contains the #my-svg part.

Source

pub fn merge(&mut self, other: Stylesheet)

Merge another stylesheet into this one (cascade — later rules override earlier)

This follows CSS cascade rules: styles from other override matching styles in self. Variables and keyframes are also merged.

Source

pub fn from_file(path: impl AsRef<Path>) -> Result<Stylesheet, ParseError>

Load and parse a .css file from disk

Source

pub fn get_variable(&self, name: &str) -> Option<&str>

Get a CSS variable value by name (without the – prefix)

§Example
let css = ":root { --card-bg: #ffffff; }";
let stylesheet = Stylesheet::parse(css)?;
assert_eq!(stylesheet.get_variable("card-bg"), Some("#ffffff"));
Source

pub fn set_variable( &mut self, name: impl Into<String>, value: impl Into<String>, )

Set a CSS variable (useful for runtime overrides)

§Example
stylesheet.set_variable("primary-color", "#FF0000");
Source

pub fn variable_names(&self) -> impl Iterator<Item = &str>

Get all variable names

Source

pub fn variable_count(&self) -> usize

Get the number of variables defined

Source

pub fn variables(&self) -> &HashMap<String, String>

Get all CSS variables as a reference to the internal map

Source

pub fn get_keyframes(&self, name: &str) -> Option<&CssKeyframes>

Get a keyframe animation by name

§Example
let css = r#"
    @keyframes fade-in {
        from { opacity: 0; }
        to { opacity: 1; }
    }
"#;
let stylesheet = Stylesheet::parse_with_errors(css).stylesheet;
if let Some(keyframes) = stylesheet.get_keyframes("fade-in") {
    let animation = keyframes.to_enter_animation(300);
}
Source

pub fn contains_keyframes(&self, name: &str) -> bool

Check if keyframes exist with the given name

Source

pub fn keyframe_names(&self) -> impl Iterator<Item = &str>

Get all keyframe animation names

Source

pub fn keyframe_count(&self) -> usize

Get the number of keyframe animations defined

Source

pub fn add_keyframes(&mut self, keyframes: CssKeyframes)

Add a keyframe animation to the stylesheet

Source

pub fn get_flow(&self, name: &str) -> Option<&FlowGraph>

Look up a flow DAG by name

Source

pub fn contains_flow(&self, name: &str) -> bool

Check if a flow exists with the given name

Source

pub fn flow_names(&self) -> impl Iterator<Item = &str>

Get all flow names

Source

pub fn flow_count(&self) -> usize

Get the number of flows defined

Source

pub fn add_flow(&mut self, flow: FlowGraph)

Add a flow DAG to the stylesheet

Source

pub fn resolve_animation(&self, id: &str) -> Option<MotionAnimation>

Resolve a full motion animation for an element by its ID

This combines:

  1. The element’s animation: property (from its style)
  2. The referenced @keyframes definition

Returns Some(MotionAnimation) if the element has an animation configured and the keyframes exist.

§Example
let css = r#"
    @keyframes fade-in {
        from { opacity: 0; transform: translateY(20px); }
        to { opacity: 1; transform: translateY(0); }
    }
    #card {
        animation: fade-in 300ms ease-out;
    }
"#;
let stylesheet = Stylesheet::parse_with_errors(css).stylesheet;

if let Some(motion) = stylesheet.resolve_animation("card") {
    // Apply motion animation to the element
}
Source

pub fn resolve_animation_with_state( &self, id: &str, state: ElementState, ) -> Option<MotionAnimation>

Resolve animation for an element considering its current state

This checks both the base style and state-specific styles for animations.

Source

pub fn resolve_keyframe_animation( &self, id: &str, ) -> Option<MultiKeyframeAnimation>

Resolve CSS animation to full MultiKeyframeAnimation with all keyframes preserved

Unlike resolve_animation() which only captures first/last keyframes for simple enter/exit animations, this method preserves ALL keyframes for complex multi-step animations like pulse, bounce, etc.

§Example
let css = r#"
    @keyframes pulse {
        0%, 100% { opacity: 1; transform: scale(1); }
        50% { opacity: 0.8; transform: scale(1.05); }
    }
    #button { animation: pulse 1000ms ease-in-out infinite; }
"#;
let stylesheet = Stylesheet::parse_with_errors(css).stylesheet;
if let Some(mut anim) = stylesheet.resolve_keyframe_animation("button") {
    anim.start();
    // Animation will interpolate through all 3 keyframes
}
Source

pub fn resolve_keyframe_animation_with_state( &self, id: &str, state: ElementState, ) -> Option<MultiKeyframeAnimation>

Resolve keyframe animation for an element considering its current state

This checks both the base style and state-specific styles for animations, returning a full MultiKeyframeAnimation with all keyframes preserved.

Trait Implementations§

Source§

impl Clone for Stylesheet

Source§

fn clone(&self) -> Stylesheet

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Stylesheet

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for Stylesheet

Source§

fn default() -> Stylesheet

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> NodeState for T
where T: Send + 'static,

Source§

fn as_any(&self) -> &(dyn Any + 'static)

Get self as Any for downcasting
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Get self as mutable Any for downcasting
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,