grio 0.1.1

A fast, pure Rust alternative to Gradio with zero frontend dependencies
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
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
//! Composants de médias et vision par ordinateur (Image, ImageEditor, Audio, Video, Gallery, etc.).

use serde_json::{json, Value};

use super::{Component, Role};

/// Image : **upload** (entrée, interactive) et/ou **affichage** (serveur → client
/// via `ctx.set`). La valeur transportée est une **data URL**
/// (`data:image/png;base64,…`).
#[derive(Clone, Debug)]
pub struct Image {
    id: String,
    label: String,
    value: String,
    interactive: bool,
    out: bool,
}

impl Image {
    /// Crée une image, avec son identifiant. Entrée (upload) par défaut.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            label: String::new(),
            value: String::new(),
            interactive: true,
            out: false,
        }
    }
    /// Étiquette affichée au-dessus.
    pub fn label(mut self, l: impl Into<String>) -> Self {
        self.label = l.into();
        self
    }
    /// Data URL initiale affichée.
    pub fn value(mut self, v: impl Into<String>) -> Self {
        self.value = v.into();
        self
    }
    /// Ouvre/ferme le contrôle d'upload (fichier ou glisser-déposer).
    pub fn interactive(mut self, on: bool) -> Self {
        self.interactive = on;
        self
    }
    /// Déclare l'image **sortie** (résultat calculé, pas d'upload).
    pub fn output(mut self) -> Self {
        self.out = true;
        self
    }
    /// Déclare l'image **entrée** (upload — comportement par défaut).
    pub fn input(mut self) -> Self {
        self.out = false;
        self
    }
}

impl Component for Image {
    fn id(&self) -> &str {
        &self.id
    }
    fn kind(&self) -> &'static str {
        "image"
    }
    fn role(&self) -> Role {
        if self.out {
            Role::Output
        } else {
            Role::Input
        }
    }
    fn props(&self) -> Value {
        json!({ "label": self.label, "value": self.value, "interactive": self.interactive })
    }
}

/// Éditeur d'image **côté client** : pinceau, gomme, formes (rect/ligne/
/// flèche), rognage (crop), rotation, filtres, annuler/rétablir, zoom/pan et
/// **calques** (2 par défaut, `.layers(n)`).
#[derive(Clone, Debug)]
pub struct ImageEditor {
    id: String,
    label: String,
    value: String,
    interactive: bool,
    layers: usize,
    brush: bool,
    crop: bool,
    shapes: bool,
    filters: bool,
    rotflip: bool,
    out: bool,
}

impl ImageEditor {
    /// Crée un éditeur d'image, avec son identifiant. Entrée par défaut.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            label: String::new(),
            value: String::new(),
            interactive: true,
            layers: 2,
            brush: true,
            crop: true,
            shapes: true,
            filters: true,
            rotflip: true,
            out: false,
        }
    }
    /// Étiquette affichée au-dessus.
    pub fn label(mut self, l: impl Into<String>) -> Self {
        self.label = l.into();
        self
    }
    /// Image d'arrière-plan initiale (data URL) chargée dans le canvas.
    pub fn value(mut self, v: impl Into<String>) -> Self {
        self.value = v.into();
        self
    }
    /// Autorise ou non l'édition (affichage seul si `false`).
    pub fn interactive(mut self, on: bool) -> Self {
        self.interactive = on;
        self
    }
    /// Nombre de **calques** d'annotation (1..=4, défaut 2).
    pub fn layers(mut self, n: usize) -> Self {
        self.layers = n.clamp(1, 4);
        self
    }
    /// Active le pinceau et la gomme (défaut : `true`).
    pub fn brush(mut self, on: bool) -> Self {
        self.brush = on;
        self
    }
    /// Active le **rognage** (crop) (défaut : `true`).
    pub fn crop(mut self, on: bool) -> Self {
        self.crop = on;
        self
    }
    /// Active les formes : rectangle, ligne, flèche (défaut : `true`).
    pub fn shapes(mut self, on: bool) -> Self {
        self.shapes = on;
        self
    }
    /// Active les filtres (niveaux de gris, inversion, luminosité, flou).
    pub fn filters(mut self, on: bool) -> Self {
        self.filters = on;
        self
    }
    /// Active la rotation 90° (défaut : `true`).
    pub fn rotflip(mut self, on: bool) -> Self {
        self.rotflip = on;
        self
    }
    /// Déclare l'éditeur **sortie** (affichage seul de `value`).
    pub fn output(mut self) -> Self {
        self.out = true;
        self
    }
    /// Déclare l'éditeur **entrée** (édition — par défaut).
    pub fn input(mut self) -> Self {
        self.out = false;
        self
    }
}

impl Component for ImageEditor {
    fn id(&self) -> &str {
        &self.id
    }
    fn kind(&self) -> &'static str {
        "imageeditor"
    }
    fn role(&self) -> Role {
        if self.out {
            Role::Output
        } else {
            Role::Input
        }
    }
    fn props(&self) -> Value {
        json!({
            "label": self.label, "value": self.value, "interactive": self.interactive,
            "layers": self.layers, "brush": self.brush, "crop": self.crop,
            "shapes": self.shapes, "filters": self.filters, "rotflip": self.rotflip
        })
    }
}

/// Audio : **upload** (entrée, interactive), **affichage/lecteur** (sortie) ou
/// **micro live** (`.live(true)`).
#[derive(Clone, Debug)]
pub struct Audio {
    id: String,
    label: String,
    value: String,
    interactive: bool,
    out: bool,
    live: bool,
}

impl Audio {
    /// Crée un audio, avec son identifiant. Entrée par défaut.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            label: String::new(),
            value: String::new(),
            interactive: true,
            out: false,
            live: false,
        }
    }
    /// Étiquette affichée au-dessus.
    pub fn label(mut self, l: impl Into<String>) -> Self {
        self.label = l.into();
        self
    }
    /// Data URL initiale.
    pub fn value(mut self, v: impl Into<String>) -> Self {
        self.value = v.into();
        self
    }
    /// Ouvre/ferme le contrôle d'upload.
    pub fn interactive(mut self, on: bool) -> Self {
        self.interactive = on;
        self
    }
    /// Déclare l'audio **sortie** (lecteur de résultats).
    pub fn output(mut self) -> Self {
        self.out = true;
        self
    }
    /// Déclare l'audio **entrée** (upload — par défaut).
    pub fn input(mut self) -> Self {
        self.out = false;
        self
    }
    /// Mode **micro live** : capture micro client et streaming de chunks.
    pub fn live(mut self, on: bool) -> Self {
        self.live = on;
        self
    }
}

impl Component for Audio {
    fn id(&self) -> &str {
        &self.id
    }
    fn kind(&self) -> &'static str {
        "audio"
    }
    fn role(&self) -> Role {
        if self.out {
            Role::Output
        } else {
            Role::Input
        }
    }
    fn props(&self) -> Value {
        json!({ "label": self.label, "value": self.value, "interactive": self.interactive, "live": self.live })
    }
}

/// Vidéo : **affichage/lecteur** (sortie, par défaut) ou **caméra live**
/// (`.live(true)`) ou **upload** (`.interactive(true)`).
#[derive(Clone, Debug)]
pub struct Video {
    id: String,
    label: String,
    value: String,
    interactive: bool,
    out: bool,
    live: bool,
}

impl Video {
    /// Crée une vidéo, avec son identifiant. Sortie (affichage) par défaut.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            label: String::new(),
            value: String::new(),
            interactive: false,
            out: true,
            live: false,
        }
    }
    /// Étiquette affichée au-dessus.
    pub fn label(mut self, l: impl Into<String>) -> Self {
        self.label = l.into();
        self
    }
    /// Data URL initiale (ou URL de flux).
    pub fn value(mut self, v: impl Into<String>) -> Self {
        self.value = v.into();
        self
    }
    /// Ouvre/ferme le contrôle d'upload.
    pub fn interactive(mut self, on: bool) -> Self {
        self.interactive = on;
        self
    }
    /// Déclare la vidéo **entrée** (upload).
    pub fn input(mut self) -> Self {
        self.out = false;
        self
    }
    /// Déclare la vidéo **sortie** (affichage — par défaut).
    pub fn output(mut self) -> Self {
        self.out = true;
        self
    }
    /// Mode **caméra live** : la caméra s'affiche en local et pousse des chunks.
    pub fn live(mut self, on: bool) -> Self {
        self.live = on;
        self
    }
}

impl Component for Video {
    fn id(&self) -> &str {
        &self.id
    }
    fn kind(&self) -> &'static str {
        "video"
    }
    fn role(&self) -> Role {
        if self.out {
            Role::Output
        } else {
            Role::Input
        }
    }
    fn props(&self) -> Value {
        json!({ "label": self.label, "value": self.value, "interactive": self.interactive, "live": self.live })
    }
}

/// Galerie d'images en grille (affichage et/ou upload multiple, avec lightbox/zoom).
#[derive(Clone, Debug)]
pub struct Gallery {
    id: String,
    label: String,
    value: Value,
    columns: usize,
    rows: Option<usize>,
    height: Option<String>,
    min_height: Option<String>,
    max_height: Option<String>,
    limit: Option<usize>,
    item_height: Option<String>,
    item_width: Option<String>,
    aspect_ratio: Option<String>,
    object_fit: String,
    allow_preview: bool,
    interactive: bool,
    upload: bool,
    out: bool,
}

impl Gallery {
    /// Crée une galerie, avec son identifiant. Entrée (upload) par défaut.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            label: String::new(),
            value: json!([]),
            columns: 3,
            rows: None,
            height: None,
            min_height: None,
            max_height: None,
            limit: None,
            item_height: None,
            item_width: None,
            aspect_ratio: None,
            object_fit: "cover".into(),
            allow_preview: true,
            interactive: true,
            upload: true,
            out: false,
        }
    }
    /// Étiquette/Titre affiché au-dessus de la galerie.
    pub fn label(mut self, l: impl Into<String>) -> Self {
        self.label = l.into();
        self
    }
    /// Alias pour label (titre).
    pub fn title(mut self, t: impl Into<String>) -> Self {
        self.label = t.into();
        self
    }
    /// Images initiales (data URLs ou URLs).
    pub fn value(mut self, items: &[&str]) -> Self {
        let v: Vec<String> = items.iter().map(|s| s.to_string()).collect();
        self.value = json!(v);
        self
    }
    /// Images initiales depuis une collection de Strings ou Data URLs.
    pub fn items(mut self, items: &[impl AsRef<str>]) -> Self {
        let v: Vec<String> = items.iter().map(|s| s.as_ref().to_string()).collect();
        self.value = json!(v);
        self
    }
    /// Images initiales depuis une collection d'objets sérialisables (`{image, caption}`).
    pub fn raw_items(mut self, items: impl serde::Serialize) -> Self {
        self.value = serde_json::to_value(items).unwrap_or_else(|_| json!([]));
        self
    }
    /// Nombre de colonnes de la grille.
    pub fn columns(mut self, n: usize) -> Self {
        self.columns = n.max(1);
        self
    }
    /// Nombre de lignes visibles simultanément (active le défilement si plus d'images).
    pub fn rows(mut self, n: usize) -> Self {
        self.rows = Some(n.max(1));
        self
    }
    /// Hauteur fixe ou relative de la galerie (ex: "500px", "60vh", 500.0).
    pub fn height(mut self, h: impl Into<String>) -> Self {
        self.height = Some(h.into());
        self
    }
    /// Hauteur minimale du conteneur de la galerie.
    pub fn min_height(mut self, mh: impl Into<String>) -> Self {
        self.min_height = Some(mh.into());
        self
    }
    /// Hauteur maximale du conteneur avant scrollbar (ex: "650px", "80vh").
    pub fn max_height(mut self, mh: impl Into<String>) -> Self {
        self.max_height = Some(mh.into());
        self
    }
    /// Limite maximale d'images affichées dans la galerie (les plus récentes en premier).
    pub fn limit(mut self, n: usize) -> Self {
        self.limit = Some(n);
        self
    }
    /// Hauteur d'une vignette / image de la galerie (ex: "140px", "180px", "220px").
    pub fn item_height(mut self, ih: impl Into<String>) -> Self {
        self.item_height = Some(ih.into());
        self
    }
    /// Largeur d'une vignette / image de la galerie (ex: "180px", "240px").
    pub fn item_width(mut self, iw: impl Into<String>) -> Self {
        self.item_width = Some(iw.into());
        self
    }
    /// Ratio d'aspect d'une vignette (ex: "1/1", "16/9", "4/3", "9/16").
    pub fn aspect_ratio(mut self, ar: impl Into<String>) -> Self {
        self.aspect_ratio = Some(ar.into());
        self
    }
    /// Mode d'ajustement des images (`"cover"`, `"contain"`, `"scale-down"`).
    pub fn object_fit(mut self, fit: impl Into<String>) -> Self {
        self.object_fit = fit.into();
        self
    }
    /// Active la visionneuse / lightbox plein écran au clic (défaut : `true`).
    pub fn allow_preview(mut self, allow: bool) -> Self {
        self.allow_preview = allow;
        self
    }
    /// Autorise la sélection/upload.
    pub fn interactive(mut self, on: bool) -> Self {
        self.interactive = on;
        self
    }
    /// Affiche le bouton d'ajout d'image.
    pub fn upload(mut self, on: bool) -> Self {
        self.upload = on;
        self
    }
    /// Déclare la galerie **sortie** (affichage seul).
    pub fn output(mut self) -> Self {
        self.out = true;
        self
    }
    /// Déclare la galerie **entrée** (upload — par défaut).
    pub fn input(mut self) -> Self {
        self.out = false;
        self
    }
}

impl Component for Gallery {
    fn id(&self) -> &str {
        &self.id
    }
    fn kind(&self) -> &'static str {
        "gallery"
    }
    fn role(&self) -> Role {
        if self.out {
            Role::Output
        } else {
            Role::Input
        }
    }
    fn props(&self) -> Value {
        json!({
            "label": self.label,
            "value": self.value,
            "columns": self.columns,
            "rows": self.rows,
            "height": self.height,
            "min_height": self.min_height,
            "max_height": self.max_height,
            "limit": self.limit,
            "item_height": self.item_height,
            "item_width": self.item_width,
            "aspect_ratio": self.aspect_ratio,
            "object_fit": self.object_fit,
            "allow_preview": self.allow_preview,
            "interactive": self.interactive,
            "upload": self.upload
        })
    }
}

/// **Bounding box** representation for [`AnnotatedImage`].
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq)]
pub struct BoundingBox {
    /// Normalized coordinates `[ymin, xmin, ymax, xmax]` in `0.0..=1.0`.
    pub box_coords: [f64; 4],
    /// Classification label (e.g. `"person"`, `"car"`, `"cat"`).
    pub label: String,
    /// Confidence score (e.g. `0.95`).
    pub score: Option<f64>,
    /// Hex stroke & tag color (e.g. `"#6366f1"`).
    pub color: String,
}

/// **AnnotatedImage** component (`gr.AnnotatedImage` equivalent): displays a base
/// image with vector bounding boxes, labels, and confidence tags.
#[derive(Clone, Debug)]
pub struct AnnotatedImage {
    id: String,
    label: String,
    image: String,
    boxes: Vec<BoundingBox>,
    show_labels: bool,
    show_scores: bool,
}

impl AnnotatedImage {
    /// Creates an annotated image viewer with its identifier. Output by default.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            label: String::new(),
            image: String::new(),
            boxes: Vec::new(),
            show_labels: true,
            show_scores: true,
        }
    }
    /// Label displayed above the image viewer.
    pub fn label(mut self, l: impl Into<String>) -> Self {
        self.label = l.into();
        self
    }
    /// Base background image URL or data URL.
    pub fn image(mut self, img: impl Into<String>) -> Self {
        self.image = img.into();
        self
    }
    /// Adds a normalized bounding box `[ymin, xmin, ymax, xmax]` with label, score and color.
    #[allow(clippy::too_many_arguments)]
    pub fn box_norm(
        mut self,
        ymin: f64,
        xmin: f64,
        ymax: f64,
        xmax: f64,
        label: impl Into<String>,
        score: Option<f64>,
        color: impl Into<String>,
    ) -> Self {
        self.boxes.push(BoundingBox {
            box_coords: [ymin, xmin, ymax, xmax],
            label: label.into(),
            score,
            color: color.into(),
        });
        self
    }
    /// Sets the full list of bounding boxes.
    pub fn boxes(mut self, b: Vec<BoundingBox>) -> Self {
        self.boxes = b;
        self
    }
    /// Sets full JSON data: `{ "image": "...", "boxes": [...] }`.
    pub fn data<T: serde::Serialize>(mut self, d: &T) -> Self {
        if let Ok(v) = serde_json::to_value(d) {
            if let Some(img) = v.get("image").and_then(|x| x.as_str()) {
                self.image = img.to_string();
            }
            if let Some(arr) = v.get("boxes").and_then(|x| x.as_array()) {
                if let Ok(b) = serde_json::from_value::<Vec<BoundingBox>>(Value::Array(arr.clone()))
                {
                    self.boxes = b;
                }
            }
        }
        self
    }
    /// Shows or hides class label badges on boxes.
    pub fn show_labels(mut self, on: bool) -> Self {
        self.show_labels = on;
        self
    }
    /// Shows or hides percentage confidence scores.
    pub fn show_scores(mut self, on: bool) -> Self {
        self.show_scores = on;
        self
    }
}

impl Component for AnnotatedImage {
    fn id(&self) -> &str {
        &self.id
    }
    fn kind(&self) -> &'static str {
        "annotatedimage"
    }
    fn role(&self) -> Role {
        Role::Output
    }
    fn props(&self) -> Value {
        json!({
            "label": self.label,
            "image": self.image,
            "boxes": self.boxes,
            "show_labels": self.show_labels,
            "show_scores": self.show_scores
        })
    }
}

/// **ImageComparison** component (`gr.ImageSlider` equivalent): interactive
/// before-and-after image viewer with a draggable divider slider.
#[derive(Clone, Debug)]
pub struct ImageComparison {
    id: String,
    label: String,
    before: String,
    after: String,
    before_label: String,
    after_label: String,
    position: f64,
}

impl ImageComparison {
    /// Creates an image comparison viewer with its identifier. Output by default.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            label: String::new(),
            before: String::new(),
            after: String::new(),
            before_label: "Before".into(),
            after_label: "After".into(),
            position: 50.0,
        }
    }
    /// Label displayed above the comparison viewer.
    pub fn label(mut self, l: impl Into<String>) -> Self {
        self.label = l.into();
        self
    }
    /// Sets before image URL and optional badge label.
    pub fn before(mut self, img: impl Into<String>, label: impl Into<String>) -> Self {
        self.before = img.into();
        self.before_label = label.into();
        self
    }
    /// Sets after image URL and optional badge label.
    pub fn after(mut self, img: impl Into<String>, label: impl Into<String>) -> Self {
        self.after = img.into();
        self.after_label = label.into();
        self
    }
    /// Initial slider position percentage (e.g. `50.0`).
    pub fn position(mut self, pos: f64) -> Self {
        self.position = pos.clamp(0.0, 100.0);
        self
    }
}

impl Component for ImageComparison {
    fn id(&self) -> &str {
        &self.id
    }
    fn kind(&self) -> &'static str {
        "imagecomparison"
    }
    fn role(&self) -> Role {
        Role::Output
    }
    fn props(&self) -> Value {
        json!({
            "label": self.label,
            "before": self.before,
            "after": self.after,
            "before_label": self.before_label,
            "after_label": self.after_label,
            "position": self.position
        })
    }
}

/// **AudioRecorder** component: direct microphone recording with dedicated REC
/// button, active recording animation, elapsed timer, and audio export.
#[derive(Clone, Debug)]
pub struct AudioRecorder {
    id: String,
    label: String,
    max_duration: f64,
    interactive: bool,
}

impl AudioRecorder {
    /// Creates an audio recorder component with default 60-second limit. Input by default.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            label: String::new(),
            max_duration: 60.0,
            interactive: true,
        }
    }
    /// Label displayed above the recorder.
    pub fn label(mut self, l: impl Into<String>) -> Self {
        self.label = l.into();
        self
    }
    /// Maximum recording duration in seconds (default `60.0`).
    pub fn max_duration(mut self, d: f64) -> Self {
        self.max_duration = d;
        self
    }
    /// Enables or disables recording interaction.
    pub fn interactive(mut self, on: bool) -> Self {
        self.interactive = on;
        self
    }
}

impl Component for AudioRecorder {
    fn id(&self) -> &str {
        &self.id
    }
    fn kind(&self) -> &'static str {
        "audiorecorder"
    }
    fn role(&self) -> Role {
        Role::Input
    }
    fn props(&self) -> Value {
        json!({
            "label": self.label,
            "max_duration": self.max_duration,
            "interactive": self.interactive
        })
    }
}

/// Surlignage / boîte de détection sur une page de document PDF (pour RAG et OCR).
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct PdfHighlight {
    /// Numéro de page (1-indexé).
    pub page: u32,
    /// Coordonnée X normalisée (0.0 à 1.0) ou en pourcentage.
    pub x: f64,
    /// Coordonnée Y normalisée (0.0 à 1.0) ou en pourcentage.
    pub y: f64,
    /// Largeur normalisée (0.0 à 1.0).
    pub width: f64,
    /// Hauteur normalisée (0.0 à 1.0).
    pub height: f64,
    /// Libellé ou extrait textuel associé.
    pub label: Option<String>,
    /// Couleur du surlignage (code hexadécimal ou CSS).
    pub color: Option<String>,
}

/// **Pdf** : Visualiseur de documents PDF interactif avec navigation multi-pages,
/// zoom et surlignage dynamique de boîtes de détection / extractions RAG/OCR.
///
/// ```rust
/// # use grio::*;
/// Pdf::new("invoice")
///     .label("Facture & Extraction RAG")
///     .src("https://example.com/doc.pdf")
///     .page(1)
///     .highlight(1, 0.1, 0.2, 0.5, 0.08, "Montant Total: 1 250 €", "#6366f1");
/// ```
#[derive(Clone, Debug)]
pub struct Pdf {
    id: String,
    label: String,
    src: String,
    page: u32,
    total_pages: Option<u32>,
    zoom: f64,
    highlights: Vec<PdfHighlight>,
    show_toolbar: bool,
    interactive: bool,
}

impl Pdf {
    /// Crée un nouveau composant PDF avec son identifiant. Rôle `Output` par défaut.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            label: String::new(),
            src: String::new(),
            page: 1,
            total_pages: None,
            zoom: 1.0,
            highlights: Vec::new(),
            show_toolbar: true,
            interactive: true,
        }
    }

    /// Libellé affiché au-dessus du visualiseur.
    pub fn label(mut self, l: impl Into<String>) -> Self {
        self.label = l.into();
        self
    }

    /// Source du fichier PDF (URL HTTP, chemin relatif ou data URL base64).
    pub fn src(mut self, s: impl Into<String>) -> Self {
        self.src = s.into();
        self
    }

    /// Page initiale affichée (1-indexée).
    pub fn page(mut self, p: u32) -> Self {
        self.page = p.max(1);
        self
    }

    /// Nombre total de pages (optionnel).
    pub fn total_pages(mut self, total: u32) -> Self {
        self.total_pages = Some(total);
        self
    }

    /// Facteur de zoom initial (ex. 1.0 pour 100%, 1.25 pour 125%).
    pub fn zoom(mut self, z: f64) -> Self {
        self.zoom = z.clamp(0.2, 4.0);
        self
    }

    /// Ajoute une zone de surlignage RAG/OCR sur une page donnée.
    #[allow(clippy::too_many_arguments)]
    pub fn highlight(
        mut self,
        page: u32,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
        label: impl Into<String>,
        color: impl Into<String>,
    ) -> Self {
        self.highlights.push(PdfHighlight {
            page,
            x,
            y,
            width,
            height,
            label: Some(label.into()),
            color: Some(color.into()),
        });
        self
    }

    /// Définit la liste complète des surlignages.
    pub fn highlights(mut self, hl: Vec<PdfHighlight>) -> Self {
        self.highlights = hl;
        self
    }

    /// Affiche ou masque la barre d'outils de pagination et zoom.
    pub fn show_toolbar(mut self, on: bool) -> Self {
        self.show_toolbar = on;
        self
    }

    /// Active ou désactive l'interactivité utilisateur.
    pub fn interactive(mut self, on: bool) -> Self {
        self.interactive = on;
        self
    }
}

impl Component for Pdf {
    fn id(&self) -> &str {
        &self.id
    }
    fn kind(&self) -> &'static str {
        "pdf"
    }
    fn role(&self) -> Role {
        Role::Output
    }
    fn props(&self) -> Value {
        json!({
            "label": self.label,
            "src": self.src,
            "page": self.page,
            "total_pages": self.total_pages,
            "zoom": self.zoom,
            "highlights": self.highlights,
            "show_toolbar": self.show_toolbar,
            "interactive": self.interactive,
        })
    }
}

/// Composant de flux audio temps réel bidirectionnel avec détection de voix (VAD).
///
/// Permet de capturer l'audio du microphone sous forme de fragments (PCM/Opus),
/// d'émettre des événements de parole/silence (`on_speech_start`/`on_speech_stop`),
/// et de diffuser de l'audio synthétisé vers le navigateur sans rafraîchir la page.
#[derive(Clone, Debug)]
pub struct AudioStream {
    id: String,
    label: String,
    sample_rate: u32,
    vad: bool,
    show_waveform: bool,
    interactive: bool,
    out: bool,
    autoplay: bool,
}

impl AudioStream {
    /// Crée un nouveau flux audio temps réel.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            label: String::new(),
            sample_rate: 16000,
            vad: true,
            show_waveform: true,
            interactive: true,
            out: false,
            autoplay: true,
        }
    }

    /// Étiquette affichée au-dessus du composant.
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = label.into();
        self
    }

    /// Taux d'échantillonnage cible (ex: 16000 pour les modèles STT type Whisper, ou 48000).
    pub fn sample_rate(mut self, hz: u32) -> Self {
        self.sample_rate = hz;
        self
    }

    /// Active ou désactive la détection d'activité vocale (VAD) côté client.
    pub fn vad(mut self, on: bool) -> Self {
        self.vad = on;
        self
    }

    /// Affiche ou masque la visualisation de forme d'onde (waveform) temps réel.
    pub fn show_waveform(mut self, on: bool) -> Self {
        self.show_waveform = on;
        self
    }

    /// Active ou désactive le contrôle d'enregistrement/écoute par l'utilisateur.
    pub fn interactive(mut self, on: bool) -> Self {
        self.interactive = on;
        self
    }

    /// Déclare le composant comme sortie (lecture audio / haut-parleur uniquement).
    pub fn output(mut self) -> Self {
        self.out = true;
        self
    }

    /// Déclare le composant comme entrée (microphone / capture — par défaut).
    pub fn input(mut self) -> Self {
        self.out = false;
        self
    }

    /// Active la lecture automatique des flux reçus du serveur.
    pub fn autoplay(mut self, on: bool) -> Self {
        self.autoplay = on;
        self
    }
}

impl Component for AudioStream {
    fn id(&self) -> &str {
        &self.id
    }
    fn kind(&self) -> &'static str {
        "audiostream"
    }
    fn role(&self) -> Role {
        if self.out {
            Role::Output
        } else {
            Role::Input
        }
    }
    fn props(&self) -> Value {
        json!({
            "label": self.label,
            "sample_rate": self.sample_rate,
            "vad": self.vad,
            "show_waveform": self.show_waveform,
            "interactive": self.interactive,
            "autoplay": self.autoplay,
        })
    }
}

/// Composant de capture vidéo/caméra temps réel avec calque de rendu d'overlays GPU.
///
/// Permet d'ingérer le flux webcam ou vidéo en direct et d'afficher des boîtes englobantes,
/// des masques polygonaux, des squelettes de pose et un badge de télémétrie FPS
/// à 60 FPS sans bloquer le thread principal.
#[derive(Clone, Debug)]
pub struct CameraStream {
    id: String,
    label: String,
    fps: u32,
    mirror: bool,
    show_telemetry: bool,
    facing_mode: String,
    interactive: bool,
    out: bool,
}

impl CameraStream {
    /// Crée un nouveau flux caméra temps réel.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            label: String::new(),
            fps: 30,
            mirror: true,
            show_telemetry: true,
            facing_mode: "user".to_string(),
            interactive: true,
            out: false,
        }
    }

    /// Étiquette affichée au-dessus du flux caméra.
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = label.into();
        self
    }

    /// Cadence cible de capture/traitement des frames en images par seconde (ex: 15, 30, 60).
    pub fn fps(mut self, fps: u32) -> Self {
        self.fps = fps.clamp(1, 120);
        self
    }

    /// Active ou désactive l'effet miroir (horizontal flip) pour la caméra frontale.
    pub fn mirror(mut self, on: bool) -> Self {
        self.mirror = on;
        self
    }

    /// Affiche ou masque la télémétrie en temps réel (FPS, résolution, latence).
    pub fn show_telemetry(mut self, on: bool) -> Self {
        self.show_telemetry = on;
        self
    }

    /// Sélectionne la caméra frontale (face utilisateur).
    pub fn user_camera(mut self) -> Self {
        self.facing_mode = "user".to_string();
        self.mirror = true;
        self
    }

    /// Sélectionne la caméra arrière / environnementale.
    pub fn environment_camera(mut self) -> Self {
        self.facing_mode = "environment".to_string();
        self.mirror = false;
        self
    }

    /// Active ou désactive l'interactivité.
    pub fn interactive(mut self, on: bool) -> Self {
        self.interactive = on;
        self
    }

    /// Déclare le composant comme sortie.
    pub fn output(mut self) -> Self {
        self.out = true;
        self
    }

    /// Déclare le composant comme entrée (capture caméra — par défaut).
    pub fn input(mut self) -> Self {
        self.out = false;
        self
    }
}

impl Component for CameraStream {
    fn id(&self) -> &str {
        &self.id
    }
    fn kind(&self) -> &'static str {
        "camerastream"
    }
    fn role(&self) -> Role {
        if self.out {
            Role::Output
        } else {
            Role::Input
        }
    }
    fn props(&self) -> Value {
        json!({
            "label": self.label,
            "fps": self.fps,
            "mirror": self.mirror,
            "show_telemetry": self.show_telemetry,
            "facing_mode": self.facing_mode,
            "interactive": self.interactive,
        })
    }
}