cercis_html/
lib.rs

1use smallvec::SmallVec;
2use std::cell::RefCell;
3use std::rc::Rc;
4
5use crate::prelude::*;
6
7pub mod attribute;
8pub mod component;
9pub mod content;
10pub mod element;
11pub mod prelude;
12pub mod render;
13
14const CHLD_DEFAULT: usize = 8;
15
16/// Type alias for [`VBody`] struct as ```VBody<'a>```
17pub type Element<'a, const CHLD: usize = CHLD_DEFAULT> = VBody<'a, CHLD>;
18
19type VBodyInner<'a, const CHLD: usize> = Rc<RefCell<SmallVec<[Box<dyn Render + 'a>; CHLD]>>>;
20
21/// Container for any elements which implements [`Render`] trait
22#[derive(Default, Clone)]
23pub struct VBody<'a, const CHLD: usize = CHLD_DEFAULT>(VBodyInner<'a, CHLD>);
24
25impl<'a> VBody<'a> {
26    /// Create new container with empty children
27    pub fn new() -> Self {
28        Self(Rc::new(RefCell::new(SmallVec::new())))
29    }
30
31    pub fn new_sized<const C: usize>() -> VBody<'a, C> {
32        VBody(Rc::new(RefCell::new(SmallVec::new())))
33    }
34}
35
36impl<'a, const CHLD: usize> VBody<'a, CHLD> {
37    /// Add child into container (The elements must implement trait [`Render`])
38    pub fn child(self, child: impl Render + 'a) -> Self {
39        self.0.borrow_mut().push(Box::new(child));
40
41        self
42    }
43}
44
45impl<const CHLD: usize> Render for VBody<'_, CHLD> {
46    fn render(&self) -> String {
47        let mut body = String::new();
48
49        for child in self.0.borrow().iter() {
50            body.push_str(&child.render())
51        }
52
53        body
54    }
55}
56
57impl<const CHLD: usize> Render for &VBody<'_, CHLD> {
58    fn render(&self) -> String {
59        (*self).render()
60    }
61}