stylist_core/ast/
block.rs

1use std::borrow::Cow;
2
3use serde::{Deserialize, Serialize};
4
5use super::{RuleBlockContent, Selector, StyleContext, ToStyleStr};
6
7/// A block is a set of css properties that apply to elements that
8/// match the condition. The CSS standard calls these "Qualified rules".
9///
10/// E.g.:
11/// ```css
12/// .inner {
13///     color: red;
14/// }
15/// ```
16#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
17pub struct Block {
18    /// Selector(s) for Current Block
19    ///
20    /// If the value is set as [`&[]`], it signals to substitute with the classname generated for
21    /// the [`Sheet`](super::Sheet) in which this is contained.
22    pub condition: Cow<'static, [Selector]>,
23    pub content: Cow<'static, [RuleBlockContent]>,
24}
25
26impl Block {
27    fn cond_str(&self, ctx: &mut StyleContext<'_>) -> Option<String> {
28        if self.condition.is_empty() {
29            return None;
30        }
31
32        let mut cond = "".to_string();
33
34        for (index, sel) in self.condition.iter().enumerate() {
35            sel.write_style(&mut cond, ctx);
36            if index < self.condition.len() - 1 {
37                cond.push_str(", ");
38            }
39        }
40
41        Some(cond)
42    }
43}
44
45impl ToStyleStr for Block {
46    fn write_style(&self, w: &mut String, ctx: &mut StyleContext<'_>) {
47        // TODO: nested block, which is not supported at the moment.
48        let cond_s = self.cond_str(ctx);
49
50        let mut block_ctx = ctx.with_block_condition(cond_s);
51
52        for attr in self.content.iter() {
53            attr.write_style(w, &mut block_ctx);
54        }
55
56        block_ctx.finish(w);
57    }
58}