fervid_parser/
style.rs

1use fervid_core::{fervid_atom, SfcStyleBlock};
2use swc_html_ast::{Child, Element};
3
4use crate::{error::ParseErrorKind, ParseError, SfcParser};
5
6impl SfcParser<'_, '_, '_> {
7    pub fn parse_sfc_style_element(&mut self, mut element: Element) -> Option<SfcStyleBlock> {
8        // Find the attributes
9        let mut lang = fervid_atom!("css");
10        let mut is_scoped = false;
11        let mut is_module = false;
12
13        for attr in element.attributes.into_iter() {
14            if attr.name.eq("lang") {
15                let Some(attr_val) = attr.value else {
16                    continue;
17                };
18
19                lang = attr_val;
20            } else if attr.name.eq("scoped") {
21                is_scoped = true;
22            } else if attr.name.eq("module") {
23                is_module = true;
24            }
25        }
26
27        // `<style>` must have exactly one Text child
28        let style_content = match element.children.pop() {
29            Some(Child::Text(t)) => t,
30            Some(_) => {
31                self.report_error(ParseError {
32                    kind: ParseErrorKind::UnexpectedNonRawTextContent,
33                    span: element.span,
34                });
35                return None;
36            }
37            None if self.ignore_empty => {
38                return None;
39            }
40            None => {
41                return Some(SfcStyleBlock {
42                    lang,
43                    content: fervid_atom!(""),
44                    is_scoped,
45                    is_module,
46                    span: element.span,
47                });
48            }
49        };
50
51        // Ignore empty unless allowed
52        if self.ignore_empty && style_content.data.trim().is_empty() {
53            return None;
54        }
55
56        Some(SfcStyleBlock {
57            lang,
58            content: style_content.data,
59            is_scoped,
60            is_module,
61            span: style_content.span,
62        })
63    }
64}