Skip to main content

oxigeo_pwa/
lib.rs

1//! Progressive Web App capabilities for OxiGeo.
2//!
3//! This crate provides comprehensive PWA functionality including:
4//! - Service worker integration
5//! - Offline caching strategies
6//! - Background sync
7//! - Push notifications
8//! - Web app manifest generation
9//! - PWA lifecycle management
10//! - Geospatial data caching optimizations
11//!
12//! # Examples
13//!
14//! ## Basic Service Worker Registration
15//!
16//! ```no_run
17//! use oxigeo_pwa::service_worker::ServiceWorkerRegistry;
18//!
19//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
20//! let registry = ServiceWorkerRegistry::with_script_url("/sw.js")
21//!     .with_scope("/app");
22//!
23//! let registration = registry.register().await?;
24//! # Ok(())
25//! # }
26//! ```
27//!
28//! ## Caching Strategies
29//!
30//! ```no_run
31//! use oxigeo_pwa::cache::strategies::{CacheStrategy, StrategyType};
32//!
33//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
34//! // Create a cache-first strategy for static assets
35//! let strategy = CacheStrategy::cache_first("static-assets");
36//!
37//! // Or network-first for API calls
38//! let api_strategy = CacheStrategy::network_first("api-cache");
39//! # Ok(())
40//! # }
41//! ```
42//!
43//! ## Geospatial Tile Caching
44//!
45//! ```no_run
46//! use oxigeo_pwa::cache::geospatial::{GeospatialCache, BoundingBox};
47//!
48//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
49//! let cache = GeospatialCache::with_defaults();
50//!
51//! // Cache tiles for an area
52//! let bbox = BoundingBox::new(-180.0, -85.0, 180.0, 85.0)?;
53//! let tiles = cache.prefetch_tiles(&bbox, 0..5, "https://tiles.example.com").await?;
54//! # Ok(())
55//! # }
56//! ```
57//!
58//! ## Push Notifications
59//!
60//! ```no_run
61//! use oxigeo_pwa::notifications::{NotificationManager, NotificationConfig};
62//!
63//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
64//! let manager = NotificationManager::new();
65//!
66//! // Request permission
67//! let permission = NotificationManager::request_permission().await?;
68//!
69//! if permission.is_granted() {
70//!     let config = NotificationConfig::new("New Data Available")
71//!         .with_body("Your geospatial data has been updated")
72//!         .with_icon("/icon.png");
73//!
74//!     manager.show(&config).await?;
75//! }
76//! # Ok(())
77//! # }
78//! ```
79//!
80//! ## Web App Manifest
81//!
82//! ```
83//! use oxigeo_pwa::manifest::{ManifestBuilder, DisplayMode};
84//!
85//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
86//! let manifest = ManifestBuilder::geospatial("GeoApp", "Geo")
87//!     .description("A powerful geospatial PWA")
88//!     .colors("#ffffff", "#007bff")
89//!     .add_standard_icons("/icons")
90//!     .build();
91//!
92//! let json = manifest.to_json()?;
93//! # Ok(())
94//! # }
95//! ```
96//!
97//! # Features
98//!
99//! - `default`: Basic PWA functionality with console error hooks
100//! - `notifications`: Push notification support
101//! - `background-sync`: Background synchronization
102//! - `geospatial-cache`: Geospatial-specific caching optimizations
103
104#![warn(missing_docs)]
105#![deny(unsafe_code)]
106
107pub mod cache;
108pub mod error;
109pub mod lifecycle;
110pub mod manifest;
111pub mod notifications;
112pub mod service_worker;
113pub mod sync;
114
115// Re-export commonly used types
116pub use error::{PwaError, Result};
117
118pub use cache::{
119    CacheManager, CacheStorageManager,
120    geospatial::{BoundingBox, GeospatialCache, TileCoord},
121    strategies::{CacheStrategy, StrategyType},
122};
123
124pub use lifecycle::{
125    DisplayModeDetection, InstallPrompt, InstallState, PwaLifecycle, UpdateManager,
126};
127
128pub use manifest::{
129    AppIcon, DisplayMode, ManifestBuilder, Orientation, Screenshot, WebAppManifest,
130};
131
132pub use notifications::{
133    NotificationAction, NotificationConfig, NotificationManager, Permission,
134    PushNotificationManager,
135};
136
137pub use service_worker::{
138    ServiceWorkerEvents, ServiceWorkerMessaging, ServiceWorkerRegistry, ServiceWorkerScope,
139    UpdateViaCache, WorkerType, get_registration, get_service_worker_container,
140    is_service_worker_supported, register_service_worker,
141};
142
143pub use sync::{BackgroundSync, QueuedOperation, SyncCoordinator, SyncOptions, SyncQueue};
144
145/// Initialize PWA with console error panic hook.
146pub fn initialize() {
147    #[cfg(feature = "console_error_panic_hook")]
148    console_error_panic_hook::set_once();
149}
150
151/// PWA configuration and initialization.
152pub struct PwaConfig {
153    /// Service worker script URL
154    pub service_worker_url: String,
155
156    /// Service worker scope
157    pub scope: Option<String>,
158
159    /// Enable automatic cache management
160    pub enable_cache_management: bool,
161
162    /// Enable background sync
163    pub enable_background_sync: bool,
164
165    /// Enable notifications
166    pub enable_notifications: bool,
167
168    /// Enable geospatial cache optimizations
169    pub enable_geospatial_cache: bool,
170
171    /// Type of service worker to register (classic or ES module)
172    pub worker_type: WorkerType,
173
174    /// Update-via-cache mode used when registering the service worker
175    pub update_via_cache: UpdateViaCache,
176}
177
178impl Default for PwaConfig {
179    fn default() -> Self {
180        Self {
181            service_worker_url: "/sw.js".to_string(),
182            scope: None,
183            enable_cache_management: true,
184            enable_background_sync: false,
185            enable_notifications: false,
186            enable_geospatial_cache: true,
187            worker_type: WorkerType::Classic,
188            update_via_cache: UpdateViaCache::Imports,
189        }
190    }
191}
192
193impl PwaConfig {
194    /// Create a new PWA configuration.
195    pub fn new() -> Self {
196        Self::default()
197    }
198
199    /// Set the service worker URL.
200    pub fn with_service_worker_url(mut self, url: impl Into<String>) -> Self {
201        self.service_worker_url = url.into();
202        self
203    }
204
205    /// Set the scope.
206    pub fn with_scope(mut self, scope: impl Into<String>) -> Self {
207        self.scope = Some(scope.into());
208        self
209    }
210
211    /// Enable cache management.
212    pub fn with_cache_management(mut self, enable: bool) -> Self {
213        self.enable_cache_management = enable;
214        self
215    }
216
217    /// Enable background sync.
218    pub fn with_background_sync(mut self, enable: bool) -> Self {
219        self.enable_background_sync = enable;
220        self
221    }
222
223    /// Enable notifications.
224    pub fn with_notifications(mut self, enable: bool) -> Self {
225        self.enable_notifications = enable;
226        self
227    }
228
229    /// Enable geospatial cache.
230    pub fn with_geospatial_cache(mut self, enable: bool) -> Self {
231        self.enable_geospatial_cache = enable;
232        self
233    }
234
235    /// Set the service worker type (classic or ES module).
236    pub fn with_worker_type(mut self, worker_type: WorkerType) -> Self {
237        self.worker_type = worker_type;
238        self
239    }
240
241    /// Set the update-via-cache mode used when registering the service worker.
242    pub fn with_update_via_cache(mut self, mode: UpdateViaCache) -> Self {
243        self.update_via_cache = mode;
244        self
245    }
246}
247
248/// Main PWA application manager.
249pub struct PwaApp {
250    config: PwaConfig,
251    lifecycle: PwaLifecycle,
252    cache_manager: Option<CacheManager>,
253    geospatial_cache: Option<GeospatialCache>,
254    notification_manager: Option<NotificationManager>,
255    sync_coordinator: Option<SyncCoordinator>,
256}
257
258impl PwaApp {
259    /// Create a new PWA application.
260    pub fn new(config: PwaConfig) -> Self {
261        Self {
262            config,
263            lifecycle: PwaLifecycle::new(),
264            cache_manager: None,
265            geospatial_cache: None,
266            notification_manager: None,
267            sync_coordinator: None,
268        }
269    }
270
271    /// Create with default configuration.
272    pub fn with_defaults() -> Self {
273        Self::new(PwaConfig::default())
274    }
275
276    /// Initialize the PWA application.
277    pub async fn initialize(&mut self) -> Result<()> {
278        // Initialize console error hook
279        initialize();
280
281        // Initialize lifecycle
282        self.lifecycle.initialize()?;
283
284        // Register service worker
285        let registration = register_service_worker(
286            &self.config.service_worker_url,
287            self.config.scope.as_deref(),
288            self.config.worker_type,
289            self.config.update_via_cache,
290        )
291        .await?;
292
293        self.lifecycle.set_registration(registration.clone());
294
295        // Initialize cache management
296        if self.config.enable_cache_management {
297            self.cache_manager = Some(CacheManager::new("oxigeo-pwa-cache"));
298        }
299
300        // Initialize geospatial cache
301        if self.config.enable_geospatial_cache {
302            self.geospatial_cache = Some(GeospatialCache::with_defaults());
303        }
304
305        // Initialize notification manager
306        if self.config.enable_notifications {
307            self.notification_manager = Some(NotificationManager::new());
308        }
309
310        // Initialize sync coordinator
311        if self.config.enable_background_sync {
312            self.sync_coordinator = Some(SyncCoordinator::new(registration));
313        }
314
315        Ok(())
316    }
317
318    /// Get the lifecycle manager.
319    pub fn lifecycle(&self) -> &PwaLifecycle {
320        &self.lifecycle
321    }
322
323    /// Get mutable lifecycle manager.
324    pub fn lifecycle_mut(&mut self) -> &mut PwaLifecycle {
325        &mut self.lifecycle
326    }
327
328    /// Get the cache manager.
329    pub fn cache_manager(&self) -> Option<&CacheManager> {
330        self.cache_manager.as_ref()
331    }
332
333    /// Get the geospatial cache.
334    pub fn geospatial_cache(&self) -> Option<&GeospatialCache> {
335        self.geospatial_cache.as_ref()
336    }
337
338    /// Get the notification manager.
339    pub fn notification_manager(&self) -> Option<&NotificationManager> {
340        self.notification_manager.as_ref()
341    }
342
343    /// Get the sync coordinator.
344    pub fn sync_coordinator(&self) -> Option<&SyncCoordinator> {
345        self.sync_coordinator.as_ref()
346    }
347
348    /// Get mutable sync coordinator.
349    pub fn sync_coordinator_mut(&mut self) -> Option<&mut SyncCoordinator> {
350        self.sync_coordinator.as_mut()
351    }
352
353    /// Check if running as PWA.
354    pub fn is_pwa(&self) -> bool {
355        self.lifecycle.is_pwa()
356    }
357
358    /// Check if install prompt is available.
359    pub fn can_install(&self) -> bool {
360        self.lifecycle.can_install()
361    }
362
363    /// Show install prompt.
364    pub async fn prompt_install(&mut self) -> Result<bool> {
365        self.lifecycle.prompt_install().await
366    }
367
368    /// Get the configuration.
369    pub fn config(&self) -> &PwaConfig {
370        &self.config
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377
378    #[test]
379    fn test_pwa_config() {
380        let config = PwaConfig::new()
381            .with_service_worker_url("/custom-sw.js")
382            .with_scope("/app")
383            .with_cache_management(true)
384            .with_geospatial_cache(true);
385
386        assert_eq!(config.service_worker_url, "/custom-sw.js");
387        assert_eq!(config.scope, Some("/app".to_string()));
388        assert!(config.enable_cache_management);
389        assert!(config.enable_geospatial_cache);
390    }
391
392    #[test]
393    #[cfg(target_arch = "wasm32")]
394    fn test_pwa_app_creation() {
395        let app = PwaApp::with_defaults();
396        assert_eq!(app.config.service_worker_url, "/sw.js");
397        assert!(app.cache_manager.is_none()); // Not initialized yet
398    }
399
400    #[test]
401    fn test_pwa_config_builder() {
402        let config = PwaConfig::default();
403        assert_eq!(config.service_worker_url, "/sw.js");
404        assert!(config.enable_cache_management);
405        assert!(config.enable_geospatial_cache);
406    }
407}