pochoir-extra 0.12.2

Extra utilities for the pochoir template engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
//! CSS enhancer using the awesome [lightningcss](https://lightningcss.dev/) crate.
//!
//! Support:
//!
//! - Scoped CSS
//! - CSS minification
//! - CSS [nesting](https://www.w3.org/TR/css-nesting-1/) and custom [@media queries](https://drafts.csswg.org/mediaqueries-5/#custom-mq)
//! - CSS autoprefixer and polyfiller (supports using modern CSS and generates CSS compatible with
//!   the chosen browsers)
//!
//! This plugin has two ways of use: either you can enhance the CSS of a single component and write
//! a single `<style>` element containing the generated CSS in it (see [`EnhancedCss`]), or you can bundle all the enhanced CSS into
//! a single string that you can use as you wish (see [`EnhancedCssBundler`]).
//!
//! In either way, you need to use the `enhanced` attribute on any `<style>` element that you want to be enhanced. You can also add a `.browserslistrc` file to configure the target browsers of the
//! generated CSS (see [the other ways to configure the targets](https://docs.rs/lightningcss/1.0.0-alpha.44/lightningcss/targets/struct.Browsers.html#method.load_browserslist)). The CSS will also be scoped to the component defining it to avoid selector clashing.
//!
//! Note that when using this transformer, the component names **must be unique**, otherwise the
//! scoped CSS generated will have conflicts.
//!
//! If you need to use scoped CSS inside children of `<slot>` elements, you can add the
//! `enhanced-slots` attribute to one of the enhanced `<style>` element and they will inherit all
//! scoped styles you define in enhanced styles.
use lightningcss::{
    rules::CssRule,
    selector::{Component, Selector},
    stylesheet::{MinifyOptions, ParserFlags, ParserOptions, PrinterOptions, StyleSheet},
    targets::{Browsers, Features, Targets},
    traits::IntoOwned,
    values::ident::Ident,
};
use std::{
    borrow::Cow,
    collections::{hash_map::DefaultHasher, HashSet, VecDeque},
    hash::{Hash, Hasher},
};

use pochoir::{
    common::Spanned,
    parser::{Attrs, Node, Tree, TreeRefId},
    template_engine::{Escaping, TemplateBlock},
    transformers::Transformer,
    TransformerElementContext, TransformerResult, TransformerTreeContext,
};

fn add_component_to_selector<'a>(
    component: &Component<'a>,
    selector: &Selector<'a>,
) -> Selector<'a> {
    let mut components = vec![VecDeque::new()];
    let mut iter = selector.iter();

    loop {
        for c in &mut iter {
            components.last_mut().unwrap().push_back(c.clone());
        }

        let is_nested = components
            .last()
            .unwrap()
            .back()
            .is_none_or(|c| *c == Component::Nesting);

        if !is_nested {
            components.last_mut().unwrap().push_back(component.clone());
        }

        if let Some(combinator) = iter.next_sequence() {
            components
                .last_mut()
                .unwrap()
                .push_front(Component::Combinator(combinator));
            components.push(VecDeque::new());
        } else {
            break;
        }
    }

    let components = components
        .into_iter()
        .rev()
        .flatten()
        .collect::<Vec<Component>>();

    Selector::from(components)
}

fn do_scoped_css(
    component_name: &str,
    enhance_slots: bool,
    tree: &mut Tree,
    stylesheet: &mut StyleSheet,
) {
    fn do_scoped_css_recursive<'a>(rule: &mut CssRule<'a>, data_component: &Component<'a>) {
        if let CssRule::Style(ref mut style_rule) = rule {
            for selector in &mut style_rule.selectors.0 {
                *selector = add_component_to_selector(data_component, selector);
            }

            for rule in &mut style_rule.rules.0 {
                do_scoped_css_recursive(rule, data_component);
            }
        }
    }

    // Generated IDs should have at most 8 digits
    const MAX_DIGITS: usize = 8;

    // Generate a unique component ID by hashing the component name
    let mut hasher = DefaultHasher::new();
    component_name.hash(&mut hasher);

    let unique_id = format!("{:x}", hasher.finish());
    let unique_id_attr = format!("data-p-{}", &unique_id[..MAX_DIGITS]);

    // Add this ID as a data attribute on all elements of the component
    for id in tree.all_nodes() {
        let node = tree.get(id);

        if enhance_slots && node.name().is_ok_and(|el_name| el_name == "slot") {
            // Use single quotes in the attribute key so it could not be created manually
            tree.get_mut(id)
                .set_attr("'__p_attr'", unique_id_attr.clone(), Escaping::None);
        } else if node.name().is_ok_and(|el_name| {
            !["html", "body", "style", "script"].contains(&&*el_name)
        }) && node.closest("head").is_none()
        {
            tree.get_mut(id)
                .set_attr(unique_id_attr.clone(), "", Escaping::None);
        }
    }

    // Add this data attribute to all CSS selectors of the stylesheet (containing the concatenated
    // CSS of all <style> elements of the component)
    let local_name = Ident::from(unique_id_attr);

    let data_component = Component::Where(Box::new([Selector::from(
        Component::AttributeInNoNamespaceExists {
            local_name: local_name.clone(),
            local_name_lower: local_name.clone(),
        },
    )]));

    for rule in &mut stylesheet.rules.0 {
        do_scoped_css_recursive(rule, &data_component);
    }
}

/// Enhance the CSS of a single component and write a single `<style>` element
/// containing the generated CSS in it.
///
/// # Example
///
/// ```no_run
/// use pochoir::{lang::Context, ComponentFile, transformers::Transformers};
/// use pochoir_extra::EnhancedCss;
///
/// let source = r#"
/// <main>
///   <a href="/"></a>
/// </main>
///
/// {# Don't forget the `enhanced` attribute #}
/// <style enhanced>
/// main {
///   background-color: rebeccapurple;
///
///   & a {
///     color: aquamarine;
///   }
/// }
/// </style>"#;
/// let file_path = std::path::Path::new("index.html");
///
/// // 1. Add the `EnhancedCss` structure as a transformer
/// let mut transformers = Transformers::new()
///     .with_transformer(EnhancedCss::new());
///
/// // 2. Use `pochoir::transform_and_compile` with a mutable reference
/// // to the transformers as last argument
/// assert_eq!(
///     pochoir::transform_and_compile("index", &mut Context::new(), |name| {
///         Ok(ComponentFile::new(file_path, source))
///     }, &mut transformers),
///     Ok(r#"
/// <main data-p-fd1ea890>
///   <a href="/" data-p-fd1ea890></a>
/// </main>
///
///
/// <style>main[data-p-fd1ea890]{background-color:#639}main[data-p-fd1ea890] a{color:#7fffd4}</style>"#.to_string()),
/// );
/// ```
#[derive(Debug)]
pub struct EnhancedCss {
    enhance_slots: bool,
    style_source: String,
    include_css_features: Features,
    exclude_css_features: Features,
}

impl EnhancedCss {
    /// Create a new [`EnhancedCss`].
    pub fn new() -> Self {
        Self {
            enhance_slots: false,
            style_source: String::new(),
            include_css_features: Features::default(),
            exclude_css_features: Features::default(),
        }
    }

    /// Define the CSS features that you want your transpiled CSS code to use by including them.
    ///
    /// See [`lightningcss::targets::Features`].
    #[must_use]
    pub fn include_css_features(mut self, features: Features) -> Self {
        self.include_css_features = features;
        self
    }

    /// Define the CSS features that you want your transpiled CSS code to use by excluding the ones
    /// you don't want.
    ///
    /// See [`lightningcss::targets::Features`].
    #[must_use]
    pub fn exclude_css_features(mut self, features: Features) -> Self {
        self.exclude_css_features = features;
        self
    }
}

impl Transformer for EnhancedCss {
    fn on_after_element(&mut self, ctx: &mut TransformerElementContext) -> TransformerResult {
        let el = ctx.tree.get(ctx.element_id);

        if el.name().unwrap() == "style"
            && el
                .attr("enhanced")
                .expect("attr is called on an element")
                .is_some()
        {
            if el
                .attr("enhanced-slots")
                .expect("attr is called on an element")
                .is_some()
            {
                self.enhance_slots = true;
            }

            self.style_source
                .push_str(&el.children().map(|c| c.text()).collect::<String>());
            ctx.tree.get_mut(ctx.element_id).remove();
        }

        Ok(())
    }

    fn on_tree_parsed(&mut self, ctx: &mut TransformerTreeContext) -> TransformerResult {
        let targets = Targets {
            browsers: Browsers::load_browserslist()?,
            include: self.include_css_features,
            exclude: self.exclude_css_features,
        };

        let mut stylesheet = StyleSheet::parse(
            &self.style_source,
            ParserOptions {
                filename: ctx.file_path.to_string_lossy().into_owned(),
                flags: ParserFlags::NESTING | ParserFlags::CUSTOM_MEDIA,
                ..Default::default()
            },
        )
        .map_err(|e| e.to_string())?;

        do_scoped_css(
            ctx.component_name,
            self.enhance_slots,
            ctx.tree,
            &mut stylesheet,
        );

        stylesheet.minify(MinifyOptions {
            targets,
            ..Default::default()
        })?;

        let enhanced_css = stylesheet
            .to_css(PrinterOptions {
                minify: true,
                targets,
                ..Default::default()
            })?
            .code;

        // Add <style> node as a child of <head> if possible or as the last child
        let parent = ctx.tree.select("head").unwrap().unwrap_or(TreeRefId::Root);
        let style_id = ctx.tree.insert(
            parent,
            Spanned::new(Node::Element(Cow::Borrowed("style"), Attrs::new())),
        );
        let _text_id = ctx.tree.insert(
            style_id,
            Spanned::new(Node::TemplateBlock(TemplateBlock::RawText(Cow::Owned(
                enhanced_css,
            )))),
        );

        drop(stylesheet);

        // `stylesheet` is now dropped, we can reset the source
        self.style_source = String::new();

        Ok(())
    }
}

impl Default for EnhancedCss {
    fn default() -> Self {
        Self::new()
    }
}

/// Bundle all the enhanced CSS into a single string that you can use as you wish.
///
/// # Example
///
/// ```no_run
/// use pochoir::{lang::Context, ComponentFile, transformers::Transformers};
/// use pochoir_extra::{EnhancedCssBundler, enhanced_css::CssBundle};
///
/// let index_source = "<h1>Index page</h1><my-button />
/// <style enhanced>
/// h1 {
///   font-weight: extrabold;
/// }
/// </style>";
/// let my_button_source = "<button>Click me!</button>
/// <style enhanced>
/// button:hover {
///   background-color: antiquewhite;
/// }
/// </style>";
/// let index_file_path = std::path::Path::new("index.html");
/// let my_button_file_path = std::path::Path::new("my-button.html");
///
/// // 1. Make a buffer which will be filled with the CSS bundle
/// let mut css_bundle = CssBundle::new();
///
/// // 2. Add the `EnhancedCssBundler` structure as a transformer and give the buffer to it
/// let mut transformers = Transformers::new()
///     .with_transformer(EnhancedCssBundler::new(&mut css_bundle));
///
/// // 3. Use `pochoir::transform_and_compile` with a mutable reference
/// // to the transformers as last argument
/// let _compiled = pochoir::transform_and_compile("index", &mut Context::new(), |name| {
///     let (file_path, source) = match name {
///         "index" => (index_file_path, index_source),
///         "my-button" => (my_button_file_path, my_button_source),
///         _ => unreachable!(),
///     };
///
///     Ok(ComponentFile::new(file_path, source))
/// }, &mut transformers);
///
/// // 4. Don't forget to drop the `transformers` before using the bundle because they stored a
/// // mutable reference to it
/// drop(transformers);
/// assert_eq!(css_bundle.finish().expect("failed to bundle the CSS"), "h1[data-p-fd1ea890]{font-weight:extrabold}button:hover[data-p-92dd4f04]{background-color:#faebd7}");
/// ```
#[derive(Debug)]
pub struct EnhancedCssBundler<'a, 'source, 'options> {
    enhance_slots: bool,
    current_component_css_start: usize,
    css_bundle: &'a mut CssBundle<'source, 'options>,
}

impl<'a, 'source, 'options> EnhancedCssBundler<'a, 'source, 'options> {
    /// Create a new [`EnhancedCssBundler`].
    ///
    /// # Panics
    ///
    /// This function will panic if loading the browserslist failed.
    pub fn new(css_bundle: &'a mut CssBundle<'source, 'options>) -> Self {
        Self::try_new(css_bundle).expect("an error happened when loading browserslist")
    }

    /// Create a new [`EnhancedCssBundler`].
    ///
    /// # Errors
    ///
    /// This function will return a boxed [`std::error::Error`] if loading the browserslist failed.
    pub fn try_new(
        css_bundle: &'a mut CssBundle<'source, 'options>,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        Ok(Self {
            enhance_slots: false,
            current_component_css_start: 0,
            css_bundle,
        })
    }

    /// Define the CSS features that you want your transpiled CSS code to use by including them.
    ///
    /// See [`lightningcss::targets::Features`].
    #[must_use]
    pub fn include_css_features(self, features: Features) -> Self {
        self.css_bundle.targets.include = features;
        self
    }

    /// Define the CSS features that you want your transpiled CSS code to use by excluding the ones
    /// you don't want.
    ///
    /// See [`lightningcss::targets::Features`].
    #[must_use]
    pub fn exclude_css_features(self, features: Features) -> Self {
        self.css_bundle.targets.exclude = features;
        self
    }
}

impl Transformer for EnhancedCssBundler<'_, '_, '_> {
    fn on_after_element(&mut self, ctx: &mut TransformerElementContext) -> TransformerResult {
        let el = ctx.tree.get(ctx.element_id);

        if el.name().unwrap() == "style"
            && el
                .attr("enhanced")
                .expect("attr is called on an element")
                .is_some()
        {
            if el
                .attr("enhanced-slots")
                .expect("attr is called on an element")
                .is_some()
            {
                self.enhance_slots = true;
            }

            self.css_bundle
                .style_source
                .push_str(&el.children().map(|c| c.text()).collect::<String>());
            ctx.tree.get_mut(ctx.element_id).remove();
        }

        Ok(())
    }

    fn on_tree_parsed(&mut self, ctx: &mut TransformerTreeContext) -> TransformerResult {
        let mut stylesheet = StyleSheet::parse(
            &self.css_bundle.style_source[self.current_component_css_start..],
            ParserOptions {
                filename: ctx.file_path.to_string_lossy().into_owned(),
                flags: ParserFlags::NESTING | ParserFlags::CUSTOM_MEDIA,
                ..Default::default()
            },
        )
        .map_err(|e| e.to_string())?;

        do_scoped_css(
            ctx.component_name,
            self.enhance_slots,
            ctx.tree,
            &mut stylesheet,
        );

        if self
            .css_bundle
            .processed_components
            .contains(ctx.component_name)
        {
            return Ok(());
        }

        if let Some(bundle_stylesheet) = self.css_bundle.stylesheet.as_mut() {
            bundle_stylesheet.sources.extend(stylesheet.sources);
            bundle_stylesheet
                .rules
                .0
                .extend(stylesheet.rules.0.into_owned());
            bundle_stylesheet
                .license_comments
                .extend(stylesheet.license_comments.into_owned());
        } else {
            // Make an owned StyleSheet
            self.css_bundle.stylesheet = Some(StyleSheet::new(
                stylesheet.sources,
                stylesheet.rules.into_owned(),
                ParserOptions {
                    filename: ctx.file_path.to_string_lossy().into_owned(),
                    flags: ParserFlags::NESTING | ParserFlags::CUSTOM_MEDIA,
                    ..Default::default()
                },
            ));
        }

        self.css_bundle
            .processed_components
            .insert(ctx.component_name.to_string());

        // `stylesheet` is now dropped, we can reset the source
        self.current_component_css_start = self.css_bundle.style_source.len();

        Ok(())
    }
}

/// Represents a CSS stylesheet being built using an [`EnhancedCssBundler`].
///
/// You can use [`CssBundle::new`] or [`CssBundle::default`] to build a new empty one and
/// [`CssBundle::finish`] to get its contents.
#[derive(Debug)]
pub struct CssBundle<'source, 'options> {
    style_source: String,
    stylesheet: Option<StyleSheet<'source, 'options>>,
    targets: Targets,
    processed_components: HashSet<String>,
}

impl CssBundle<'_, '_> {
    /// Make a new empty [`CssBundle`].
    pub fn new() -> Self {
        Self::default()
    }

    /// Get the bundle contents as a minified CSS string.
    ///
    /// # Errors
    ///
    /// Returns an error if minification or print failed.
    pub fn finish(self) -> Result<String, Box<dyn std::error::Error>> {
        if let Some(mut stylesheet) = self.stylesheet {
            stylesheet.minify(MinifyOptions {
                targets: self.targets,
                ..Default::default()
            })?;

            Ok(stylesheet
                .to_css(PrinterOptions {
                    minify: true,
                    targets: self.targets,
                    ..Default::default()
                })
                .map(|c| c.code)?)
        } else {
            Ok(String::new())
        }
    }
}

impl Default for CssBundle<'_, '_> {
    fn default() -> Self {
        Self {
            style_source: String::new(),
            stylesheet: None,
            targets: Targets {
                browsers: Browsers::load_browserslist().unwrap_or(None),
                ..Default::default()
            },
            processed_components: HashSet::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pochoir::{lang::Context, transformers::Transformers, ComponentFile, Result};

    fn compile_bundle<'a>(
        index_source: &'a str,
        child_source: &'a str,
    ) -> (CssBundle<'a, 'a>, Result<String>) {
        let index_file_path = std::path::Path::new("index.html");
        let child_file_path = std::path::Path::new("child.html");

        let mut css_bundle = CssBundle::new();

        let mut transformers =
            Transformers::new().with_transformer(EnhancedCssBundler::new(&mut css_bundle));

        let compiled = pochoir::transform_and_compile(
            "index",
            &mut Context::new(),
            |name| {
                let (file_path, source) = match name {
                    "index" => (index_file_path, index_source),
                    "child-component" => (child_file_path, child_source),
                    _ => unreachable!(),
                };

                Ok(ComponentFile::new(file_path, source))
            },
            &mut transformers,
        );

        drop(transformers);
        (css_bundle, compiled)
    }

    #[test]
    fn avoid_duplication() {
        let index_source = "<h1>Index page</h1><child-component /><child-component />
<style enhanced>
h1 {
  font-weight: extrabold;
}
</style>";
        let my_button_source = "<button>Click me!</button>
<style enhanced>
button:hover {
  background-color: antiquewhite;
  color: antiquewhite;
}
</style>";

        let (css_bundle, compiled) = compile_bundle(index_source, my_button_source);

        assert_eq!(compiled.unwrap(), "<h1 data-p-fd1ea890>Index page</h1><button data-p-7bcfbb98>Click me!</button>\n<button data-p-7bcfbb98>Click me!</button>\n\n");
        assert_eq!(css_bundle.finish().unwrap(), "h1:where([data-p-fd1ea890]){font-weight:extrabold}button:hover:where([data-p-7bcfbb98]){color:#faebd7;background-color:#faebd7}");

        let my_button_source = "<button>Click me!</button>
<style enhanced>
button:hover {
  background-color: antiquewhite;
  > * {
    color: antiquewhite;
  }
}
</style>";

        let (css_bundle, compiled) = compile_bundle(index_source, my_button_source);

        assert_eq!(compiled.unwrap(), "<h1 data-p-fd1ea890>Index page</h1><button data-p-7bcfbb98>Click me!</button>\n<button data-p-7bcfbb98>Click me!</button>\n\n");
        assert_eq!(css_bundle.finish().unwrap(), "h1:where([data-p-fd1ea890]){font-weight:extrabold}button:hover:where([data-p-7bcfbb98]){background-color:#faebd7}button:hover:where([data-p-7bcfbb98])>:where([data-p-7bcfbb98]){color:#faebd7}");
    }

    #[test]
    fn ensure_the_whole_selector_is_modified() {
        let index_source = "<h1>Index page</h1><child-component />
<style enhanced>
h1 {
  font-weight: extrabold;
}
</style>";
        let my_hero_source = r#"<div class="hero">
  <div class="inner-box">
    <p>Some text</p>
  </div>

  <img src="/404.png">
</div>
<style enhanced>
  .hero {
    padding: 2rem;
  }

  .hero > * {
    border: solid 1px red;
  }
</style>"#;

        let (css_bundle, compiled) = compile_bundle(index_source, my_hero_source);

        assert_eq!(
            compiled.unwrap(),
            r#"<h1 data-p-fd1ea890>Index page</h1><div class="hero" data-p-7bcfbb98>
  <div class="inner-box" data-p-7bcfbb98>
    <p data-p-7bcfbb98>Some text</p>
  </div>

  <img src="/404.png" data-p-7bcfbb98>
</div>

"#
        );
        assert_eq!(css_bundle.finish().unwrap(), "h1:where([data-p-fd1ea890]){font-weight:extrabold}.hero:where([data-p-7bcfbb98]){padding:2rem}.hero:where([data-p-7bcfbb98])>:where([data-p-7bcfbb98]){border:1px solid red}");
    }

    #[test]
    fn slots_can_be_enhanced() {
        let index_source = r#"<h1>Index page</h1><child-component>
  <div class="inner-box">
    <p>Some text</p>
  </div>

  <img src="/404.png">
</child-component>
<style enhanced>
h1 {
  font-weight: extrabold;
}
</style>"#;
        let my_hero_source = r#"<div class="hero">
  <slot></slot>
</div>
<style enhanced enhanced-slots>
  .hero {
    padding: 2rem;
  }

  .hero > * {
    border: solid 1px red;
  }
</style>"#;

        let (css_bundle, compiled) = compile_bundle(index_source, my_hero_source);

        assert_eq!(
            compiled.unwrap(),
            r#"<h1 data-p-fd1ea890>Index page</h1><div class="hero" data-p-7bcfbb98>
  
  <div class="inner-box" data-p-fd1ea890 data-p-7bcfbb98>
    <p data-p-fd1ea890 data-p-7bcfbb98>Some text</p>
  </div>

  <img src="/404.png" data-p-fd1ea890 data-p-7bcfbb98>

</div>

"#
        );
        assert_eq!(css_bundle.finish().unwrap(), "h1:where([data-p-fd1ea890]){font-weight:extrabold}.hero:where([data-p-7bcfbb98]){padding:2rem}.hero:where([data-p-7bcfbb98])>:where([data-p-7bcfbb98]){border:1px solid red}");
    }
}