tauri-plugin-widgets 0.8.0

Tauri plugin for App Widgets on Android, iOS, and macOS (WidgetKit); Windows Widgets Board (Adaptive Cards) + desktop webview; Linux desktop webview with X11 DESKTOP pin.
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
//! Shared style values: colors, backgrounds, gradients, shadows, padding,
//! frame/border config, and the small enums used across element fields.

use serde::{Deserialize, Serialize};

#[cfg(feature = "schema")]
use schemars::JsonSchema;

/// Shared visual style applied to any element (padding, background, frame, …).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct ElementStyle {
    /// Inset padding (number or per-edge object).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub padding: Option<PaddingValue>,
    /// Solid, adaptive, or gradient background.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub background: Option<BackgroundValue>,
    /// Corner radius in points.
    #[serde(
        rename = "cornerRadius",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub corner_radius: Option<f64>,
    /// Opacity from `0` (invisible) to `1` (opaque).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub opacity: Option<f64>,
    /// Explicit width / height / max constraints.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub frame: Option<FrameConfig>,
    /// Border color and width.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub border: Option<BorderConfig>,
    /// Drop shadow.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shadow: Option<ShadowConfig>,
    /// Clip content to a shape (e.g. circle avatar from square image).
    #[serde(rename = "clipShape", default, skip_serializing_if = "Option::is_none")]
    pub clip_shape: Option<ClipShape>,
    /// Layout weight for flexible sizing inside stacks (like Android `layout_weight`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flex: Option<f64>,
    /// Hide this content where the OS redacts private data (iOS / macOS locked screen,
    /// StandBy). Ignored where no redaction exists.
    #[serde(
        rename = "privacySensitive",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub privacy_sensitive: Option<bool>,
    /// Text read by screen readers instead of the visible content.
    #[serde(
        rename = "accessibilityLabel",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub accessibility_label: Option<String>,
    /// Set fields from data with their JSON type: `{"value": "data.progress"}`.
    /// Use for numbers / booleans / arrays (`{{…}}` only fills strings).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bind: Option<std::collections::BTreeMap<String, String>>,
    /// Outer spacing (number or per-edge object), outside background and border.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub margin: Option<PaddingValue>,
    /// Keep width / height at this ratio (`1` = square).
    #[serde(
        rename = "aspectRatio",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub aspect_ratio: Option<f64>,
    /// Who keeps its size in a crowded stack: higher first. Default `0`.
    #[serde(
        rename = "layoutPriority",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub layout_priority: Option<f64>,
    /// Move right by points after layout (does not affect siblings).
    #[serde(rename = "offsetX", default, skip_serializing_if = "Option::is_none")]
    pub offset_x: Option<f64>,
    /// Move down by points after layout (does not affect siblings).
    #[serde(rename = "offsetY", default, skip_serializing_if = "Option::is_none")]
    pub offset_y: Option<f64>,
    /// Rotate by degrees (clockwise).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rotation: Option<f64>,
    /// Scale factor (`1` = unchanged).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scale: Option<f64>,
    /// Apple tinted / accented Home Screen: draw this part in the accent color
    /// (`widgetAccentable`). Ignored elsewhere.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub accentable: Option<bool>,
    /// Show only when the condition holds (`{"path": "data.n", "gt": 0}`; see
    /// [`crate::resolve`]). Removed before rendering.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(
        feature = "schema",
        schemars(with = "Option<serde_json::Map<String, serde_json::Value>>")
    )]
    pub when: Option<serde_json::Value>,
    /// How this element changes between timeline entries / redraws (a hint):
    /// `numeric` animates digits, `opacity` cross-fades, `slide` pushes from the bottom.
    /// Apple and desktop animate; Android and Adaptive Cards ignore it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub transition: Option<Transition>,
}

/// Color value — hex string, semantic name, or adaptive `{ light, dark }` pair.
///
/// Semantic names: `"label"`, `"secondaryLabel"`, `"systemBackground"`,
/// `"secondarySystemBackground"`, `"accent"`, `"separator"`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(untagged)]
pub enum ColorValue {
    /// Hex string or semantic color name.
    Solid(String),
    /// Distinct colors for light and dark appearance.
    Adaptive {
        /// Color used in light appearance.
        light: String,
        /// Color used in dark appearance.
        dark: String,
    },
}

impl From<&str> for ColorValue {
    fn from(value: &str) -> Self {
        ColorValue::Solid(value.to_string())
    }
}

impl From<String> for ColorValue {
    fn from(value: String) -> Self {
        ColorValue::Solid(value)
    }
}

/// Clip shape for content masking.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum ClipShape {
    /// `roundedRectangle` (uses `cornerRadius`).
    RoundedRectangle,
    /// `ellipse`.
    Ellipse,
    /// `circle`.
    Circle,
    /// `capsule`.
    Capsule,
    /// `rectangle`.
    Rectangle,
}

/// Semantic text style — respects Dynamic Type / accessibility settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum TextStyle {
    /// `large title`.
    LargeTitle,
    /// `title`.
    Title,
    /// `title2`.
    Title2,
    /// `title3`.
    Title3,
    /// `headline`.
    Headline,
    /// `subheadline`.
    Subheadline,
    /// `body`.
    Body,
    /// `callout`.
    Callout,
    /// `footnote`.
    Footnote,
    /// `caption`.
    Caption,
    /// `caption2`.
    Caption2,
}

/// Background: solid color string, adaptive pair, gradient, or material blur.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(untagged)]
pub enum BackgroundValue {
    /// Hex string or semantic color name.
    Solid(String),
    /// Linear, radial, or angular gradient.
    Gradient(GradientConfig),
    /// Distinct colors for light and dark appearance.
    Adaptive {
        /// Color used in light appearance.
        light: String,
        /// Color used in dark appearance.
        dark: String,
    },
}

impl From<&str> for BackgroundValue {
    fn from(value: &str) -> Self {
        BackgroundValue::Solid(value.to_string())
    }
}

impl From<String> for BackgroundValue {
    fn from(value: String) -> Self {
        BackgroundValue::Solid(value)
    }
}

/// Linear, radial, or angular gradient background.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct GradientConfig {
    /// `"linear"`, `"radial"`, or `"angular"`
    #[serde(rename = "gradientType")]
    pub gradient_type: GradientType,
    /// Stop colors, in order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub colors: Vec<String>,
    /// Direction for linear gradients
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub direction: Option<GradientDirection>,
    /// Colors at explicit positions (`location` 0…1); replaces `colors` when set.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub stops: Vec<GradientStop>,
    /// Start point in unit space (`{x:0,y:0}` = top leading); overrides `direction`.
    #[serde(
        rename = "startPoint",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub start_point: Option<UnitPoint>,
    /// End point in unit space (`{x:1,y:1}` = bottom trailing).
    #[serde(rename = "endPoint", default, skip_serializing_if = "Option::is_none")]
    pub end_point: Option<UnitPoint>,
}

/// A gradient color at a position.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct GradientStop {
    /// Hex color.
    pub color: String,
    /// Position `0…1` along the gradient.
    pub location: f64,
}

/// A point in unit coordinates (`0…1` on both axes, origin top leading).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct UnitPoint {
    /// Horizontal position, `0` = leading.
    pub x: f64,
    /// Vertical position, `0` = top.
    pub y: f64,
}

/// Gradient shape.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum GradientType {
    /// `linear`.
    Linear,
    /// `radial`.
    Radial,
    /// `angular`.
    Angular,
}

/// Direction for linear gradients.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum GradientDirection {
    /// `top to bottom`.
    TopToBottom,
    /// `bottom to top`.
    BottomToTop,
    /// `leading to trailing`.
    LeadingToTrailing,
    /// `trailing to leading`.
    TrailingToLeading,
    /// `top leading to bottom trailing`.
    TopLeadingToBottomTrailing,
    /// `top trailing to bottom leading`.
    TopTrailingToBottomLeading,
}

/// Drop shadow configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct ShadowConfig {
    /// Shadow color (hex string or semantic name).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub color: Option<String>,
    /// Blur radius in points.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub radius: Option<f64>,
    /// Horizontal offset in points.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub x: Option<f64>,
    /// Vertical offset in points.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub y: Option<f64>,
}

/// Inset padding — a single uniform value or per-edge overrides.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(untagged)]
pub enum PaddingValue {
    /// Same padding on every edge.
    Uniform(f64),
    /// Independent padding per edge.
    Edges {
        /// Top edge padding.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        top: Option<f64>,
        /// Bottom edge padding.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        bottom: Option<f64>,
        /// Leading (left in LTR) edge padding.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        leading: Option<f64>,
        /// Trailing (right in LTR) edge padding.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        trailing: Option<f64>,
    },
}

impl From<f64> for PaddingValue {
    fn from(value: f64) -> Self {
        PaddingValue::Uniform(value)
    }
}

impl From<f32> for PaddingValue {
    fn from(value: f32) -> Self {
        PaddingValue::Uniform(f64::from(value))
    }
}

impl From<i32> for PaddingValue {
    fn from(value: i32) -> Self {
        PaddingValue::Uniform(f64::from(value))
    }
}

/// Explicit width / height / max-size constraints for an element.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct FrameConfig {
    /// Fixed width in points.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub width: Option<f64>,
    /// Fixed height in points.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub height: Option<f64>,
    /// Maximum width — a fixed point value or `"infinity"`.
    #[serde(rename = "maxWidth", default, skip_serializing_if = "Option::is_none")]
    pub max_width: Option<FrameDimension>,
    /// Maximum height — a fixed point value or `"infinity"`.
    #[serde(rename = "maxHeight", default, skip_serializing_if = "Option::is_none")]
    pub max_height: Option<FrameDimension>,
    /// Minimum width in points.
    #[serde(rename = "minWidth", default, skip_serializing_if = "Option::is_none")]
    pub min_width: Option<f64>,
    /// Minimum height in points.
    #[serde(rename = "minHeight", default, skip_serializing_if = "Option::is_none")]
    pub min_height: Option<f64>,
}

/// A frame dimension — either a fixed point value or `"infinity"`.
#[derive(Debug, Clone)]
pub enum FrameDimension {
    /// Fixed point value.
    Fixed(f64),
    /// `"infinity"`.
    Infinity,
}

#[cfg(feature = "schema")]
impl JsonSchema for FrameDimension {
    fn schema_name() -> String {
        "FrameDimension".into()
    }

    fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
        use schemars::schema::{
            InstanceType, Metadata, Schema, SchemaObject, SingleOrVec, SubschemaValidation,
        };

        Schema::Object(SchemaObject {
            metadata: Some(Box::new(Metadata {
                description: Some(
                    "A frame dimension — either a fixed point value or `\"infinity\"`.".into(),
                ),
                ..Default::default()
            })),
            subschemas: Some(Box::new(SubschemaValidation {
                any_of: Some(vec![
                    SchemaObject {
                        metadata: Some(Box::new(Metadata {
                            description: Some("Fixed point value.".into()),
                            ..Default::default()
                        })),
                        instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::Number))),
                        format: Some("double".into()),
                        ..Default::default()
                    }
                    .into(),
                    SchemaObject {
                        metadata: Some(Box::new(Metadata {
                            description: Some("Keyword `\"infinity\"`.".into()),
                            ..Default::default()
                        })),
                        instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::String))),
                        enum_values: Some(vec!["infinity".into()]),
                        ..Default::default()
                    }
                    .into(),
                ]),
                ..Default::default()
            })),
            ..Default::default()
        })
    }
}

impl Serialize for FrameDimension {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Self::Fixed(v) => serializer.serialize_f64(*v),
            Self::Infinity => serializer.serialize_str("infinity"),
        }
    }
}

impl<'de> Deserialize<'de> for FrameDimension {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Helper {
            Num(f64),
            Str(String),
        }
        match Helper::deserialize(deserializer)? {
            Helper::Num(v) => Ok(Self::Fixed(v)),
            Helper::Str(s) if s == "infinity" => Ok(Self::Infinity),
            Helper::Str(s) => Err(serde::de::Error::custom(format!(
                "unknown frame dimension keyword: {s}"
            ))),
        }
    }
}

/// Border color and width.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct BorderConfig {
    /// Border color (hex string or semantic name).
    pub color: String,
    /// Border width in points. Default `1.0`.
    #[serde(default = "default_border_width")]
    pub width: f64,
}

fn default_border_width() -> f64 {
    1.0
}

/// Font weight.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum FontWeight {
    /// `ultralight`.
    Ultralight,
    /// `thin`.
    Thin,
    /// `light`.
    Light,
    /// `regular`.
    Regular,
    /// `medium`.
    Medium,
    /// `semibold`.
    Semibold,
    /// `bold`.
    Bold,
    /// `heavy`.
    Heavy,
    /// `black`.
    Black,
}

/// Font design (default, monospaced, rounded, serif).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum FontDesign {
    /// `default`.
    Default,
    /// `monospaced`.
    Monospaced,
    /// `rounded`.
    Rounded,
    /// `serif`.
    Serif,
}

/// Text alignment within the line.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum TextAlignment {
    /// `leading`.
    Leading,
    /// `center`.
    Center,
    /// `trailing`.
    Trailing,
}

/// Horizontal alignment of children within a stack.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum HorizontalAlignment {
    /// `leading`.
    Leading,
    /// `center`.
    Center,
    /// `trailing`.
    Trailing,
}

/// Vertical alignment of children within a stack.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum VerticalAlignment {
    /// `top`.
    Top,
    /// `center`.
    Center,
    /// `bottom`.
    Bottom,
}

/// How an image fills its frame.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum ContentMode {
    /// `fit`.
    Fit,
    /// `fill`.
    Fill,
    /// `stretch`: fill both axes, ignoring the aspect ratio.
    Stretch,
    /// `center`: natural size, centered, no scaling.
    Center,
}

/// Progress indicator style.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum ProgressStyle {
    /// `linear`.
    Linear,
    /// `circular`.
    Circular,
}

/// Gauge visual style.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum GaugeStyle {
    /// `circular`.
    Circular,
    /// `linear`.
    Linear,
}

/// Date / relative-time display style.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum DateStyle {
    /// `time`.
    Time,
    /// `date`.
    Date,
    /// `relative`.
    Relative,
    /// `offset`.
    Offset,
    /// `timer`.
    Timer,
}

/// Chart kind.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum ChartType {
    /// `bar`.
    #[default]
    Bar,
    /// `line`.
    Line,
    /// `area`.
    Area,
    /// `pie` (donut with `innerRadius`).
    Pie,
    /// `point`: scatter dots.
    Point,
}

/// Shape kind for [`crate::models::ShapeElement`].
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum ShapeType {
    /// `circle`.
    #[default]
    Circle,
    /// `capsule`.
    Capsule,
    /// `rectangle`.
    Rectangle,
    /// `roundedRectangle` (uses `cornerRadius`).
    RoundedRectangle,
    /// `ellipse`.
    Ellipse,
}

/// Countdown/countup direction for [`crate::models::TimerElement`].
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum TimerCounting {
    /// `up`.
    Up,
    /// `down`.
    Down,
}

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

    proptest! {
        /// Any solid / adaptive colour and any uniform / per-edge padding survives
        /// serialize → deserialize with the same variant and values.
        #[test]
        fn color_and_padding_roundtrip(
            a in "[#a-zA-Z0-9]{0,8}",
            b in "[#a-zA-Z0-9]{0,8}",
            u in -4_000_000i32..4_000_000,
            edges in proptest::array::uniform4(proptest::option::of(0u32..40_000)),
        ) {
            // Quarter steps: exact in f64 and in JSON (serde_json's default float parser
            // is not round-trip exact for arbitrary f64).
            let u = f64::from(u) / 4.0;
            let edges = edges.map(|e| e.map(|q| f64::from(q) / 4.0));
            for c in [ColorValue::Solid(a.clone()), ColorValue::Adaptive { light: a.clone(), dark: b.clone() }] {
                let back: ColorValue = serde_json::from_str(&serde_json::to_string(&c).unwrap()).unwrap();
                match (&c, &back) {
                    (ColorValue::Solid(x), ColorValue::Solid(y)) => prop_assert_eq!(x, y),
                    (ColorValue::Adaptive { light: l1, dark: d1 }, ColorValue::Adaptive { light: l2, dark: d2 }) => {
                        prop_assert_eq!((l1, d1), (l2, d2))
                    }
                    _ => prop_assert!(false, "{:?} -> {:?}", c, back),
                }
            }
            let back: PaddingValue = serde_json::from_str(&serde_json::to_string(&PaddingValue::Uniform(u)).unwrap()).unwrap();
            prop_assert!(matches!(back, PaddingValue::Uniform(v) if v == u));
            let [top, bottom, leading, trailing] = edges;
            let p = PaddingValue::Edges { top, bottom, leading, trailing };
            let back: PaddingValue = serde_json::from_str(&serde_json::to_string(&p).unwrap()).unwrap();
            match back {
                PaddingValue::Edges { top: t, bottom: b, leading: l, trailing: tr } => {
                    prop_assert_eq!((t, b, l, tr), (top, bottom, leading, trailing))
                }
                // All-`None` edges serialize to `{}`, which is still an edges object.
                other => prop_assert!(false, "{:?}", other),
            }
        }
    }

    /// Wire spellings and defaults of the style vocabulary: uniform padding is a bare
    /// number → an empty style is `{}` → border width defaults to 1 → chart / shape
    /// defaults → camelCase enums → `infinity` is the only frame keyword.
    #[test]
    fn style_wire_spellings_and_defaults() {
        assert_eq!(
            serde_json::to_string(&PaddingValue::Uniform(8.0)).unwrap(),
            "8.0"
        );
        assert_eq!(
            serde_json::to_string(&ElementStyle::default()).unwrap(),
            "{}"
        );
        let b: BorderConfig = serde_json::from_str(r##"{"color":"#ffffff"}"##).unwrap();
        assert!((b.width - 1.0).abs() < f64::EPSILON);
        assert_eq!(b.color, "#ffffff");
        assert!(matches!(ChartType::default(), ChartType::Bar));
        assert!(matches!(ShapeType::default(), ShapeType::Circle));
        let w: FontWeight = serde_json::from_str(r#""semibold""#).unwrap();
        assert!(matches!(w, FontWeight::Semibold));
        let a: TextAlignment = serde_json::from_str(r#""trailing""#).unwrap();
        assert!(matches!(a, TextAlignment::Trailing));
        let t: TimerCounting = serde_json::from_str(r#""down""#).unwrap();
        assert!(matches!(t, TimerCounting::Down));
        let d: FrameDimension = serde_json::from_str(r#""infinity""#).unwrap();
        assert!(matches!(d, FrameDimension::Infinity));
        assert!(serde_json::from_str::<FrameDimension>(r#""auto""#).is_err());
    }
}

/// Distribution of stack children along the stack axis.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum Justify {
    /// Packed at the start (default).
    Start,
    /// Packed in the middle.
    Center,
    /// Packed at the end.
    End,
    /// First and last at the edges, equal gaps between.
    SpaceBetween,
    /// Equal space around each child.
    SpaceAround,
    /// Equal gaps everywhere, edges included.
    SpaceEvenly,
}

/// Where text is cut when it does not fit.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum TruncationMode {
    /// `…end`.
    Head,
    /// `sta…end`.
    Middle,
    /// `start…` (default).
    Tail,
}

/// SF Symbol rendering mode.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum SymbolRendering {
    /// One color (default).
    Monochrome,
    /// One color, layered opacity.
    Hierarchical,
    /// Up to three `paletteColors`.
    Palette,
    /// The symbol's own colors.
    Multicolor,
}

/// Button look.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum ButtonVariant {
    /// Tinted rounded background (default).
    Bordered,
    /// Filled with `backgroundColor` / accent, white label.
    Prominent,
    /// Label only.
    Plain,
    /// Outline in the label color, no fill.
    Outline,
}

/// Toggle look.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum ToggleVariant {
    /// Switch (default).
    Switch,
    /// Checkbox.
    Checkbox,
}

/// Line / area curve.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum ChartInterpolation {
    /// Straight segments (default).
    Linear,
    /// Smooth curve through every point.
    Monotone,
    /// Steps.
    Step,
}

/// Content change animation hint (`transition`).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase")]
pub enum Transition {
    /// Swap without animation.
    None,
    /// Cross-fade.
    Opacity,
    /// Push the new content in from the bottom.
    Slide,
    /// Roll changed digits (`contentTransition(.numericText())`).
    Numeric,
}