tauri-plugin-widgets 0.5.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
//! 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>,
}

/// 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 {
    /// `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.
    pub colors: Vec<String>,
    /// Direction for linear gradients
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub direction: Option<GradientDirection>,
}

/// 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>,
}

/// 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,
}

/// 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`.
    Pie,
}

/// 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,
}

/// 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::*;

    #[test]
    fn color_value_roundtrip_solid_and_adaptive() {
        let solid = ColorValue::Solid("#ff0000".into());
        let s = serde_json::to_string(&solid).unwrap();
        let back: ColorValue = serde_json::from_str(&s).unwrap();
        assert!(matches!(back, ColorValue::Solid(ref x) if x == "#ff0000"));

        let adaptive = ColorValue::Adaptive {
            light: "#fff".into(),
            dark: "#000".into(),
        };
        let s = serde_json::to_string(&adaptive).unwrap();
        let back: ColorValue = serde_json::from_str(&s).unwrap();
        assert!(matches!(
            back,
            ColorValue::Adaptive {
                ref light,
                ref dark
            } if light == "#fff" && dark == "#000"
        ));
    }

    #[test]
    fn padding_value_roundtrip() {
        let u = PaddingValue::Uniform(8.0);
        let s = serde_json::to_string(&u).unwrap();
        assert_eq!(s, "8.0");
        let back: PaddingValue = serde_json::from_str(&s).unwrap();
        assert!(matches!(back, PaddingValue::Uniform(v) if (v - 8.0).abs() < f64::EPSILON));

        let edges = PaddingValue::Edges {
            top: Some(1.0),
            bottom: Some(2.0),
            leading: Some(3.0),
            trailing: None,
        };
        let s = serde_json::to_string(&edges).unwrap();
        let back: PaddingValue = serde_json::from_str(&s).unwrap();
        assert!(matches!(back, PaddingValue::Edges { .. }));
    }

    #[test]
    fn element_style_default_is_empty_object() {
        let s = serde_json::to_string(&ElementStyle::default()).unwrap();
        assert_eq!(s, "{}");
    }

    #[test]
    fn border_config_default_width() {
        let b: BorderConfig =
            serde_json::from_str(r##"{"color":"#ffffff"}"##).unwrap();
        assert!((b.width - 1.0).abs() < f64::EPSILON);
        assert_eq!(b.color, "#ffffff");
    }

    #[test]
    fn chart_shape_defaults() {
        assert!(matches!(ChartType::default(), ChartType::Bar));
        assert!(matches!(ShapeType::default(), ShapeType::Circle));
    }

    #[test]
    fn enums_deserialize_camel_case() {
        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));
    }

    #[test]
    fn frame_dimension_accepts_infinity() {
        let d: FrameDimension = serde_json::from_str(r#""infinity""#).unwrap();
        assert!(matches!(d, FrameDimension::Infinity));
    }

    #[test]
    fn frame_dimension_rejects_unknown_keyword() {
        assert!(serde_json::from_str::<FrameDimension>(r#""auto""#).is_err());
    }
}