Skip to main content

g3_native_plugins/
lib.rs

1//! Dioxus wrappers around native platform capabilities: clipboard and share
2//! sheets, Apple and Google sign-in, opening external URLs, hardware back
3//! button handling, and background media playback - plus helpers for the
4//! deep-link metadata files iOS and Android expect a server to host.
5//!
6//! Every plugin sits behind a feature flag, so an app compiles in only what
7//! it uses. Platform coverage is not uniform; see the support matrix in the
8//! README. Where a plugin has no implementation for the current target it
9//! compiles to an inert no-op rather than failing to build, which keeps the
10//! same call sites working on web, desktop, and mobile.
11#![allow(non_snake_case)]
12#![warn(missing_docs)]
13/// Builders for the `apple-app-site-association` and `assetlinks.json` files
14/// that make universal links and App Links resolve to the app.
15pub mod deep_links;
16cfg_if::cfg_if! {
17    if #[cfg(feature = "clipboard")] { mod clipboard; #[allow(unused_imports)] pub use
18    clipboard::*; }
19}
20cfg_if::cfg_if! {
21    if #[cfg(feature = "auth")] { mod auth; #[allow(unused_imports)] pub use auth::*; }
22}
23cfg_if::cfg_if! {
24    if #[cfg(feature = "back-button")] { mod back_button; #[allow(unused_imports)] pub
25    use back_button::*; }
26}
27cfg_if::cfg_if! {
28    if #[cfg(feature = "external-url")] { mod external_url; #[allow(unused_imports)] pub
29    use external_url::*; }
30}
31cfg_if::cfg_if! {
32    if #[cfg(feature = "media")] { mod media; #[allow(unused_imports)] pub use media::*;
33    }
34}
35use dioxus::prelude::*;
36#[cfg(all(
37    any(
38        feature = "auth",
39        feature = "back-button",
40        feature = "clipboard",
41        feature = "external-url",
42        feature = "media"
43    ),
44    any(
45        target_arch = "wasm32",
46        target_os = "android",
47        target_os = "ios",
48        target_os = "macos"
49    )
50))]
51use dioxus_signals::Signal;
52#[cfg(any(
53    target_arch = "wasm32",
54    target_os = "android",
55    target_os = "ios",
56    target_os = "macos"
57))]
58#[derive(Clone, Copy)]
59pub struct NativePlugins {
60    #[cfg(all(
61        feature = "auth",
62        any(target_os = "android", target_os = "ios", target_os = "macos")
63    ))]
64    pub auth: Signal<Auth>,
65    /// Available on every target: the non-Android builds are inert, so callers
66    /// need no cfg of their own.
67    #[cfg(feature = "back-button")]
68    pub back_button: Signal<BackButton>,
69    #[cfg(feature = "clipboard")]
70    pub clipboard: Signal<Clipboard>,
71    #[cfg(all(
72        feature = "external-url",
73        any(target_arch = "wasm32", target_os = "android", target_os = "ios")
74    ))]
75    pub external_url: Signal<ExternalUrl>,
76    #[cfg(feature = "media")]
77    pub media: Signal<Media>,
78}
79#[cfg(any(
80    target_arch = "wasm32",
81    target_os = "android",
82    target_os = "ios",
83    target_os = "macos"
84))]
85impl NativePlugins {
86    pub fn new() -> Self {
87        Self {
88            #[cfg(all(
89                feature = "auth",
90                any(target_os = "android", target_os = "ios", target_os = "macos")
91            ))]
92            auth: Signal::new(Auth::new()),
93            #[cfg(feature = "back-button")]
94            back_button: Signal::new(BackButton::new()),
95            #[cfg(feature = "clipboard")]
96            clipboard: Signal::new(Clipboard::new()),
97            #[cfg(all(
98                feature = "external-url",
99                any(target_arch = "wasm32", target_os = "android", target_os = "ios")
100            ))]
101            external_url: Signal::new(ExternalUrl::new()),
102            #[cfg(feature = "media")]
103            media: Signal::new(Media::new()),
104        }
105    }
106}
107#[cfg(any(
108    target_arch = "wasm32",
109    target_os = "android",
110    target_os = "ios",
111    target_os = "macos"
112))]
113impl Default for NativePlugins {
114    fn default() -> Self {
115        Self::new()
116    }
117}
118#[component]
119pub fn NativePluginsProvider(children: Element) -> Element {
120    #[cfg(any(
121        target_arch = "wasm32",
122        target_os = "android",
123        target_os = "ios",
124        target_os = "macos"
125    ))]
126    use_context_provider(NativePlugins::default);
127    rsx! {
128        {children}
129    }
130}
131#[cfg(test)]
132mod tests {
133    fn production_source(source: &str) -> &str {
134        source
135            .split("#[cfg(test)]")
136            .next()
137            .expect("source should split before tests")
138    }
139    #[test]
140    fn back_button_interception_is_opt_in() {
141        let source = production_source(include_str!("back_button.rs"));
142        assert!(source.contains("intercepting: false"));
143        assert!(source.contains("pub fn set_intercepting"));
144        let kotlin = include_str!(
145            "android/back_button/src/main/kotlin/dev/dioxus/g3_native_plugins/back_button/BackButtonPlugin.kt",
146        );
147        assert!(kotlin.contains("g3nativeback"));
148        assert!(kotlin.contains("cancelable: true"));
149        assert!(kotlin.contains("evaluateJavascript(BACK_EVENT_SCRIPT"));
150        assert!(kotlin.contains("OnBackPressedCallback(false)"));
151        assert!(kotlin.contains("fun fallThroughFromRust()"));
152        assert!(kotlin.contains("current?.isEnabled = false"));
153        assert!(source.contains("pub fn fall_through"));
154        assert!(source.contains("pub const NATIVE_BACK_EVENT"));
155    }
156    #[test]
157    fn native_plugins_provider_owns_plugin_construction() {
158        let source = production_source(include_str!("lib.rs"));
159        let provider_start = source
160            .find("pub fn NativePluginsProvider(children: Element) -> Element")
161            .expect("provider component should be exported");
162        let provider_prefix = &source[..provider_start];
163        assert!(source.contains("pub struct NativePlugins"));
164        assert!(source.contains("pub fn NativePluginsProvider(children: Element) -> Element"),);
165        assert!(
166            !provider_prefix
167                .trim_end()
168                .ends_with("target_os = \"macos\"\n))]\n#[component]"),
169        );
170        assert!(source.contains("use_context_provider(NativePlugins::default)"));
171        assert!(source.contains("{children}"));
172        assert!(source.contains("pub auth: Signal<Auth>"));
173        assert!(source.contains("pub clipboard: Signal<Clipboard>"));
174        assert!(source.contains("pub external_url: Signal<ExternalUrl>"));
175        assert!(source.contains("pub media: Signal<Media>"));
176        assert!(source.contains("auth: Signal::new(Auth::new())"));
177        assert!(source.contains("clipboard: Signal::new(Clipboard::new())"));
178        assert!(source.contains("external_url: Signal::new(ExternalUrl::new())"));
179        assert!(source.contains("media: Signal::new(Media::new())"));
180        assert!(source.contains("impl Default for NativePlugins"));
181        assert!(source.contains("Self::new()"));
182    }
183    #[test]
184    fn ios_clipboard_plugin_supports_copy_and_scene_safe_share() {
185        let swift = include_str!("ios/Sources/ClipboardPlugin.swift");
186        let rust = include_str!("clipboard.rs");
187        assert!(rust.contains("pub fn copy_to_clipboard(&mut self, text: String)"));
188        assert!(rust.contains(
189            "pub fn copyToClipboardFromRust(this: &ClipboardPlugin, text: String) -> String;",
190        ),);
191        assert!(swift.contains("public func copyToClipboardFromRust(_ text: String) -> String",),);
192        assert!(swift.contains("UIPasteboard.general.string = text"));
193        assert!(swift.contains("NSLog(\"[ClipboardPlugin]"));
194        assert!(swift.contains("connectedScenes"));
195        assert!(swift.contains("popover.sourceView = vc.view"));
196        assert!(!swift.contains("keyWindow"));
197    }
198    #[test]
199    fn ios_plugins_share_one_swift_package_for_current_dx() {
200        let manifest = include_str!("ios/Package.swift");
201        let auth = include_str!("auth.rs");
202        let swift_auth = include_str!("ios/Sources/AuthPlugin.swift");
203        let clipboard = include_str!("clipboard.rs");
204        let external_url = include_str!("external_url.rs");
205        assert!(manifest.contains("name: \"DioxusNativePlugins\""));
206        assert!(manifest.contains(".library(name: \"AuthPlugin\""));
207        assert!(manifest.contains(".library(name: \"ClipboardPlugin\""));
208        assert!(manifest.contains(".library(name: \"ExternalUrlPlugin\""));
209        assert!(manifest.contains(".linkedFramework(\"AuthenticationServices\")"));
210        assert!(auth.contains("#[manganis::ffi(\"src/ios\")]"));
211        assert!(
212            auth.contains("pub fn startAppleAuthFromRust(this: &AuthPlugin) -> Option<String>;",),
213        );
214        assert!(auth.contains("pub fn getAuthState(this: &AuthPlugin) -> Option<String>;"),);
215        assert!(!auth.contains("signOutFromRust"));
216        assert!(swift_auth.contains("ASAuthorizationAppleIDProvider"));
217        assert!(swift_auth.contains("public func getAuthState() -> String?"));
218        assert!(swift_auth.contains("identity_token"));
219        assert!(clipboard.contains("#[manganis::ffi(\"src/ios\")]"));
220        assert!(external_url.contains("#[manganis::ffi(\"src/ios\")]"));
221    }
222    #[test]
223    fn android_auth_plugin_exposes_google_sign_in() {
224        let auth = include_str!("auth.rs");
225        let kotlin_auth = include_str!(
226            "android/auth/src/main/kotlin/dev/dioxus/g3_native_plugins/auth/AuthPlugin.kt",
227        );
228        assert!(auth.contains("#[manganis::ffi(\"src/android/auth\")]"));
229        assert!(auth.contains("unsafe extern \"Kotlin\""));
230        assert!(
231            auth.contains("pub fn startGoogleAuthFromRust(this: &AuthPlugin) -> Option<String>;",),
232        );
233        assert!(auth.contains("pub struct AuthResult"));
234        assert!(auth.contains("pub credential: Option<String>"));
235        assert!(
236            auth.contains("pub fn start_google_auth(&mut self) -> Result<AuthResult, String>",),
237        );
238        assert!(kotlin_auth.contains("fun startGoogleAuthFromRust(): String?"));
239        assert!(kotlin_auth.contains("GoogleIdTokenCredential.createFrom"));
240    }
241    #[test]
242    fn android_media_plugin_owns_mobile_playback_capabilities() {
243        let rust = include_str!("media.rs");
244        let kotlin = include_str!(
245            "android/media/src/main/kotlin/dev/dioxus/g3_native_plugins/media/MediaPlugin.kt",
246        );
247        let service = include_str!(
248            "android/media/src/main/kotlin/dev/dioxus/g3_native_plugins/media/PlaybackService.kt",
249        );
250        let manifest = include_str!("android/media/src/main/AndroidManifest.xml");
251        assert!(rust.contains("getClassLoader"));
252        assert!(rust.contains("enter_picture_in_picture"));
253        assert!(rust.contains("set_orientation"));
254        assert!(rust.contains("set_playback_active"));
255        assert!(kotlin.contains("enterPictureInPictureMode"));
256        assert!(kotlin.contains("setActions(pipActions())"));
257        assert!(kotlin.contains("COMMAND_REWIND"));
258        assert!(kotlin.contains("COMMAND_FORWARD"));
259        assert!(kotlin.contains("dataset.androidPip"));
260        assert!(kotlin.contains("tawnynativepictureinpicturechange"));
261        assert!(kotlin.contains("tawnynativeplaybackresume"));
262        assert!(kotlin.contains("Application.ActivityLifecycleCallbacks"));
263        assert!(kotlin.contains("if (!wasActive || titleChanged)"));
264        assert!(!kotlin.contains("setSourceRectHint"));
265        assert!(kotlin.contains("SCREEN_ORIENTATION_SENSOR_LANDSCAPE"));
266        assert!(kotlin.contains("--android-status-bar-inset"));
267        assert!(service.contains("startForeground"));
268        assert!(manifest.contains("android:supportsPictureInPicture=\"true\""));
269        assert!(manifest.contains("foregroundServiceType=\"mediaPlayback\""));
270    }
271    #[test]
272    fn plugin_wrapper_constructors_stay_crate_private_and_lazy() {
273        for (source, plugin_type) in [
274            (production_source(include_str!("auth.rs")), "AuthPlugin"),
275            (
276                production_source(include_str!("clipboard.rs")),
277                "ClipboardPlugin",
278            ),
279            (
280                production_source(include_str!("external_url.rs")),
281                "ExternalUrlPlugin",
282            ),
283        ] {
284            assert!(source.contains("pub(crate) fn new() -> Self"));
285            assert!(!source.contains("pub fn new() -> Self"));
286            assert!(source.contains(&format!("plugin: Option<{plugin_type}>")));
287            assert!(source.contains("Self { plugin: None }"));
288            assert!(source.contains("self.plugin = Some("));
289            assert!(source.contains(&format!("{plugin_type}::new()")));
290            assert!(!source.contains(&format!("plugin: Result<{plugin_type}, String>")));
291        }
292    }
293}