web-preset.ts
Overview
The web-preset.ts file provides utility functions and configuration presets designed to manage and track the online/offline status and visibility state of a web application. It addresses browser inconsistencies (notably a Chromium bug affecting reliable online status detection) by implementing a workaround that assumes the app is online on initial load and updates status through event listeners for network connectivity and page visibility changes.
This file exports:
A
presetobject exposing methods to check if the app is currently online or visible.A
defaultConfigOptionsobject providing initialization handlers (initFocus,initReconnect) for focus and network reconnect events, intended for integration into a broader provider configuration system.
The utilities here are essential for applications that rely on reactive behavior based on network connectivity or user focus, such as data revalidation or UI updates when the user returns to the page or regains internet connection.
Detailed Explanation of Elements
Variables and Functions
online: boolean
Purpose: Tracks the current online status of the application.
Initialization: Starts as
truedue to the Chromium bug withnavigator.onLine.Usage: Updated internally by event listeners for
onlineandofflinewindow events.
isOnline(): boolean
Returns: The current online status (
trueorfalse).Usage: Used to query whether the app is considered online.
isVisible(): boolean
Returns:
trueif the document is visible or if visibility state is undefined; otherwisefalse.Details: Uses the document.visibilityState property to determine if the page is currently visible to the user.
Fallback: If
documentis not defined or visibilityState is undefined, assumes the app is visible.
onWindowEvent and offWindowEvent
Purpose: Utility bindings for adding and removing window event listeners safely.
Details: These are either bound to
window.addEventListenerandwindow.removeEventListeneror fallback to no-op functions (noop) whenwindowis undefined (e.g., in Node.js or React Native environments).Usage: Used internally to attach/detach event listeners for focus and network events.
Functions for Initialization and Event Handling
initFocus(callback: () => void): () => void
Purpose: Sets up event listeners to trigger a callback when the browser window gains focus or when the page visibility changes to visible.
Parameters:
callback: A function to be called when the page gains focus or becomes visible.
Returns: A cleanup function that removes the event listeners.
Implementation Details:
Adds a
visibilitychangelistener to the document.Adds a
focuslistener to the window.On either event, the callback is triggered.
Use Case: Typically used to revalidate or refresh data when the user returns to the app or switches to the tab.
Example Usage:
const cleanup = initFocus(() => {
console.log('App focused or tab visible - refresh data');
});
// Later, to remove listeners:
cleanup();
initReconnect(callback: () => void): () => void
Purpose: Sets up event listeners to monitor network connectivity changes and trigger a callback when the app goes online.
Parameters:
callback: A function to be called when the app transitions to an online state.
Returns: A cleanup function that removes the event listeners.
Implementation Details:
Listens for
onlineandofflineevents on the window.When
onlinefires, setsonline = trueand calls the callback.When
offlinefires, setsonline = falsebut does not call the callback (no revalidation).
Use Case: Useful for triggering data refetch or synchronization when the network connection is restored.
Example Usage:
const cleanup = initReconnect(() => {
console.log('Back online - revalidate data');
});
// Later, to remove listeners:
cleanup();
Exported Objects
preset
Type:
readonly { isOnline: () => boolean; isVisible: () => boolean }Description: An object exposing methods to check online and visibility states.
Usage: Can be imported and used to query the current state.
defaultConfigOptions
Type:
ProviderConfiguration(imported type)Description: Provides default initialization functions (
initFocus,initReconnect) used by higher-level provider components or modules to register event listeners for focus and reconnect events.Usage: Used as default options when configuring the provider or client that manages data fetching or UI updates.
Important Implementation Details
Chromium Bug Workaround:
The file addresses Chromium bug #678075 that causesnavigator.onLineto be unreliable on initial app load. The workaround is to assume the app is online initially and update the status reactively through event listeners.Universal Environment Support:
The code safely checks for the existence ofwindowanddocumentto ensure compatibility with environments where these globals do not exist (e.g., server-side rendering, React Native).Event Listener Management:
BothinitFocusandinitReconnectreturn cleanup functions for removing event listeners, promoting good resource management and preventing memory leaks.
Interaction with Other Parts of the System
Type Dependency:
Imports theProviderConfigurationtype from'../types', indicating integration with a larger configuration or provider system.Helper Functions:
Utilizes utility functionsisWindowDefined,isDocumentDefined(likely simple boolean checks for environment detection), andisUndefinedandnoopfrom shared helper modules.Provider Configuration:
The exporteddefaultConfigOptionsare likely used in a data-fetching or state management provider component to handle revalidation triggers based on focus and network status, enhancing the responsiveness and efficiency of the application.
Mermaid Diagram: Class/Module Structure
classDiagram
class web-preset {
+isOnline(): boolean
+isVisible(): boolean
+initFocus(callback: () => void): () => void
+initReconnect(callback: () => void): () => void
-online: boolean
-onWindowEvent: (event: string, handler: EventListener) => void
-offWindowEvent: (event: string, handler: EventListener) => void
}
web-preset : +preset
web-preset : +defaultConfigOptions
Summary
The web-preset.ts file is a lightweight but crucial utility module that provides reliable detection and handling of online/offline states and page visibility changes in web applications. By abstracting away browser inconsistencies and environment differences, it enables other parts of the system to react appropriately to focus and connectivity changes, improving user experience and data freshness. Its design promotes modularity, cleanup safety, and easy integration into provider-based architectures.