Offline Detection and Management
The offline detection system serves as a critical safeguard in RitoSwap’s architecture, preventing users from attempting blockchain operations when network connectivity is compromised. This system goes beyond simple connection monitoring—it represents a fundamental commitment to user experience coherence in an always-online blockchain environment.
Design Philosophy
Traditional websites gracefully degrade when offline, displaying cached content or limited functionality. Decentralized applications face a more challenging constraint: every meaningful interaction requires blockchain connectivity. RitoSwap’s offline detection system acknowledges this reality through aggressive monitoring and clear communication, transforming what could be confusing transaction failures into a coherent user experience.
The system operates on three core principles. First, it implements immediate detection through multiple monitoring strategies that catch connectivity changes within seconds. Second, it provides complete interaction blocking via a full-screen modal that prevents any attempt at blockchain operations. Third, it maintains visual continuity by showing the underlying interface through a blurred backdrop while clearly indicating unavailability.
Technical Architecture
The offline detection system integrates directly with the PWA infrastructure through the PWAProvider component, which wraps the entire application and manages connection state globally.
Multi-Strategy Detection
The system employs three complementary detection strategies to ensure no offline state goes unnoticed:
// Event-based detection for immediate response
window.addEventListener('online', handleConnectionChange)
window.addEventListener('offline', handleConnectionChange)
// Polling for edge cases like airplane mode
const interval = setInterval(checkConnection, 1000)
// Focus-based verification for app switching
window.addEventListener('focus', checkConnection)
This multi-layered approach addresses various scenarios where single detection methods might fail. Browser online/offline events handle most network changes, but these events don’t always fire reliably, particularly when users enable airplane mode or experience gradual connection degradation. The one-second polling interval catches these edge cases, while focus detection ensures accurate state after users switch between applications or return from device sleep.
State Management
The connection state propagates through the application via a simple but effective mechanism:
const checkConnection = () => {
const offline = !navigator.onLine
setIsOffline(offline)
// Global state access for debugging
if (typeof window !== 'undefined') {
(window as any).__isOffline = offline
}
}
Storing the offline state on the window object enables debugging and allows other components to access connection status without prop drilling or complex state management. This approach prioritizes simplicity and reliability over architectural purity—appropriate for a critical system component.
User Interface Design
The offline modal represents the visual culmination of the detection system, transforming a technical limitation into a clear, non-threatening user communication.
Visual Hierarchy and Messaging
The modal implements a carefully crafted visual hierarchy that communicates connection loss without inducing panic:
The design incorporates several intentional decisions. The Wi-Fi icon with diagonal strike-through provides immediate recognition across language barriers, utilizing a universal symbol for connectivity issues. The “You’re Offline” headline states the situation clearly without technical jargon or error codes that might confuse non-technical users. The explanatory text “Please reconnect to the internet to continue using RitoSwap” provides actionable guidance while reinforcing the application’s online requirement.
Animation and Feedback
The modal includes subtle animations that serve functional purposes beyond aesthetic appeal:
/* Pulsing Wi-Fi icon indicates active monitoring */
@keyframes pulse {
0%, 100% { opacity: 0.6; }
50% { opacity: 1; }
}
/* Animated loading dots show ongoing connection attempts */
@keyframes loading {
0%, 60%, 100% {
transform: scale(1);
background: rgba(255, 255, 255, 0.6);
}
30% {
transform: scale(1.5);
background: rgba(255, 255, 255, 0.95);
}
}
These animations communicate that the application remains active and monitoring for connection restoration. The pulsing Wi-Fi icon prevents users from perceiving the modal as a frozen error state, while the sequential dot animation reinforces the sense of ongoing activity.
Backdrop Treatment
The modal’s backdrop implementation balances visibility with context preservation:
.modalOverlay {
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(10px);
z-index: 10000;
}
The blur effect maintains visual connection to the underlying application while clearly indicating its unavailability. This approach prevents user disorientation that might occur with a completely opaque overlay, while the high z-index ensures the modal remains visible above all other interface elements, including other modals or dropdowns.
Integration with Application State
The offline detection system integrates seamlessly with RitoSwap’s broader state management architecture, ensuring consistent behavior across all components.
Automatic UI Blocking
When offline state is detected, the modal automatically prevents all user interactions through its full-screen overlay. This approach eliminates the need for individual components to check connection state before attempting blockchain operations.
State Preservation
The application maintains its current state during offline periods, allowing users to resume exactly where they left off once connectivity returns. NFT ownership data, wallet connections, and UI state all persist through offline episodes, creating a seamless recovery experience.
Instant Recovery
The moment connectivity returns, the system immediately removes the modal overlay:
useEffect(() => {
if (!isOffline && modalVisible) {
// Instant removal when connection restored
setModalVisible(false)
}
}, [isOffline])
This instant recovery avoids any delay that might make users question whether their connection has truly been restored.
Mobile Considerations
While designed with PWA installation in mind, the offline detection system accounts for the unique challenges of mobile connectivity.
Mobile devices frequently experience connection state changes as users move between Wi-Fi and cellular networks, enter buildings with poor reception, or enable airplane mode for battery conservation. The aggressive one-second polling interval ensures these transitions are caught quickly, preventing users from initiating transactions during momentary connection losses.
The modal’s touch-friendly design includes appropriately sized elements and clear visual hierarchy that remains effective on smaller screens. The centered layout adapts to various screen sizes without requiring responsive breakpoints.
Performance Optimization
Despite its aggressive monitoring approach, the offline detection system implements several optimizations to minimize performance impact.
The connection check logic remains lightweight, simply reading the navigator.onLine
property rather than attempting network requests. This approach provides instant results without the latency or resource consumption of actual connectivity tests.
Event listeners are properly cleaned up when the component unmounts, preventing memory leaks in single-page application contexts:
return () => {
clearInterval(interval)
window.removeEventListener('online', handleConnectionChange)
window.removeEventListener('offline', handleConnectionChange)
window.removeEventListener('focus', checkConnection)
}
Testing and Debugging
The offline detection system includes built-in debugging capabilities to assist development and troubleshooting.
Browser DevTools Testing
Developers can simulate offline conditions using Chrome DevTools:
Step 1: Open DevTools Network Panel
Access the Network panel and locate the connection throttling dropdown.
Step 2: Select Offline Mode
Choose “Offline” from the presets to immediately trigger the offline modal.
Step 3: Verify Modal Behavior
Confirm the modal appears within one second and blocks all interactions.
Step 4: Restore Connection
Return to “Online” mode and verify instant modal removal.
Debug State Access
The global offline state stored on the window object enables console debugging:
// Check current offline state
console.log(window.__isOffline)
// Monitor state changes
Object.defineProperty(window, '__isOffline', {
set(value) {
console.log('Offline state changed:', value)
this._isOffline = value
},
get() {
return this._isOffline
}
})
Edge Cases and Limitations
The offline detection system handles most connectivity scenarios effectively, but certain edge cases deserve consideration.
The navigator.onLine
API indicates browser-level connectivity but cannot guarantee actual internet access. Users might be connected to a Wi-Fi network without internet access, causing the API to report online status incorrectly. While this limitation exists, attempting to verify true internet connectivity would require network requests that could impact performance and introduce latency.
Some browser extensions or privacy tools might interfere with online/offline events, potentially causing detection delays. The one-second polling interval serves as a backup for these scenarios.
Corporate networks with aggressive proxies or firewalls might cause intermittent connectivity that triggers frequent modal appearances. In these environments, users might need to rely on more stable connections for optimal experience.
Summary
RitoSwap’s offline detection system exemplifies thoughtful design for the unique constraints of blockchain applications. By implementing aggressive monitoring, clear visual communication, and seamless recovery, the system transforms a technical limitation into a coherent user experience. The modal’s design carefully balances urgency with calm guidance, ensuring users understand the situation without feeling alarmed.
This infrastructure proves particularly valuable in the PWA context, where users expect application-like behavior even when connectivity issues arise. Rather than allowing confusing transaction failures or unclear error states, the offline detection system provides immediate, unmistakable feedback that maintains user trust and application coherence.
The implementation demonstrates that even fundamental constraints like blockchain’s online requirements can be addressed through careful UX design and robust technical architecture, creating an experience that feels polished and professional regardless of network conditions.