tauri_plugin_widgets/lib.rs
1//! # tauri-plugin-widgets
2//!
3//! A Tauri v2 plugin for building native widgets on Android, iOS, macOS,
4//! Windows, and Linux from a single JSON UI configuration.
5//!
6//! Empty placeholders for Adaptive Cards are avoided when the `rasterize`
7//! feature is enabled (chart/canvas/gauge/shape/zstack/gradients → PNG).
8//!
9//! ## Overview
10//!
11//! - **Widget Config API** — send a declarative [`WidgetConfig`](models::WidgetConfig)
12//! describing layouts and elements. The native widget renders it using
13//! SwiftUI (Apple), RemoteViews (Android), or HTML/CSS (desktop).
14//!
15//! - **Data API** — key-value storage shared with native widget extensions
16//! via the App Group shared container (Apple), SharedPreferences (Android),
17//! or JSON files (desktop).
18//!
19//! - **Desktop widget windows** — frameless, transparent Tauri webview windows
20//! that render the same JSON config as HTML/CSS.
21//!
22//! ## Architecture
23//!
24//! The plugin acts as a **library**, not a builder. It does NOT compile or
25//! inject widget extensions at runtime. Instead, it provides:
26//!
27//! 1. **Rust side** — commands for data storage and WidgetKit reload
28//! 2. **Swift Package** (`swift/TauriWidgets`) — public SwiftUI views and
29//! models that developers import into their own Widget Extension target
30//! 3. **Templates** (`templates/`) — ready-to-use scripts and Swift files
31//!
32//! This follows Apple's guidelines: the extension is built by Xcode, signed
33//! with the developer's certificate, and included in the app bundle at
34//! compile time.
35//!
36//! ## Quick Start (Rust)
37//!
38//! ```no_run
39//! tauri::Builder::default()
40//! .plugin(tauri_plugin_widgets::init());
41//! ```
42//!
43//! ## iOS Setup
44//!
45//! 1. Open `gen/apple/*.xcodeproj` in Xcode
46//! 2. File → New → Target → Widget Extension
47//! 3. Add `swift/` as a Local Swift Package dependency
48//! 4. Add `TauriWidgets` library to the Widget Extension target
49//! 5. Enable **App Groups** in both targets (App + Widget Extension)
50//! 6. Use the template from `templates/ios-widget/MyWidget.swift`
51//!
52//! ## macOS Setup ("Satellite Project")
53//!
54//! Tauri for macOS does not generate an `.xcodeproj`, so the widget
55//! extension must be built as a separate Xcode project:
56//!
57//! 1. Create `src-tauri/widget-extension/` with an Xcode project
58//! containing a Widget Extension target
59//! 2. Add `swift/` as a Local Swift Package dependency
60//! 3. Enable **App Groups** in both the main app entitlements and
61//! the widget extension entitlements
62//! 4. `build-widget.sh` runs via `beforeBundleCommand` (builds + signs `.appex`)
63//! 5. `bundle.macOS.files` copies the `.appex` into `Contents/PlugIns/`
64//! during a normal `tauri build` (Tauri nested-codesigns PlugIns)
65//! 6. Set `plugins.widgets.transport` (`appGroup` with Team ID, or
66//! `widgetContainer` for ad-hoc) and `plugins.widgets.appGroup`
67//!
68//! ## Rust API
69//!
70//! Build a config with typed helpers (compile-checked, not executed here):
71//!
72//! ```
73//! use tauri_plugin_widgets::models::{text, vstack, WidgetConfig};
74//!
75//! let _cfg = WidgetConfig::small(vstack(vec![
76//! text("72°").font_size(36.0).into(),
77//! ]));
78//! ```
79//!
80//! Then call [`WidgetExt::widget`] on an `AppHandle` to `set_widget_config` /
81//! `reload_all_timelines` (requires a running Tauri app).
82
83#![cfg_attr(docsrs, feature(doc_cfg))]
84#![warn(missing_docs)]
85
86#[cfg(mobile)]
87use tauri::RunEvent;
88use tauri::{
89 plugin::{Builder, TauriPlugin},
90 Manager, Runtime,
91};
92
93#[cfg(desktop)]
94use std::borrow::Cow;
95
96#[cfg(desktop)]
97#[allow(missing_docs)]
98#[cfg_attr(docsrs, doc(cfg(desktop)))]
99pub mod desktop;
100#[cfg(mobile)]
101#[allow(missing_docs)]
102#[cfg_attr(docsrs, doc(cfg(mobile)))]
103pub mod mobile;
104
105/// Adaptive Cards transpiler (Windows Widgets Board).
106#[allow(missing_docs)]
107pub mod adaptive_card;
108/// Outcomes for `set_widget_config` (written / reload / skip).
109pub mod apply;
110/// Element × platform capability matrix.
111#[allow(missing_docs)]
112pub mod capabilities;
113/// TypeScript IR emitter (`gen-ts`).
114#[allow(missing_docs)]
115pub mod codegen;
116mod commands;
117/// Plugin configuration (`plugins.widgets` in `tauri.conf.json`).
118pub mod config;
119/// Plugin error type.
120pub mod error;
121/// Fail-closed validation for widget `group` identifiers.
122pub mod group;
123/// Host-side remote image prefetch for WidgetKit / desktop store writes.
124pub mod image_prefetch;
125/// SF Symbol → Material / emoji resolve for non-Apple hosts.
126pub mod icons;
127/// Widget IR models (`WidgetConfig`, `WidgetElement`, …).
128///
129/// Element structs and their fields carry rustdoc used by `schemars` / docs site.
130pub mod models;
131/// Host-side IR normalization (`textStyle` → points, semantic colors → adaptive hex).
132pub mod normalize;
133/// SVG / PNG helpers for Adaptive Cards fallbacks.
134#[allow(missing_docs)]
135pub mod rasterize;
136/// Render receipts written by native / desktop surfaces.
137pub mod receipt;
138/// Canonical layout dumps for snapshot tests.
139pub mod snapshot;
140/// Shared key-value store helpers and action envelopes.
141pub mod store;
142/// Host black-box journal (`WIDGET_DEBUG` / debug builds).
143pub mod trace;
144/// macOS / desktop config transport selection.
145pub mod transport;
146
147#[cfg(target_os = "windows")]
148#[allow(missing_docs)]
149#[cfg_attr(docsrs, doc(cfg(windows)))]
150pub mod windows;
151
152#[cfg(all(target_os = "linux", feature = "linux"))]
153#[allow(missing_docs)]
154#[cfg_attr(docsrs, doc(cfg(all(target_os = "linux", feature = "linux"))))]
155pub mod linux;
156
157#[cfg(target_os = "macos")]
158#[allow(missing_docs)]
159#[cfg_attr(docsrs, doc(cfg(macos)))]
160pub mod macos_transport;
161
162pub use adaptive_card::{to_adaptive_card, to_adaptive_card_for_size, TranspileResult};
163pub use apply::{ApplyOutcome, ReloadOutcome, SkipReason};
164pub use config::{TransportKind, WidgetsPluginConfig};
165pub use error::{Error, Result};
166pub use receipt::{SkippedElement, WidgetRenderReceipt};
167pub use store::WidgetActionEnvelope;
168pub use trace::{TraceEntry, TraceEvent, WidgetTrace};
169pub use transport::{Receipt, Transport};
170
171#[cfg(desktop)]
172pub use desktop::Widget;
173#[cfg(mobile)]
174pub use mobile::Widget;
175
176/// Extension trait for convenient access from any Tauri manager.
177pub trait WidgetExt<R: Runtime> {
178 /// Returns the managed [`Widget`] state.
179 fn widget(&self) -> &Widget<R>;
180}
181
182impl<R: Runtime, T: Manager<R>> WidgetExt<R> for T {
183 fn widget(&self) -> &Widget<R> {
184 self.state::<Widget<R>>().inner()
185 }
186}
187
188/// Initialize the widgets plugin. Register it with `tauri::Builder::plugin()`.
189pub fn init<R: Runtime>() -> TauriPlugin<R, Option<WidgetsPluginConfig>> {
190 let builder = Builder::<R, Option<WidgetsPluginConfig>>::new("widgets")
191 .invoke_handler(tauri::generate_handler![
192 commands::set_items,
193 commands::get_items,
194 commands::set_register_widget,
195 commands::reload_all_timelines,
196 commands::reload_timelines,
197 commands::request_widget,
198 commands::create_widget_window,
199 commands::close_widget_window,
200 commands::set_widget_config,
201 commands::set_widget_config_from_path,
202 commands::get_widget_config,
203 commands::widget_action,
204 commands::poll_pending_actions,
205 commands::report_receipt,
206 commands::get_widget_diagnostics,
207 commands::get_widget_trace,
208 commands::flush_widget_trace,
209 ])
210 .setup(|app, api| {
211 #[cfg(mobile)]
212 let widget = mobile::init(app, api)?;
213 #[cfg(desktop)]
214 let widget = desktop::init(app, api)?;
215 app.manage(widget);
216 Ok(())
217 });
218
219 #[cfg(mobile)]
220 let builder = builder.on_event(|app, event| match event {
221 RunEvent::Ready | RunEvent::Resumed => {
222 if let Some(widget) = app.try_state::<Widget<R>>() {
223 widget.inner().drain_pending_actions_to_events();
224 }
225 }
226 _ => {}
227 });
228
229 #[cfg(desktop)]
230 let builder =
231 builder.register_uri_scheme_protocol(desktop::BUILTIN_PROTOCOL, |_app, _request| {
232 const HTML: &[u8] = include_bytes!("../widget.html");
233 tauri::http::Response::builder()
234 .header("content-type", "text/html; charset=utf-8")
235 .body(Cow::Borrowed(HTML))
236 .unwrap()
237 });
238
239 builder.build()
240}