rustyle_css/
ssr.rs

1use crate::style::{get_all_global_styles, StyleRegistry};
2
3/// Collect styles for SSR rendering
4pub fn collect_styles_for_ssr() -> String {
5    let scoped_styles = StyleRegistry::get_all_styles();
6    let global_styles = get_all_global_styles();
7
8    let all_styles = if global_styles.is_empty() {
9        scoped_styles
10    } else if scoped_styles.is_empty() {
11        global_styles
12    } else {
13        format!("{}\n{}", global_styles, scoped_styles)
14    };
15
16    if all_styles.is_empty() {
17        String::new()
18    } else {
19        format!("<style id=\"rustyle-styles\">{}</style>", all_styles)
20    }
21}
22
23/// Inject styles into SSR HTML
24pub fn inject_styles_ssr(html: &str, styles: &str) -> String {
25    if styles.is_empty() {
26        return html.to_string();
27    }
28
29    // Try to inject before </head>, otherwise before </body>
30    if html.contains("</head>") {
31        html.replace("</head>", &format!("{}\n</head>", styles))
32    } else if html.contains("</body>") {
33        html.replace("</body>", &format!("{}\n</body>", styles))
34    } else {
35        format!("{}\n{}", styles, html)
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42
43    #[test]
44    fn test_inject_styles_ssr() {
45        let html = "<html><head></head><body></body></html>";
46        let styles = "<style>test</style>";
47        let result = inject_styles_ssr(html, styles);
48        assert!(result.contains("test"));
49    }
50}