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:

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

isOnline(): boolean

isVisible(): boolean

onWindowEvent and offWindowEvent


Functions for Initialization and Event Handling

initFocus(callback: () => void): () => void

Example Usage:

const cleanup = initFocus(() => {
  console.log('App focused or tab visible - refresh data');
});

// Later, to remove listeners:
cleanup();

initReconnect(callback: () => void): () => void

Example Usage:

const cleanup = initReconnect(() => {
  console.log('Back online - revalidate data');
});

// Later, to remove listeners:
cleanup();

Exported Objects

preset

defaultConfigOptions


Important Implementation Details


Interaction with Other Parts of the System


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.