hyperchad_renderer 0.3.0

HyperChad renderer package
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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
//! `HyperChad` renderer abstractions and core types.
//!
//! This crate provides the core rendering infrastructure for `HyperChad` applications,
//! including traits for implementing custom renderers, view composition types for
//! building dynamic UIs, and utilities for asset management, canvas operations, and
//! viewport handling.
//!
//! # Features
//!
//! * `assets` - Static asset serving and routing support
//! * `canvas` - Canvas drawing operations and updates
//! * `html` - HTML tag rendering with hyperchad transformations
//! * `json` - JSON response content support
//! * `viewport` - Viewport visibility calculations
//! * `viewport-immediate` - Immediate mode viewport rendering
//! * `viewport-retained` - Retained mode viewport rendering
//!
//! # Core Types
//!
//! * [`Renderer`] - Async trait for implementing custom renderers
//! * [`View`] - Unified view structure for full pages and partial updates
//! * [`Content`] - Response content enum (HTML views, JSON, or raw data)
//! * [`RendererEvent`] - Events emitted by renderers
//!
//! # Examples
//!
//! Creating a view with primary content and fragments:
//!
//! ```rust
//! use hyperchad_renderer::{View, transformer::Container};
//!
//! # fn main() {
//! let view = View::builder()
//!     .with_primary(Container::default())
//!     .build();
//! # }
//! ```

#![cfg_attr(feature = "fail-on-warnings", deny(warnings))]
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
#![allow(clippy::multiple_crate_versions)]

#[cfg(feature = "assets")]
pub mod assets;
#[cfg(feature = "canvas")]
pub mod canvas;
#[cfg(feature = "viewport")]
pub mod viewport;

use async_trait::async_trait;
use bytes::Bytes;
pub use hyperchad_color::Color;
use hyperchad_transformer::{Container, ResponsiveTrigger, html::ParseError, models::Selector};
pub use switchy_async::runtime::Handle;

pub use hyperchad_transformer as transformer;

/// Events that can be emitted by a renderer
#[derive(Debug)]
pub enum RendererEvent {
    /// View content to render
    View(Box<View>),
    /// Canvas update event
    #[cfg(feature = "canvas")]
    CanvasUpdate(canvas::CanvasUpdate),
    /// Generic event with optional value
    Event {
        /// Event name
        name: String,
        /// Optional event value
        value: Option<String>,
    },
}

/// Response content that can be returned to the client
#[derive(Debug, Clone)]
pub enum Content {
    /// HTML view content
    View(Box<View>),
    /// JSON response content
    #[cfg(feature = "json")]
    Json(serde_json::Value),
    /// Raw response with custom content type
    Raw {
        /// Response data
        data: Bytes,
        /// HTTP content type
        content_type: String,
    },
}

impl Content {
    /// Create a `ContentBuilder`
    #[must_use]
    pub fn builder() -> ContentBuilder {
        ContentBuilder::default()
    }

    /// Create a `Content::View` from any type that can be converted to a `View`.
    ///
    /// # Errors
    ///
    /// * If the `view` fails to convert to a `View`
    pub fn try_view<T: TryInto<View>>(view: T) -> Result<Self, T::Error> {
        Ok(Self::View(Box::new(view.try_into()?)))
    }
}

/// Container with selector for targeted DOM replacement
#[derive(Debug, Clone)]
pub struct ReplaceContainer {
    /// CSS selector to target DOM element for replacement
    pub selector: Selector,
    /// Container content to replace the target with
    pub container: Container,
}

impl From<Container> for ReplaceContainer {
    fn from(container: Container) -> Self {
        Self {
            selector: container
                .str_id
                .as_ref()
                .map_or(Selector::SelfTarget, |id| Selector::Id(id.clone())),
            container,
        }
    }
}

impl From<Vec<Container>> for ReplaceContainer {
    fn from(container: Vec<Container>) -> Self {
        Self {
            selector: Selector::SelfTarget,
            container: container.into(),
        }
    }
}

/// Unified view structure - handles full pages, partials, and composite responses
#[derive(Debug, Clone, Default)]
pub struct View {
    /// Primary content (swaps to triggering element)
    /// None = fragments-only response
    pub primary: Option<Container>,

    /// Additional containers to swap by ID
    /// Each container MUST have an `id` attribute
    /// Client finds DOM elements with matching IDs and swaps them
    pub fragments: Vec<ReplaceContainer>,

    /// Element selectors to delete from the DOM
    /// Client finds DOM elements with matching selectors and removes them
    pub delete_selectors: Vec<Selector>,
}

impl View {
    /// Create a `ViewBuilder` for constructing a `View` with primary content, fragments, and delete selectors
    #[must_use]
    pub fn builder() -> ViewBuilder {
        ViewBuilder::default()
    }
}

/// Builder for constructing `View` instances
#[derive(Debug, Default)]
pub struct ViewBuilder {
    primary: Option<Container>,
    fragments: Vec<ReplaceContainer>,
    delete_selectors: Vec<Selector>,
}

impl ViewBuilder {
    /// Set the primary view
    #[must_use]
    pub fn with_primary(mut self, view: impl Into<Container>) -> Self {
        self.primary = Some(view.into());
        self
    }

    /// Set the primary view
    pub fn primary(&mut self, view: impl Into<Container>) -> &mut Self {
        self.primary = Some(view.into());
        self
    }

    /// Add a fragment container (must have an ID)
    #[must_use]
    pub fn with_fragment(mut self, container: impl Into<ReplaceContainer>) -> Self {
        self.fragments.push(container.into());
        self
    }

    /// Add a fragment container (must have an ID)
    pub fn fragment(&mut self, container: impl Into<ReplaceContainer>) -> &mut Self {
        self.fragments.push(container.into());
        self
    }

    /// Add multiple fragment containers
    #[must_use]
    pub fn with_fragments(
        mut self,
        containers: impl IntoIterator<Item = impl Into<ReplaceContainer>>,
    ) -> Self {
        self.fragments
            .extend(containers.into_iter().map(Into::into));
        self
    }

    /// Add multiple fragment containers
    pub fn fragments(
        &mut self,
        containers: impl IntoIterator<Item = impl Into<ReplaceContainer>>,
    ) -> &mut Self {
        self.fragments
            .extend(containers.into_iter().map(Into::into));
        self
    }

    /// Add a delete selector
    #[must_use]
    pub fn with_delete_selector(mut self, selector: impl Into<Selector>) -> Self {
        self.delete_selectors.push(selector.into());
        self
    }

    /// Add a delete selector
    pub fn delete_selector(&mut self, selector: impl Into<Selector>) -> &mut Self {
        self.delete_selectors.push(selector.into());
        self
    }

    /// Add multiple delete selectors
    #[must_use]
    pub fn with_delete_selectors(
        mut self,
        selectors: impl IntoIterator<Item = impl Into<Selector>>,
    ) -> Self {
        self.delete_selectors
            .extend(selectors.into_iter().map(Into::into));
        self
    }

    /// Add multiple delete selectors
    pub fn delete_selectors(
        &mut self,
        selectors: impl IntoIterator<Item = impl Into<Selector>>,
    ) -> &mut Self {
        self.delete_selectors
            .extend(selectors.into_iter().map(Into::into));
        self
    }

    /// Build the View
    #[must_use]
    pub fn build(self) -> View {
        View {
            primary: self.primary,
            fragments: self.fragments,
            delete_selectors: self.delete_selectors,
        }
    }
}

/// Builder for constructing `Content` instances
///
/// Provides a fluent interface for building `Content::View` responses with
/// primary content, fragments, and delete selectors. Automatically wraps
/// the resulting `View` in a `Content` variant when built.
#[derive(Debug, Default)]
pub struct ContentBuilder {
    builder: ViewBuilder,
}

impl ContentBuilder {
    /// Set the primary view
    #[must_use]
    pub fn with_primary(mut self, view: impl Into<Container>) -> Self {
        self.builder = self.builder.with_primary(view);
        self
    }

    /// Set the primary view
    pub fn primary(&mut self, view: impl Into<Container>) -> &mut Self {
        self.builder.primary(view);
        self
    }

    /// Add a fragment container (must have an ID)
    #[must_use]
    pub fn with_fragment(mut self, container: impl Into<ReplaceContainer>) -> Self {
        self.builder = self.builder.with_fragment(container);
        self
    }

    /// Add a fragment container (must have an ID)
    pub fn fragment(&mut self, container: impl Into<ReplaceContainer>) -> &mut Self {
        self.builder.fragment(container);
        self
    }

    /// Add multiple fragment containers
    #[must_use]
    pub fn with_fragments(
        mut self,
        containers: impl IntoIterator<Item = impl Into<ReplaceContainer>>,
    ) -> Self {
        self.builder = self.builder.with_fragments(containers);
        self
    }

    /// Add multiple fragment containers
    pub fn fragments(
        &mut self,
        containers: impl IntoIterator<Item = impl Into<ReplaceContainer>>,
    ) -> &mut Self {
        self.builder.fragments(containers);
        self
    }

    /// Add a delete selector
    #[must_use]
    pub fn with_delete_selector(mut self, selector: impl Into<Selector>) -> Self {
        self.builder = self.builder.with_delete_selector(selector);
        self
    }

    /// Add a delete selector
    pub fn delete_selector(&mut self, selector: impl Into<Selector>) -> &mut Self {
        self.builder.delete_selector(selector);
        self
    }

    /// Add multiple delete selectors
    #[must_use]
    pub fn with_delete_selectors(
        mut self,
        selectors: impl IntoIterator<Item = impl Into<Selector>>,
    ) -> Self {
        self.builder = self.builder.with_delete_selectors(selectors);
        self
    }

    /// Add multiple delete selectors
    pub fn delete_selectors(
        &mut self,
        selectors: impl IntoIterator<Item = impl Into<Selector>>,
    ) -> &mut Self {
        self.builder.delete_selectors(selectors);
        self
    }

    /// Build the Content
    #[must_use]
    pub fn build(self) -> Content {
        Content::View(Box::new(self.builder.build()))
    }
}

#[cfg(feature = "json")]
impl TryFrom<serde_json::Value> for Content {
    type Error = serde_json::Error;

    fn try_from(value: serde_json::Value) -> Result<Self, Self::Error> {
        Ok(Self::Json(value))
    }
}

impl<'a> TryFrom<&'a str> for Content {
    type Error = ParseError;

    fn try_from(value: &'a str) -> Result<Self, Self::Error> {
        Ok(Self::Raw {
            data: value.as_bytes().to_vec().into(),
            content_type: "text/html".to_string(),
        })
    }
}

impl TryFrom<String> for Content {
    type Error = ParseError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        value.as_str().try_into()
    }
}

impl From<Container> for Content {
    fn from(value: Container) -> Self {
        Self::View(Box::new(View {
            primary: Some(value),
            fragments: vec![],
            delete_selectors: vec![],
        }))
    }
}

impl From<Vec<Container>> for Content {
    fn from(value: Vec<Container>) -> Self {
        Container {
            children: value,
            ..Default::default()
        }
        .into()
    }
}

impl From<View> for Content {
    fn from(value: View) -> Self {
        Self::View(Box::new(value))
    }
}

impl<'a> TryFrom<&'a str> for View {
    type Error = ParseError;

    fn try_from(value: &'a str) -> Result<Self, Self::Error> {
        Ok(Self {
            primary: Some(value.try_into()?),
            fragments: vec![],
            delete_selectors: vec![],
        })
    }
}

impl TryFrom<String> for View {
    type Error = ParseError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Ok(Self {
            primary: Some(value.try_into()?),
            fragments: vec![],
            delete_selectors: vec![],
        })
    }
}

impl From<Container> for View {
    fn from(value: Container) -> Self {
        Self {
            primary: Some(value),
            fragments: vec![],
            delete_selectors: vec![],
        }
    }
}

impl From<Vec<Container>> for View {
    fn from(value: Vec<Container>) -> Self {
        Self {
            primary: Some(value.into()),
            fragments: vec![],
            delete_selectors: vec![],
        }
    }
}

/// Trait for running a renderer in a blocking manner
pub trait RenderRunner: Send + Sync {
    /// # Errors
    ///
    /// * If the renderer fails to run
    fn run(&mut self) -> Result<(), Box<dyn std::error::Error + Send + 'static>>;
}

/// Trait for converting a value into a `RenderRunner`
pub trait ToRenderRunner {
    /// # Errors
    ///
    /// * If failed to convert the value to a `RenderRunner`
    fn to_runner(
        self,
        handle: Handle,
    ) -> Result<Box<dyn RenderRunner>, Box<dyn std::error::Error + Send>>;
}

/// Trait for async renderer implementations
#[async_trait]
pub trait Renderer: ToRenderRunner + Send + Sync {
    /// Initialize the renderer with window dimensions and metadata.
    ///
    /// # Errors
    ///
    /// * If the `Renderer` implementation fails to start
    #[allow(clippy::too_many_arguments)]
    async fn init(
        &mut self,
        width: f32,
        height: f32,
        x: Option<i32>,
        y: Option<i32>,
        background: Option<Color>,
        title: Option<&str>,
        description: Option<&str>,
        viewport: Option<&str>,
    ) -> Result<(), Box<dyn std::error::Error + Send + 'static>>;

    /// Register a responsive trigger for media queries and breakpoint handling.
    fn add_responsive_trigger(&mut self, name: String, trigger: ResponsiveTrigger);

    /// Emit a custom event to the renderer's event system.
    ///
    /// # Errors
    ///
    /// * If the `Renderer` implementation fails to emit the event
    async fn emit_event(
        &self,
        event_name: String,
        event_value: Option<String>,
    ) -> Result<(), Box<dyn std::error::Error + Send + 'static>>;

    /// Render a view to the output display.
    ///
    /// # Errors
    ///
    /// * If the `Renderer` implementation fails to render the view
    async fn render(&self, view: View) -> Result<(), Box<dyn std::error::Error + Send + 'static>>;

    /// Render a canvas update with drawing operations.
    ///
    /// # Errors
    ///
    /// * If the `Renderer` implementation fails to render the canvas update
    ///
    /// # Panics
    ///
    /// * Always panics in the default implementation because canvas rendering is not implemented
    #[cfg(feature = "canvas")]
    async fn render_canvas(
        &self,
        update: canvas::CanvasUpdate,
    ) -> Result<(), Box<dyn std::error::Error + Send + 'static>> {
        unimplemented!("Unable to render canvas update={update:?}")
    }
}

/// Trait for rendering HTML elements with hyperchad transformations
#[cfg(feature = "html")]
pub trait HtmlTagRenderer {
    /// Add a responsive trigger for media queries
    fn add_responsive_trigger(&mut self, name: String, trigger: ResponsiveTrigger);

    /// Render element attributes to HTML output.
    ///
    /// # Errors
    ///
    /// * If the `HtmlTagRenderer` fails to write the element attributes
    fn element_attrs_to_html(
        &self,
        f: &mut dyn std::io::Write,
        container: &Container,
        is_flex_child: bool,
    ) -> Result<(), std::io::Error>;

    /// Render reactive media query conditions to CSS output.
    ///
    /// # Errors
    ///
    /// * If the `HtmlTagRenderer` fails to write the css media-queries
    fn reactive_conditions_to_css(
        &self,
        _f: &mut dyn std::io::Write,
        _container: &Container,
    ) -> Result<(), std::io::Error> {
        Ok(())
    }

    /// Generate partial HTML for a container without full page structure.
    fn partial_html(
        &self,
        headers: &std::collections::BTreeMap<String, String>,
        container: &Container,
        content: String,
        viewport: Option<&str>,
        background: Option<Color>,
    ) -> String;

    /// Generate complete HTML document with full page structure and metadata.
    #[allow(clippy::too_many_arguments)]
    fn root_html(
        &self,
        headers: &std::collections::BTreeMap<String, String>,
        container: &Container,
        content: String,
        viewport: Option<&str>,
        background: Option<Color>,
        title: Option<&str>,
        description: Option<&str>,
        css_urls: &[String],
        css_paths: &[String],
        inline_css: &[String],
    ) -> String;
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test_log::test]
    fn test_replace_container_from_container_with_id() {
        let container = Container {
            str_id: Some("test-id".to_string()),
            ..Default::default()
        };

        let replace = ReplaceContainer::from(container.clone());

        assert_eq!(replace.selector, Selector::Id("test-id".to_string()));
        assert_eq!(replace.container.str_id, container.str_id);
    }

    #[test_log::test]
    fn test_replace_container_from_container_without_id() {
        let container = Container {
            str_id: None,
            ..Default::default()
        };

        let replace = ReplaceContainer::from(container);

        assert_eq!(replace.selector, Selector::SelfTarget);
    }

    #[test_log::test]
    fn test_replace_container_from_vec_containers() {
        let containers = vec![
            Container {
                str_id: Some("first".to_string()),
                ..Default::default()
            },
            Container {
                str_id: Some("second".to_string()),
                ..Default::default()
            },
        ];

        let replace = ReplaceContainer::from(containers);

        assert_eq!(replace.selector, Selector::SelfTarget);
        assert_eq!(replace.container.children.len(), 2);
    }

    #[test_log::test]
    fn test_view_builder_with_primary() {
        let container = Container::default();
        let view = View::builder().with_primary(container).build();

        assert!(view.primary.is_some());
        assert!(view.fragments.is_empty());
        assert!(view.delete_selectors.is_empty());
    }

    #[test_log::test]
    fn test_view_builder_with_fragments() {
        let fragment1 = Container {
            str_id: Some("frag1".to_string()),
            ..Default::default()
        };
        let fragment2 = Container {
            str_id: Some("frag2".to_string()),
            ..Default::default()
        };

        let view = View::builder()
            .with_fragment(fragment1)
            .with_fragment(fragment2)
            .build();

        assert!(view.primary.is_none());
        assert_eq!(view.fragments.len(), 2);
    }

    #[test_log::test]
    fn test_view_builder_with_delete_selectors() {
        let view = View::builder()
            .with_delete_selector(Selector::Id("remove-me".to_string()))
            .with_delete_selector(Selector::Class("hidden".to_string()))
            .build();

        assert_eq!(view.delete_selectors.len(), 2);
    }

    #[test_log::test]
    fn test_view_builder_mutable_methods() {
        let mut builder = View::builder();
        builder
            .primary(Container::default())
            .fragment(Container {
                str_id: Some("test".to_string()),
                ..Default::default()
            })
            .delete_selector(Selector::Id("del".to_string()));

        let view = builder.build();

        assert!(view.primary.is_some());
        assert_eq!(view.fragments.len(), 1);
        assert_eq!(view.delete_selectors.len(), 1);
    }

    #[test_log::test]
    fn test_content_builder_creates_view_content() {
        let container = Container::default();
        let content = Content::builder().with_primary(container).build();

        match content {
            Content::View(view) => {
                assert!(view.primary.is_some());
            }
            #[cfg(feature = "json")]
            Content::Json(_) => panic!("Expected View, got Json"),
            Content::Raw { .. } => panic!("Expected View, got Raw"),
        }
    }

    #[test_log::test]
    fn test_content_from_container() {
        let container = Container::default();
        let content: Content = container.into();

        match content {
            Content::View(view) => {
                assert!(view.primary.is_some());
                assert!(view.fragments.is_empty());
            }
            #[cfg(feature = "json")]
            Content::Json(_) => panic!("Expected View, got Json"),
            Content::Raw { .. } => panic!("Expected View, got Raw"),
        }
    }

    #[test_log::test]
    fn test_content_from_vec_containers() {
        let containers = vec![Container::default(), Container::default()];
        let content: Content = containers.into();

        match content {
            Content::View(view) => {
                assert!(view.primary.is_some());
                if let Some(primary) = &view.primary {
                    assert_eq!(primary.children.len(), 2);
                }
            }
            #[cfg(feature = "json")]
            Content::Json(_) => panic!("Expected View, got Json"),
            Content::Raw { .. } => panic!("Expected View, got Raw"),
        }
    }

    #[test_log::test]
    fn test_content_from_view() {
        let view = View::builder().with_primary(Container::default()).build();
        let content: Content = view.into();

        match content {
            Content::View(boxed_view) => {
                assert!(boxed_view.primary.is_some());
            }
            #[cfg(feature = "json")]
            Content::Json(_) => panic!("Expected View, got Json"),
            Content::Raw { .. } => panic!("Expected View, got Raw"),
        }
    }

    #[test_log::test]
    fn test_content_try_from_str() {
        let html = "<div>test</div>";
        let content = Content::try_from(html);

        assert!(content.is_ok());
        match content.unwrap() {
            Content::Raw { data, content_type } => {
                assert_eq!(data.as_ref(), html.as_bytes());
                assert_eq!(content_type, "text/html");
            }
            #[cfg(feature = "json")]
            Content::Json(_) => panic!("Expected Raw, got Json"),
            Content::View(_) => panic!("Expected Raw, got View"),
        }
    }

    #[test_log::test]
    fn test_content_try_from_string() {
        let html = String::from("<div>test</div>");
        let content = Content::try_from(html);

        assert!(content.is_ok());
    }

    #[test_log::test]
    fn test_view_from_container() {
        let container = Container::default();
        let view: View = container.into();

        assert!(view.primary.is_some());
        assert!(view.fragments.is_empty());
        assert!(view.delete_selectors.is_empty());
    }

    #[test_log::test]
    fn test_view_from_vec_containers() {
        let containers = vec![Container::default(), Container::default()];
        let view: View = containers.into();

        assert!(view.primary.is_some());
        if let Some(primary) = &view.primary {
            assert_eq!(primary.children.len(), 2);
        }
    }

    #[test_log::test]
    fn test_view_builder_with_fragments_batch() {
        let fragments = vec![
            Container {
                str_id: Some("frag1".to_string()),
                ..Default::default()
            },
            Container {
                str_id: Some("frag2".to_string()),
                ..Default::default()
            },
            Container {
                str_id: Some("frag3".to_string()),
                ..Default::default()
            },
        ];

        let view = View::builder().with_fragments(fragments).build();

        assert_eq!(view.fragments.len(), 3);
    }

    #[test_log::test]
    fn test_view_builder_fragments_mutable_batch() {
        let fragments = vec![
            Container {
                str_id: Some("a".to_string()),
                ..Default::default()
            },
            Container {
                str_id: Some("b".to_string()),
                ..Default::default()
            },
        ];

        let mut builder = View::builder();
        builder.fragments(fragments);
        let view = builder.build();

        assert_eq!(view.fragments.len(), 2);
    }

    #[test_log::test]
    fn test_view_builder_with_delete_selectors_batch() {
        let selectors = vec![
            Selector::Id("del1".to_string()),
            Selector::Class("del2".to_string()),
            Selector::SelfTarget,
        ];

        let view = View::builder().with_delete_selectors(selectors).build();

        assert_eq!(view.delete_selectors.len(), 3);
    }

    #[test_log::test]
    fn test_view_builder_delete_selectors_mutable_batch() {
        let selectors = vec![Selector::Id("x".to_string()), Selector::Id("y".to_string())];

        let mut builder = View::builder();
        builder.delete_selectors(selectors);
        let view = builder.build();

        assert_eq!(view.delete_selectors.len(), 2);
    }

    #[test_log::test]
    fn test_content_builder_mutable_fragment() {
        let mut builder = Content::builder();
        builder.fragment(Container {
            str_id: Some("frag".to_string()),
            ..Default::default()
        });
        let content = builder.build();

        match content {
            Content::View(view) => {
                assert_eq!(view.fragments.len(), 1);
            }
            #[cfg(feature = "json")]
            Content::Json(_) => panic!("Expected View, got Json"),
            Content::Raw { .. } => panic!("Expected View, got Raw"),
        }
    }

    #[test_log::test]
    fn test_content_builder_mutable_delete_selector() {
        let mut builder = Content::builder();
        builder.delete_selector(Selector::Id("remove".to_string()));
        let content = builder.build();

        match content {
            Content::View(view) => {
                assert_eq!(view.delete_selectors.len(), 1);
            }
            #[cfg(feature = "json")]
            Content::Json(_) => panic!("Expected View, got Json"),
            Content::Raw { .. } => panic!("Expected View, got Raw"),
        }
    }

    #[test_log::test]
    fn test_content_builder_with_fragments_batch() {
        let fragments = vec![
            Container {
                str_id: Some("f1".to_string()),
                ..Default::default()
            },
            Container {
                str_id: Some("f2".to_string()),
                ..Default::default()
            },
        ];

        let content = Content::builder().with_fragments(fragments).build();

        match content {
            Content::View(view) => {
                assert_eq!(view.fragments.len(), 2);
            }
            #[cfg(feature = "json")]
            Content::Json(_) => panic!("Expected View, got Json"),
            Content::Raw { .. } => panic!("Expected View, got Raw"),
        }
    }

    #[test_log::test]
    fn test_content_builder_fragments_mutable_batch() {
        let fragments = vec![Container {
            str_id: Some("test".to_string()),
            ..Default::default()
        }];

        let mut builder = Content::builder();
        builder.fragments(fragments);
        let content = builder.build();

        match content {
            Content::View(view) => {
                assert_eq!(view.fragments.len(), 1);
            }
            #[cfg(feature = "json")]
            Content::Json(_) => panic!("Expected View, got Json"),
            Content::Raw { .. } => panic!("Expected View, got Raw"),
        }
    }

    #[test_log::test]
    fn test_content_builder_with_delete_selectors_batch() {
        let selectors = vec![
            Selector::Id("a".to_string()),
            Selector::Class("b".to_string()),
        ];

        let content = Content::builder().with_delete_selectors(selectors).build();

        match content {
            Content::View(view) => {
                assert_eq!(view.delete_selectors.len(), 2);
            }
            #[cfg(feature = "json")]
            Content::Json(_) => panic!("Expected View, got Json"),
            Content::Raw { .. } => panic!("Expected View, got Raw"),
        }
    }

    #[test_log::test]
    fn test_content_builder_delete_selectors_mutable_batch() {
        let selectors = vec![Selector::SelfTarget];

        let mut builder = Content::builder();
        builder.delete_selectors(selectors);
        let content = builder.build();

        match content {
            Content::View(view) => {
                assert_eq!(view.delete_selectors.len(), 1);
            }
            #[cfg(feature = "json")]
            Content::Json(_) => panic!("Expected View, got Json"),
            Content::Raw { .. } => panic!("Expected View, got Raw"),
        }
    }

    #[test_log::test]
    fn test_content_try_view_with_container() {
        let container = Container::default();
        let content = Content::try_view(container);

        assert!(content.is_ok());
        match content.unwrap() {
            Content::View(view) => {
                assert!(view.primary.is_some());
            }
            #[cfg(feature = "json")]
            Content::Json(_) => panic!("Expected View, got Json"),
            Content::Raw { .. } => panic!("Expected View, got Raw"),
        }
    }

    #[test_log::test]
    fn test_content_try_view_with_view() {
        let view = View::builder()
            .with_primary(Container::default())
            .with_fragment(Container {
                str_id: Some("frag".to_string()),
                ..Default::default()
            })
            .build();

        let content = Content::try_view(view);

        assert!(content.is_ok());
        match content.unwrap() {
            Content::View(boxed_view) => {
                assert!(boxed_view.primary.is_some());
                assert_eq!(boxed_view.fragments.len(), 1);
            }
            #[cfg(feature = "json")]
            Content::Json(_) => panic!("Expected View, got Json"),
            Content::Raw { .. } => panic!("Expected View, got Raw"),
        }
    }

    #[test_log::test]
    fn test_view_try_from_valid_html_str() {
        let html = "<div>Hello</div>";
        let view = View::try_from(html);

        assert!(view.is_ok());
        let view = view.unwrap();
        assert!(view.primary.is_some());
        assert!(view.fragments.is_empty());
        assert!(view.delete_selectors.is_empty());
    }

    #[test_log::test]
    fn test_view_try_from_valid_html_string() {
        let html = String::from("<span>World</span>");
        let view = View::try_from(html);

        assert!(view.is_ok());
        let view = view.unwrap();
        assert!(view.primary.is_some());
    }

    #[test_log::test]
    fn test_view_builder_combined_operations() {
        let view = View::builder()
            .with_primary(Container::default())
            .with_fragment(Container {
                str_id: Some("frag1".to_string()),
                ..Default::default()
            })
            .with_fragments(vec![Container {
                str_id: Some("frag2".to_string()),
                ..Default::default()
            }])
            .with_delete_selector(Selector::Id("del1".to_string()))
            .with_delete_selectors(vec![Selector::Class("del2".to_string())])
            .build();

        assert!(view.primary.is_some());
        assert_eq!(view.fragments.len(), 2);
        assert_eq!(view.delete_selectors.len(), 2);
    }

    #[test_log::test]
    fn test_content_builder_combined_operations() {
        let content = Content::builder()
            .with_primary(Container::default())
            .with_fragment(Container {
                str_id: Some("f1".to_string()),
                ..Default::default()
            })
            .with_delete_selector(Selector::Id("d1".to_string()))
            .build();

        match content {
            Content::View(view) => {
                assert!(view.primary.is_some());
                assert_eq!(view.fragments.len(), 1);
                assert_eq!(view.delete_selectors.len(), 1);
            }
            #[cfg(feature = "json")]
            Content::Json(_) => panic!("Expected View, got Json"),
            Content::Raw { .. } => panic!("Expected View, got Raw"),
        }
    }

    #[test_log::test]
    fn test_replace_container_selector_types() {
        // Test with various selector types via ReplaceContainer
        let container_with_id = Container {
            str_id: Some("my-id".to_string()),
            ..Default::default()
        };
        let replace = ReplaceContainer::from(container_with_id);
        assert!(matches!(replace.selector, Selector::Id(_)));

        let container_no_id = Container {
            str_id: None,
            ..Default::default()
        };
        let replace = ReplaceContainer::from(container_no_id);
        assert!(matches!(replace.selector, Selector::SelfTarget));
    }
}