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
//! Shared token helpers: container style, size/weight/color buckets, flex widths.

use crate::models::{
    ButtonElement, CanvasElement, ChartElement, ColorValue, ContainerElement, DateElement,
    DividerElement, ElementStyle, FontWeight, GaugeElement, GridElement, HStackElement,
    ImageElement, LabelElement, LinkElement, ListElement, PaddingValue, ProgressElement,
    ShapeElement, TextAlignment, TextElement, TimerElement, ToggleElement, VStackElement,
    WidgetElement, ZStackElement,
};
use serde_json::{json, Value};

pub(super) fn flex_width(c: &WidgetElement) -> Value {
    flex_of(c)
        .map(|f| {
            if f <= 0.0 {
                json!("auto")
            } else {
                json!((f * 100.0).round() as u64)
            }
        })
        .unwrap_or(json!("auto"))
}

fn flex_of(e: &WidgetElement) -> Option<f64> {
    style_of(e)?.flex
}

/// `layoutPriority` of a child (stack column widths).
pub(super) fn priority_of(e: &WidgetElement) -> Option<f64> {
    style_of(e)?.layout_priority
}

/// Takes all the width a row offers, as on Apple / desktop: a linear progress, a
/// `frame.maxWidth: infinity`, or a stack holding one. Its row column then gets "stretch"
/// instead of "auto" (an auto column shrank empty progress columns to nothing).
pub(super) fn fills_width(e: &WidgetElement) -> bool {
    let infinite = style_of(e)
        .and_then(|s| s.frame.as_ref())
        .is_some_and(|f| matches!(f.max_width, Some(crate::models::FrameDimension::Infinity)));
    infinite
        || match e {
            WidgetElement::Progress(p) => {
                !matches!(p.bar_style, Some(crate::models::ProgressStyle::Circular))
            }
            WidgetElement::VStack(VStackElement { children, .. })
            | WidgetElement::HStack(HStackElement { children, .. }) => {
                children.iter().any(fills_width)
            }
            _ => false,
        }
}

/// Shared style of any element (`None` for `spacer`).
pub(super) fn style_of(e: &WidgetElement) -> Option<&ElementStyle> {
    match e {
        WidgetElement::VStack(VStackElement { style, .. })
        | WidgetElement::HStack(HStackElement { style, .. })
        | WidgetElement::ZStack(ZStackElement { style, .. })
        | WidgetElement::Grid(GridElement { style, .. })
        | WidgetElement::Container(ContainerElement { style, .. })
        | WidgetElement::Text(TextElement { style, .. })
        | WidgetElement::Image(ImageElement { style, .. })
        | WidgetElement::Progress(ProgressElement { style, .. })
        | WidgetElement::Gauge(GaugeElement { style, .. })
        | WidgetElement::Button(ButtonElement { style, .. })
        | WidgetElement::Toggle(ToggleElement { style, .. })
        | WidgetElement::Divider(DividerElement { style, .. })
        | WidgetElement::Date(DateElement { style, .. })
        | WidgetElement::Chart(ChartElement { style, .. })
        | WidgetElement::List(ListElement { style, .. })
        | WidgetElement::Link(LinkElement { style, .. })
        | WidgetElement::Shape(ShapeElement { style, .. })
        | WidgetElement::Timer(TimerElement { style, .. })
        | WidgetElement::Canvas(CanvasElement { style, .. })
        | WidgetElement::Label(LabelElement { style, .. })
        | WidgetElement::Repeat(crate::models::RepeatElement { style, .. })
        | WidgetElement::Use(crate::models::UseElement { style, .. }) => Some(style),
        WidgetElement::Spacer(_) => None,
    }
}

/// `"12px"` for AC pixel sizes.
pub(super) fn px(v: f64) -> String {
    format!("{}px", v.max(0.0).round() as i64)
}

/// Empty block of a fixed height (vertical margin / gap emulation).
fn v_gap(h: f64) -> Value {
    json!({"type": "Container", "spacing": "None", "minHeight": px(h), "items": []})
}

/// Style every element gets after its own conversion: `frame.minHeight` (AC `minHeight`)
/// and `margin` (fixed-height blocks above / below, fixed-width columns beside).
/// `offsetX/Y`, `rotation`, `scale`, `accentable`, `frame.minWidth` have no AC form.
pub(super) fn apply_common(mut v: Value, style: &ElementStyle) -> Value {
    if let Some(min_h) = style
        .frame
        .as_ref()
        .and_then(|f| f.min_height)
        .filter(|h| *h > 0.0)
    {
        if !matches!(v["type"].as_str(), Some("Container" | "ColumnSet")) {
            v = json!({"type": "Container", "spacing": "None", "items": [v]});
        }
        v["minHeight"] = json!(px(min_h));
    }
    if let Some(m) = &style.margin {
        let (t, b, l, r) = match *m {
            PaddingValue::Uniform(u) => (u, u, u, u),
            PaddingValue::Edges {
                top,
                bottom,
                leading,
                trailing,
            } => (
                top.unwrap_or(0.0),
                bottom.unwrap_or(0.0),
                leading.unwrap_or(0.0),
                trailing.unwrap_or(0.0),
            ),
        };
        if t > 0.0 || b > 0.0 {
            let mut items = Vec::new();
            if t > 0.0 {
                items.push(v_gap(t));
            }
            items.push(v);
            if b > 0.0 {
                items.push(v_gap(b));
            }
            v = json!({"type": "Container", "spacing": "None", "items": items});
        }
        if l > 0.0 || r > 0.0 {
            let mut cols = Vec::new();
            if l > 0.0 {
                cols.push(json!({"type": "Column", "width": px(l), "items": []}));
            }
            cols.push(
                json!({"type": "Column", "width": "stretch", "spacing": "None", "items": [v]}),
            );
            if r > 0.0 {
                cols.push(
                    json!({"type": "Column", "width": px(r), "spacing": "None", "items": []}),
                );
            }
            v = json!({"type": "ColumnSet", "spacing": "None", "columns": cols});
        }
    }
    v
}

fn push_id_token(obj: &mut Value, token: &str) {
    match obj.get("id").and_then(|v| v.as_str()) {
        Some(id) if !id.is_empty() => {
            if id.split(';').any(|p| p == token) {
                return;
            }
            obj["id"] = json!(format!("{id};{token}"));
        }
        _ => {
            obj["id"] = json!(token);
        }
    }
}

pub(super) fn apply_gap_id(obj: &mut Value, spacing: Option<f64>) {
    let Some(s) = spacing else {
        return;
    };
    if s <= 0.0 {
        return;
    }
    // Adaptive Cards layout spacing (pt buckets) — keep gap id for debug tooling.
    let ac = if s < 4.0 {
        "Small"
    } else if s < 10.0 {
        "Default"
    } else if s < 16.0 {
        "Medium"
    } else {
        "Large"
    };
    obj["spacing"] = json!(ac);
    push_id_token(obj, &format!("gap:{}", s.round() as i64));
}

pub(super) fn apply_container_style(obj: &mut Value, style: &ElementStyle) {
    if let Some(bg) = &style.background {
        match bg {
            crate::models::BackgroundValue::Gradient(g) => {
                if let Ok(uri) = crate::rasterize::gradient_to_png_data_uri(g) {
                    obj["backgroundImage"] = json!({
                        "url": uri,
                        "fillMode": "cover",
                    });
                } else {
                    // Fallback when rasterize is off: emphasis + first stop in id.
                    obj["style"] = json!("emphasis");
                    if let Some(hex) = background_hex(bg) {
                        push_id_token(obj, &format!("card:{hex}"));
                    }
                }
            }
            _ => {
                // Adaptive Cards only has emphasis / good / attention / warning / accent / default:
                // the style is the fallback, a repeated 1x1 PNG gives the exact colour.
                obj["style"] = json!("emphasis");
                if let Some(hex) = background_hex(bg) {
                    if let Some(uri) = crate::rasterize::solid_png_data_uri(&hex) {
                        obj["backgroundImage"] = json!({ "url": uri, "fillMode": "repeat" });
                    }
                    push_id_token(obj, &format!("card:{hex}"));
                }
            }
        }
    }
}

pub(super) fn apply_container_style_to_wrapper(obj: &mut Value, style: &ElementStyle) {
    // Rasterized zstack Image cannot take Container style; still stamp color id for composites.
    if let Some(bg) = &style.background {
        if let Some(hex) = background_hex(bg) {
            push_id_token(obj, &format!("card:{hex}"));
        }
    }
}

fn background_hex(bg: &crate::models::BackgroundValue) -> Option<String> {
    match bg {
        crate::models::BackgroundValue::Solid(s) => {
            let s = s.trim();
            if s.starts_with('#') {
                Some(s.to_ascii_lowercase())
            } else {
                None
            }
        }
        crate::models::BackgroundValue::Adaptive { dark, .. } => {
            let s = dark.trim();
            if s.starts_with('#') {
                Some(s.to_ascii_lowercase())
            } else {
                None
            }
        }
        crate::models::BackgroundValue::Gradient(g) => g
            .stops
            .first()
            .map(|s| &s.color)
            .or(g.colors.first())
            .map(|c| c.trim().to_ascii_lowercase())
            .filter(|c| c.starts_with('#')),
    }
}

pub(super) fn size_bucket(font_size: Option<f64>) -> &'static str {
    match font_size {
        Some(s) if s <= 12.0 => "Small",
        Some(s) if s <= 16.0 => "Default",
        Some(s) if s <= 22.0 => "Medium",
        Some(s) if s <= 32.0 => "Large",
        Some(_) => "ExtraLarge",
        None => "Default",
    }
}

pub(super) fn img_size_bucket(size: Option<f64>) -> &'static str {
    match size {
        Some(s) if s <= 24.0 => "Small",
        Some(s) if s <= 48.0 => "Medium",
        Some(_) => "Large",
        None => "Medium",
    }
}

pub(super) fn weight_token(w: Option<&FontWeight>) -> &'static str {
    match w {
        Some(FontWeight::Bold)
        | Some(FontWeight::Semibold)
        | Some(FontWeight::Heavy)
        | Some(FontWeight::Black) => "Bolder",
        Some(FontWeight::Light) | Some(FontWeight::Thin) | Some(FontWeight::Ultralight) => {
            "Lighter"
        }
        _ => "Default",
    }
}

pub(super) fn align(a: Option<&TextAlignment>) -> Option<&'static str> {
    match a {
        Some(TextAlignment::Leading) => Some("Left"),
        Some(TextAlignment::Center) => Some("Center"),
        Some(TextAlignment::Trailing) => Some("Right"),
        None => None,
    }
}

/// Map IR colors to Adaptive Card semantic tokens; hex → omit (caller may approx).
pub(super) fn ac_color(color: Option<&ColorValue>) -> Option<&'static str> {
    let raw = match color? {
        ColorValue::Solid(s) => s.as_str(),
        ColorValue::Adaptive { light, .. } => light.as_str(),
    };
    let lower = raw.to_ascii_lowercase();
    match lower.as_str() {
        "accent" => Some("Accent"),
        "good" | "success" => Some("Good"),
        "warning" => Some("Warning"),
        "attention" | "error" | "danger" => Some("Attention"),
        // "Dark" text on dark Widgets Board / goldens is invisible — use Default.
        "label" | "dark" => Some("Default"),
        "secondarylabel" | "light" => Some("Light"),
        "default" => Some("Default"),
        s if s.starts_with('#') => None,
        _ => None,
    }
}

pub(super) fn color_hex(color: Option<&ColorValue>) -> Option<String> {
    let raw = match color? {
        ColorValue::Solid(s) => s.as_str(),
        ColorValue::Adaptive { light, .. } => light.as_str(),
    };
    let s = raw.trim();
    if s.starts_with('#') && (s.len() == 7 || s.len() == 4) {
        Some(s.to_ascii_lowercase())
    } else {
        None
    }
}

/// Approximate hex → AC semantic (for labels / progress style hints).
pub(super) fn approx_hex_semantic(color: Option<&ColorValue>) -> Option<&'static str> {
    let hex = color_hex(color)?;
    let (r, g, b) = parse_hex_rgb(&hex)?;
    let max = r.max(g).max(b) as f32;
    let min = r.min(g).min(b) as f32;
    let luma = 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32;
    let sat = max - min;
    // Near-black → light text on dark goldens.
    if luma < 60.0 {
        return Some("Light");
    }
    // Low-saturation slate/gray (e.g. #94a3b8) → Light, not Accent.
    if sat < 50.0 {
        return Some("Light");
    }
    if luma > 200.0 && sat < 30.0 {
        return Some("Light");
    }
    let (rf, gf, bf) = (r as f32, g as f32, b as f32);
    if rf > gf + 30.0 && rf > bf + 30.0 {
        return Some("Attention");
    }
    if gf > rf + 20.0 && gf > bf + 20.0 {
        return Some("Good");
    }
    if bf > rf + 20.0 && bf > gf + 10.0 {
        return Some("Accent");
    }
    if rf > 180.0 && gf > 120.0 && bf < 100.0 {
        return Some("Warning");
    }
    Some("Default")
}

fn parse_hex_rgb(hex: &str) -> Option<(u8, u8, u8)> {
    let h = hex.trim_start_matches('#');
    if h.len() == 3 {
        let r = u8::from_str_radix(&h[0..1].repeat(2), 16).ok()?;
        let g = u8::from_str_radix(&h[1..2].repeat(2), 16).ok()?;
        let b = u8::from_str_radix(&h[2..3].repeat(2), 16).ok()?;
        return Some((r, g, b));
    }
    if h.len() == 6 {
        let r = u8::from_str_radix(&h[0..2], 16).ok()?;
        let g = u8::from_str_radix(&h[2..4], 16).ok()?;
        let b = u8::from_str_radix(&h[4..6], 16).ok()?;
        return Some((r, g, b));
    }
    None
}

/// Media / SF-ish glyphs often missing in SVG fonts → ASCII stand-ins.
pub(super) fn sanitize_button_label(label: &str) -> String {
    let t = label.trim();
    match t {
        "⏮" | "⏮️" => "Prev".into(),
        "⏭" | "⏭️" => "Next".into(),
        "⏸" | "⏸️" => "Pause".into(),
        "▶" | "▶️" | "⏯" => "Play".into(),
        "⏹" | "⏹️" => "Stop".into(),
        "⌫" => "BS".into(),
        "±" => "+/-".into(),
        "÷" => "/".into(),
        "×" => "x".into(),
        "−" => "-".into(),
        _ => {
            let mut s = t.to_string();
            for (from, to) in [
                ("⏮", "Prev"),
                ("⏭", "Next"),
                ("⏸", "Pause"),
                ("▶", "Play"),
                ("⌫", "BS"),
                ("±", "+/-"),
                ("÷", "/"),
                ("×", "x"),
                ("−", "-"),
            ] {
                if s.contains(from) {
                    s = s.replace(from, to);
                }
            }
            s
        }
    }
}

pub(super) fn sf_symbol_glyph(name: &str) -> &'static str {
    crate::icons::sf_symbol_emoji(name)
}

/// Shared SF Symbol → emoji/glyph map for Adaptive Cards and rasterized zstacks.
pub(crate) fn sf_symbol_glyph_public(name: &str) -> &'static str {
    crate::icons::sf_symbol_emoji(name)
}