### run Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md Executes the complete PWA setup flow, including checking installation status, displaying relevant UI, and attaching event listeners for installation prompts. ```APIDOC ## run(isSetupEnabled?: boolean): void ### Description Runs the complete PWA setup flow. This method checks the PWA installation status, displays the appropriate UI if needed, and attaches event listeners to manage user interactions related to installation prompts. The setup UI and prompts can be optionally enabled or disabled. ### Method `run` ### Parameters #### Query Parameters - **isSetupEnabled** (boolean) - Optional - Defaults to `true`. Whether to enable setup UI and prompts. ### Usage Example ```javascript const setup = new PWASetup(); setup.run(true); window.addEventListener("DOMContentLoaded", () => { setup.run(true); }); ``` ``` -------------------------------- ### Run Complete PWA Setup Flow Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md The `run` method initiates the full PWA setup process, including checking installation status, displaying relevant UI, and attaching event listeners for user interaction. It can be configured to enable or disable setup UI prompts. ```javascript const setup = new PWASetup(); // Run full setup flow setup.run(true); // Or run on demand window.addEventListener("DOMContentLoaded", () => { setup.run(true); }); ``` ```javascript const setup = new PWASetup("#install", "modal"); setup.run(true); // 1. Checks if PWA is installed // 2. If not, shows appropriate UI (modal or manual instructions) // 3. Attaches event listeners for user interaction // 4. Handles install prompt when user clicks button ``` -------------------------------- ### Initialize PWASetup Manually Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md Create a new `PWASetup` instance with custom selectors for the install element and modal. Then, call the `run` method with a boolean to control the setup UI. ```javascript const setup = new PWASetup(); // Uses defaults: "#install", "modal" setup.run(isSetupEnabled); ``` -------------------------------- ### PWA Setup with Install Button Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/README.md Integrate the PWA component and PWABtn for an installable app experience with a custom button. ```astro --- import { PWA, PWABtn } from "webapp-astro-pwa"; --- ``` -------------------------------- ### Custom PWAManager Implementation Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md Implement a custom class to manage PWA setup, initializing `PWASetup` with specific selectors and controlling the display of the setup UI based on installation status. ```javascript class MyPWAManager { private setup: PWASetup; constructor() { this.setup = new PWASetup("#my-install-btn", "#my-modal"); } init() { // Only show setup if not already installed if (!this.setup.getIsInstalled()) { this.setup.run(true); } } getInstallStatus() { return { isInstalled: this.setup.getIsInstalled(), prompt: this.setup.getInstallPrompt(), }; } } ``` -------------------------------- ### PWASetup Class Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/INDEX.md Orchestrates the complete PWA setup and installation flow. ```APIDOC ## PWASetup Class ### Constructor - `new PWASetup(installSelector?, popoverId?)` - **Description**: Initializes the PWA setup orchestration. - **Parameters**: - `installSelector` (string) - Optional - CSS selector for the installation trigger element. - `popoverId` (string) - Optional - The ID of the popover element. ### Instance Methods #### showInstallationMessage(id) - **Description**: Displays an installation message to the user. - **Parameters**: - `id` (string) - Required - The identifier for the message to display. #### checkIsPWAInstalled(isSetupEnabled?) - **Description**: Checks if the PWA is installed and shows the appropriate UI. - **Parameters**: - `isSetupEnabled` (boolean) - Optional - Flag to enable/disable setup UI. - **Returns**: `Promise` #### run(isSetupEnabled?) - **Description**: Executes the PWA setup flow. - **Parameters**: - `isSetupEnabled` (boolean) - Optional - Flag to enable/disable setup flow. - **Returns**: `Promise` #### getInstallPrompt() - **Description**: Retrieves the install prompt handler. - **Returns**: `PWAInstallPrompt` #### getIsInstalled() - **Description**: Gets the current installation status of the PWA. - **Returns**: `boolean` ### Factory Function #### runPWASetup(isSetupEnabled) - **Description**: A factory function to run the PWA setup flow. - **Parameters**: - `isSetupEnabled` (boolean) - Optional - Flag to enable/disable setup flow. - **Returns**: `Promise` ``` -------------------------------- ### Check PWA Installation Status and Show UI Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md Use `checkIsPWAInstalled` to automatically display the appropriate UI based on the PWA's installation status and browser capabilities. This method can be configured to skip setup UI. ```javascript const setup = new PWASetup(); // Automatically show appropriate UI for current browser setup.checkIsPWAInstalled(true); // Skip setup UI setup.checkIsPWAInstalled(false); ``` -------------------------------- ### Get Internal PWA Install Prompt Handler Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md Retrieve the internal `PWAInstallPrompt` object using `getInstallPrompt`. This allows direct access to its properties and methods for advanced control over the installation process. ```javascript const setup = new PWASetup(); const promptHandler = setup.getInstallPrompt(); // Access internal properties console.log(promptHandler.installPrompt); console.log(promptHandler.btn); // Call methods directly promptHandler.checkIsPWAInstalled(); ``` -------------------------------- ### Handle Before Install Prompt Event Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWAInstallPrompt.md Attaches to the 'beforeinstallprompt' event to make the install button available. It stores the event and makes the button visible. ```javascript const installPrompt = new PWAInstallPrompt("#install"); const btn = document.getElementById("install"); window.addEventListener("beforeinstallprompt", (e) => { e.preventDefault(); installPrompt.beforeInstallHandler(e, btn); }); ``` -------------------------------- ### Basic PWA Install Flow Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWAInstallPrompt.md Initialize PWAInstallPrompt and attach event listeners. Check if the PWA is already installed to conditionally display prompts or messages. ```javascript const installPrompt = new PWAInstallPrompt("#install-btn"); // Attach event listeners installPrompt.runEvents(false); // Check if already installed if (installPrompt.checkIsPWAInstalled()) { console.log("App is already installed"); } else { console.log("App not installed, ready for installation"); } ``` -------------------------------- ### Constructor Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWAInstallPrompt.md Initializes the PWAInstallPrompt with a button selector. It sets up the necessary properties to manage the install prompt and the associated UI element. ```APIDOC ## constructor(btnId: string) ### Description Initializes the PWAInstallPrompt with a button selector. ### Parameters #### Path Parameters - **btnId** (string) - Required - CSS selector for the install button element (e.g., `"#install"`) ### Request Example ```javascript const installPrompt = new PWAInstallPrompt("#install-button"); // installPrompt.btn now references the element with id="install-button" ``` ``` -------------------------------- ### installPWABtnHandler Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWAInstallPrompt.md Handles the click event for the PWA installation button, attempting to show the native install prompt. ```APIDOC ## installPWABtnHandler() ### Description Handles the click event for the PWA installation button, attempting to show the native install prompt. ### Method `installPWABtnHandler` ### Response #### Success Response (Promise) - Returns a Promise that resolves when the installation prompt has been handled. ``` -------------------------------- ### Instantiate PWAInstallPrompt Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWAInstallPrompt.md Initialize a new PWAInstallPrompt instance, linking it to a specific install button element on the page. ```javascript const installPrompt = new PWAInstallPrompt("#install-button"); // installPrompt.btn now references the element with id="install-button" ``` -------------------------------- ### Install webapp-astro-pwa Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/README.md Install the library using npm. This command also automatically adds a `generateAndBundleSW` script to your project's `package.json`. ```sh npm install webapp-astro-pwa ``` -------------------------------- ### beforeInstallHandler Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWAInstallPrompt.md Responds to the `beforeinstallprompt` event, making the install button visible and storing the event for later use. ```APIDOC ## beforeInstallHandler(event: Event, btn: HTMLElement): void ### Description Handles the `beforeinstallprompt` event, which allows the application to prompt the user to install the PWA. This method makes the install button visible and stores the event object. ### Parameters #### Path Parameters * **event** (`Event`) - Required - The `beforeinstallprompt` event object. * **btn** (`HTMLElement`) - Required - The install button element to be enabled and made visible. ### Side Effects * Stores the provided `event` object in `this.installPrompt`. * Removes the `hidden` attribute from the `btn` element, making it visible. ### Usage ```javascript const installPrompt = new PWAInstallPrompt("#install"); const btn = document.getElementById("install"); window.addEventListener("beforeinstallprompt", (e) => { e.preventDefault(); installPrompt.beforeInstallHandler(e, btn); }); ``` ``` -------------------------------- ### Install webapp-astro-pwa Package Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/README.md Install the webapp-astro-pwa package using npm. ```bash # Install package npm install webapp-astro-pwa ``` -------------------------------- ### Development Server Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/README.md Command to start the development server for local testing. ```bash # Development npm run dev ``` -------------------------------- ### Manual PWA Installation on Button Click Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWAInstallPrompt.md Manually trigger the PWA installation prompt when a specific button is clicked. This provides more control over when the installation flow is initiated. ```javascript const installPrompt = new PWAInstallPrompt("#install-btn"); const btn = document.getElementById("install-btn"); installPrompt.runEvents(false); btn.addEventListener("click", async () => { await installPrompt.installPWABtnHandler(); }); ``` -------------------------------- ### Display Installation Message by ID Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md Use `showInstallationMessage` to display a specific HTML element containing installation instructions, identified by its ID. This is useful for browsers that do not support the `beforeinstallprompt` event. ```javascript const setup = new PWASetup(); // Show message for browsers without beforeinstallprompt support setup.showInstallationMessage("installation-message"); ``` -------------------------------- ### Fix Config File Not Found Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/errors.md If the `pwa.config.json` file is not found, this command installs the package, which runs a setup script to create the configuration file. ```bash npm install webapp-astro-pwa # Runs postinstall setup.js ``` -------------------------------- ### PWAInstallPrompt Class Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/INDEX.md Manages the PWA installation prompt flow. ```APIDOC ## PWAInstallPrompt Class ### Constructor - `new PWAInstallPrompt(btnId)` - **Description**: Initializes the install prompt handler. - **Parameters**: - `btnId` (string) - Required - The ID of the button that triggers the install prompt. ### Instance Properties - `btnId` (string): The ID of the trigger button. - `installPrompt` (object): The native browser install prompt event object. - `btn` (HTMLElement): The button element. ### Methods #### checkIsPWAInstalled() - **Description**: Checks if the PWA is currently installed. - **Returns**: `boolean` #### hideButton(btn) - **Description**: Hides the specified button element. - **Parameters**: - `btn` (HTMLElement) - Required - The button element to hide. #### installPWABtnHandler() - **Description**: Triggers the PWA installation prompt. - **Usage**: Call this method when the user intends to install the PWA. #### beforeInstallHandler(event, btn) - **Description**: Handles the `beforeinstallprompt` event. - **Parameters**: - `event` (Event) - Required - The `beforeinstallprompt` event object. - `btn` (HTMLElement) - Required - The button element associated with the prompt. #### runEvents(isPopup, popup?) - **Description**: Attaches necessary event listeners for the install prompt. - **Parameters**: - `isPopup` (boolean) - Required - Indicates if the prompt is displayed as a popup. - `popup` (HTMLElement) - Optional - The popup element if `isPopup` is true. ``` -------------------------------- ### Example pwa.config.json Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/SWUtils.md An example JSON object demonstrating how to configure SWUtils settings, including enabling notifications and disabling automatic permission requests. ```json { "notification": true, "notificationAutoRequestPermission": false, "notificationBtn": true, "forceUpdate": true } ``` -------------------------------- ### PWAInstallPrompt Class Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/README.md Manages the browser's native install prompt and button interactions for Progressive Web Apps. ```APIDOC ## PWAInstallPrompt ### Description Manages browser's native install prompt and button interactions. ### Methods - `constructor(btnId)`: Initialize with button selector. - `checkIsPWAInstalled()`: Check if running in standalone mode. - `hideButton(btn)`: Hide install button. - `installPWABtnHandler()`: Trigger install prompt. - `beforeInstallHandler(event, btn)`: Handle beforeinstallprompt event. - `runEvents(isPopup, popup?)`: Attach event listeners. ``` -------------------------------- ### pwa.config.json Example Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PoweredWebAppBuilder.md An example configuration file for pwa.config.json. This file is located at the project root and is read by Astro components at runtime to determine behavior. ```json { "cacheAssets": "static-assets_v1", "strategy": "StaleWhileRevalidate", "isManifest": true, "isInstallBtnVisible": true, "manifest": { /* ... */ }, "icons": [ /* ... */ ], "meta": [ /* ... */ ] } ``` -------------------------------- ### Use PWASetupWindow Component Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/index.md Implement PWASetupWindow for a customizable popover modal to guide users through PWA installation. It supports fallback UI for browsers without native popover support. ```astro ``` -------------------------------- ### BeforeInstallPromptEvent Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/types.md Extended Event interface for the PWA install prompt. It provides methods to trigger the install prompt and access the user's choice. ```APIDOC ## Interface: BeforeInstallPromptEvent ### Description Extended Event interface for the PWA install prompt. It provides methods to trigger the install prompt and access the user's choice. ### Properties - **`prompt`** (() => Promise) - Method to trigger the browser's install prompt. - **`userChoice`** (Promise<{outcome: "accepted" | "dismissed"; platform?: string}>) - Promise resolving with the user's installation decision. ### Source `src/types.ts` ``` -------------------------------- ### Initialize PWASetup Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md Instantiate the PWASetup class. Use default selectors or provide custom CSS selectors for the install button and modal/popover elements. ```javascript // Default behavior const setup = new PWASetup(); // Custom selectors const setup = new PWASetup("#custom-btn", "custom-modal"); ``` -------------------------------- ### Example of an icon configuration Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/types.md Provides an example of an icon configuration for a PWA manifest, specifying the icon's properties and path. Used for PWA manifest icon injection. ```typescript { rel: "icon", type: "image/png", sizes: "192x192", href: "/manifest_imgs/icon192x192.png" } ``` -------------------------------- ### Show PWA Install Button Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/configuration.md Set `isInstallBtnVisible` to true to display the PWA install button or prompt. This option requires `isManifest` to be true. ```javascript PoweredWebAppBuilder({ isInstallBtnVisible: true, }) ``` -------------------------------- ### Login Endpoint Example Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/endpoints.md Example of how to log in to the push API to obtain a user UUID. Stores the UUID in local storage for subsequent requests. ```javascript const loginResponse = await fetch( "/pushapi?user=admin&password=securepass" ); const { uuid, ok } = await loginResponse.json(); localStorage.setItem("pwauuid", uuid); ``` -------------------------------- ### Run PWA Installation Event Listeners Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWAInstallPrompt.md Sets up the necessary event listeners for the PWA installation flow, including handling the 'beforeinstallprompt' and 'appinstalled' events. It can be configured for modal or button-only UIs. ```javascript const installPrompt = new PWAInstallPrompt("#install"); const modal = document.getElementById("modal"); // For popover UI: installPrompt.runEvents(true, modal); // For button-only UI: installPrompt.runEvents(false); ``` ```javascript // Event Lifecycle: // 1. beforeinstallprompt fires -> button shown // 2. User clicks button -> installPWABtnHandler() called // 3. User accepts/dismisses -> appinstalled event fires // 4. Cleanup happens automatically ``` -------------------------------- ### Usage Example: updatePWAConfig Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/utilities.md Provides an example of importing and using `updatePWAConfig` to merge new configuration values into an existing PWA configuration object. ```typescript import { updatePWAConfig } from "./src/pwa/utilities"; const existingConfig = { cacheAssets: "v1", strategy: "CacheFirst" }; const newConfig = { cacheAssets: "v2", forceUpdate: true }; const updated = updatePWAConfig(existingConfig, newConfig); // Result: { cacheAssets: "v2", strategy: "CacheFirst", forceUpdate: true } ``` -------------------------------- ### Minimal PWA Configuration for Astro Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/README.md Configure astro.config.mjs to enable PWA installation and manifest generation. This snippet sets up the basic manifest name, short name, description, start URL, display mode, theme color, and icons. ```javascript // filepath: astro.config.mjs import { defineConfig } from "astro/config"; import PoweredWebAppBuilder from "webapp-astro-pwa/pwa"; export default defineConfig({ integrations: [ PoweredWebAppBuilder({ isManifest: true, createManifest: true, manifestPath: "manifest.json", manifest: { name: "My PWA Example", short_name: "PWAExample", description: "A simple Progressive Web App example.", start_url: "/", display: "standalone", theme_color: "#8936FF", icons: [ { sizes: "512x512", src: "node_modules/webapp-astro-pwa/src/manifest_imgs/icon512x512.png", type: "image/png", }, { sizes: "192x192", src: "node_modules/webapp-astro-pwa/src/manifest_imgs/icon192x192.png", type: "image/png", }, ], }, icons: [ { rel: "icon", type: "png", sizes: "512x512", href: "/webapp-astro-pwa/src/manifest_imgs/icon512x512.png", }, { rel: "apple-touch-icon", type: "png", sizes: "192x192", href: "/webapp-astro-pwa/src/manifest_imgs/icon512x512.png", }, ], }), ], }); ``` -------------------------------- ### showInstallationMessage Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md Displays an installation instruction message by element ID. This is useful for browsers that do not support the beforeinstallprompt event. ```APIDOC ## showInstallationMessage(id: string): void ### Description Displays an installation instruction message by element ID. This method queries the DOM for the specified element and sets its display style to "block" if found. It fails silently if the element is not found. ### Method `showInstallationMessage` ### Parameters #### Path Parameters - **id** (string) - Required - Element ID to display (e.g., "installation-message") ### Usage Example ```javascript const setup = new PWASetup(); setup.showInstallationMessage("installation-message"); ``` ``` -------------------------------- ### PWA Setup with Modal Prompt Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/README.md Use PWA and PWASetupWindow components to display a modal prompt for adding the app to the home screen. ```astro --- import { PWA, PWASetupWindow } from "webapp-astro-pwa"; --- ``` -------------------------------- ### Admin Login Panel Setup Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/README.md Set up the login page for an admin panel using the LoginPanel component. ```astro --- // /login page import { LoginPanel } from "webapp-astro-pwa"; --- ``` -------------------------------- ### isBeforeInstallPromptSupported(): boolean Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/utilities.md Checks if the browser supports the `beforeinstallprompt` event, which is crucial for PWA installation prompts. ```APIDOC ## isBeforeInstallPromptSupported() ### Description Checks if the browser supports the `beforeinstallprompt` event. ### Returns - `boolean` - True if event supported, false otherwise ### Browser Support - ✓ Chrome, Edge, Opera - ✗ Safari, Firefox, Internet Explorer ### Usage ```javascript import { isBeforeInstallPromptSupported } from "./view/utils/utilities"; if (isBeforeInstallPromptSupported()) { // Show install button for supported browsers } else { // Show manual install instructions } ``` ``` -------------------------------- ### Use PWABtn Component Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/index.md Integrate the PWABtn component for a standalone PWA installation button. Customize button text and appearance. It only displays if PWA installation is enabled in the configuration and the app is not already installed. ```astro ``` -------------------------------- ### PWASetup Constructor Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md Initializes the PWASetup class with optional CSS selectors for the install button and modal/popover. ```APIDOC ## constructor(installSelector?: string, popoverId?: string) ### Description Initializes PWA setup with button and modal references. ### Parameters #### Path Parameters - **installSelector** (string) - Optional - CSS selector for install button element. Defaults to "#install". - **popoverId** (string) - Optional - Element ID for modal/popover. Defaults to "modal". ### Request Example ```javascript // Default behavior const setup = new PWASetup(); // Custom selectors const setup = new PWASetup("#custom-btn", "custom-modal"); ``` ``` -------------------------------- ### Enable PWA Setup Page Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/configuration.md Enable the `isSetupPageEnabled` option to show a PWA setup window on the first load for browsers that do not support PWA features. ```javascript PoweredWebAppBuilder({ isSetupPageEnabled: true, }) ``` -------------------------------- ### Enable Additional Install Button in Astro PWA Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/README.md Add `isInstallBtnVisible: true` to your `PoweredWebAppBuilder` configuration to show an extra installation prompt. Defaults to `false`. ```javascript // filepath: astro.config.mjs import { defineConfig } from 'astro/config'; import PoweredWebAppBuilder from "webapp-astro-pwa/pwa"; export default defineConfig({ integrations: [ // this line changed PoweredWebAppBuilder({ "isInstallBtnVisible": true, }), ... ] }); ``` -------------------------------- ### Trigger PWA Install Prompt Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWAInstallPrompt.md Initiates the browser's native PWA installation prompt. This method handles the prompt display and waits for user interaction, performing cleanup afterward. ```javascript const installPrompt = new PWAInstallPrompt("#install"); const btn = document.getElementById("install"); btn.addEventListener("click", () => { installPrompt.installPWABtnHandler(); }); ``` ```javascript // In the installPrompt.userChoice handler: if (result.outcome === "accepted") { console.log("User installed the PWA"); } else if (result.outcome === "dismissed") { console.log("User dismissed the install prompt"); } ``` -------------------------------- ### Install Astro Node Adapter Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/README.md Install the necessary Node.js adapter for Astro to enable server-side rendering and API routes. This is a prerequisite for deploying Astro applications that require server functionality. ```bash npx astro add node ``` -------------------------------- ### PWASetup Class Integration Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWAInstallPrompt.md Example of how the PWASetup class utilizes PWAInstallPrompt internally. It initializes the prompt and runs events with a popover element. ```typescript class PWASetup { private pwaInstall: PWAInstallPromptType; constructor(installSelector: string = "#install") { this.pwaInstall = new PWAInstallPrompt(installSelector); this.pwaInstall.runEvents(true, this.popover); } } ``` -------------------------------- ### PWASetup Methods Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md Methods available on the PWASetup class for managing the PWA installation process. ```APIDOC ## showInstallationMessage(id: string) ### Description Displays an installation message using the provided element ID. ### Method `showInstallationMessage` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the element to display the installation message. ### Request Example ```javascript setup.showInstallationMessage("install-message-element"); ``` ``` ```APIDOC ## checkIsPWAInstalled(isSetupEnabled?: boolean) ### Description Checks the current installation status of the PWA. ### Method `checkIsPWAInstalled` ### Parameters #### Path Parameters - **isSetupEnabled** (boolean) - Optional - Flag to determine if the setup process should be enabled. ### Request Example ```javascript setup.checkIsPWAInstalled(true); ``` ``` ```APIDOC ## run(isSetupEnabled?: boolean) ### Description Executes the PWA setup flow. ### Method `run` ### Parameters #### Path Parameters - **isSetupEnabled** (boolean) - Optional - Flag to determine if the setup process should be enabled. ### Request Example ```javascript setup.run(true); ``` ``` ```APIDOC ## getInstallPrompt(): PWAInstallPromptType ### Description Retrieves the PWA install prompt object. ### Method `getInstallPrompt` ### Response #### Success Response (200) - **PWAInstallPromptType** - The PWA install prompt object. ### Request Example ```javascript const prompt = setup.getInstallPrompt(); ``` ``` ```APIDOC ## getIsInstalled(): boolean ### Description Retrieves the installation status of the PWA. ### Method `getIsInstalled` ### Response #### Success Response (200) - **boolean** - True if the PWA is installed, false otherwise. ### Request Example ```javascript const isInstalled = setup.getIsInstalled(); ``` ``` -------------------------------- ### BeforeInstallPromptEvent Interface Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/types.md Extends the native Event interface to include methods for triggering the PWA install prompt and user choice. ```typescript export interface BeforeInstallPromptEvent extends Event { prompt: () => Promise; userChoice?: Promise<{ outcome: "accepted" | "dismissed"; platform?: string }>; } ``` -------------------------------- ### runEvents Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWAInstallPrompt.md Sets up the necessary event listeners to manage the complete PWA installation flow, including handling the `beforeinstallprompt` and `appinstalled` events. ```APIDOC ## runEvents(isPopup: boolean, popup?: HTMLElement): void ### Description Attaches event listeners required for the PWA installation process. This method orchestrates the handling of the `beforeinstallprompt` and `appinstalled` events to manage the user experience during PWA installation. ### Parameters #### Path Parameters * **isPopup** (`boolean`) - Required - Indicates if the installation UI is presented within a modal popover. * **popup** (`HTMLElement`) - Optional - The modal or popover element, used only when `isPopup` is true. ### Event Listeners Attached * **`beforeinstallprompt`**: Handled by `beforeInstallHandler` to show the install button and store the prompt event. * **`appinstalled`**: Triggers automatic cleanup, including hiding modals, removing buttons, and removing event listeners. ### Usage ```javascript const installPrompt = new PWAInstallPrompt("#install"); const modal = document.getElementById("modal"); // For popover UI: installPrompt.runEvents(true, modal); // For button-only UI: installPrompt.runEvents(false); ``` ### Event Lifecycle 1. `beforeinstallprompt` fires: The install button is displayed. 2. User clicks the install button: `installPWABtnHandler()` is invoked. 3. User accepts or dismisses the prompt: The `appinstalled` event fires. 4. Automatic cleanup occurs. ``` -------------------------------- ### checkIsPWAInstalled Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWAInstallPrompt.md Checks if the PWA is already installed in the browser. ```APIDOC ## checkIsPWAInstalled() ### Description Checks if the PWA is already installed in the browser. ### Method `checkIsPWAInstalled` ### Response #### Success Response (boolean) - Returns `true` if the PWA is installed, `false` otherwise. ``` -------------------------------- ### Required HTML Elements for PWA Installation Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md These HTML elements are expected by the PWASetup class for handling PWA installations. Ensure these elements with the specified IDs and attributes are present in your HTML. ```html ``` -------------------------------- ### Send Notification Endpoint Example Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/endpoints.md Example of sending a push notification to specified device tokens. Requires the user UUID and notification content. Uses URLSearchParams for query parameters. ```javascript const uuid = localStorage.getItem("pwauuid"); const devices = ["token1", "token2", "token3"]; const sendResponse = await fetch( "/pushapi?" + new URLSearchParams({ uuid, title: "New Message", body: "You have a new update", icon: "https://example.com/icon.png", token: JSON.stringify(devices), }) ); const result = await sendResponse.json(); if (result.ok) { console.log(`Sent to ${result.response.successCount} devices`); } ``` -------------------------------- ### runEvents Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWAInstallPrompt.md Manages the display and behavior of the install prompt based on whether it's a popup or a standard button interaction. ```APIDOC ## runEvents(isPopup: boolean, popup?: HTMLElement) ### Description Manages the display and behavior of the install prompt based on whether it's a popup or a standard button interaction. ### Parameters #### Path Parameters - **isPopup** (boolean) - Required - Indicates if the prompt is displayed as a popup. - **popup** (HTMLElement) - Optional - The popup element if `isPopup` is true. ``` -------------------------------- ### Example of a meta tag configuration Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/types.md Illustrates how to configure a single meta tag, such as for theme-color. This is used within PWA manifest options. ```typescript { name: "theme-color", content: "#8936FF" } ``` -------------------------------- ### getIsInstalled Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md Checks and returns the current installation status of the PWA, indicating whether it is running in standalone mode. ```APIDOC ## getIsInstalled(): boolean ### Description Returns whether the PWA is currently installed and running standalone. This method provides a simple boolean value indicating the installation status. ### Method `getIsInstalled` ### Returns - **boolean** - True if installed, false otherwise. ### Usage Example ```javascript const setup = new PWASetup(); if (setup.getIsInstalled()) { console.log("Running as installed PWA"); } else { console.log("Running in browser"); } ``` ``` -------------------------------- ### runPWASetup Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md A convenience function to create and run PWASetup with default settings. It simplifies the process of initializing the PWA setup flow. ```APIDOC ## runPWASetup(isSetupEnabled: boolean): void ### Description Convenience function to create and run PWASetup with default settings. ### Method `runPWASetup` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### `isSetupEnabled` - **Type**: `boolean` - **Required**: Yes - **Description**: Whether to enable setup UI ### Usage Examples ```javascript // Default setup runPWASetup(true); // Skip setup (already installed) runPWASetup(false); ``` ### Equivalent to ```javascript const setup = new PWASetup(); // Uses defaults: "#install", "modal" setup.run(isSetupEnabled); ``` ``` -------------------------------- ### checkIsPWAInstalled Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWAInstallPrompt.md Checks if the application is currently running in a standalone PWA mode, indicating it has been installed by the user. ```APIDOC ## checkIsPWAInstalled(): boolean ### Description Checks if the app is running in PWA standalone mode. ### Returns * `boolean` - True if PWA is installed and running standalone, false otherwise. ### Usage ```javascript const installPrompt = new PWAInstallPrompt("#install"); if (installPrompt.checkIsPWAInstalled()) { // PWA is running as an app } ``` ``` -------------------------------- ### Usage Example: GetPWAConfigPathFromGrandparent Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/utilities.md Demonstrates how to import and use the `getPWAConfigPathFromGrandparent` function to retrieve and parse the PWA configuration file. ```typescript import { getPWAConfigPathFromGrandparent } from "./src/pwa/utilities"; const configPath = getPWAConfigPathFromGrandparent(); if (configPath && fs.existsSync(configPath)) { const config = JSON.parse(fs.readFileSync(configPath, "utf8")); // Use config } ``` -------------------------------- ### Usage Example: runShellCommand Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/utilities.md Shows how to import and use the `runShellCommand` function to execute a shell command, such as regenerating the service worker. ```typescript import { runShellCommand } from "./src/pwa/utilities"; // Regenerate service worker when config changes runShellCommand("npm run generateAndBundleSW"); ``` -------------------------------- ### Basic PWA Setup in Astro Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/README.md Include the PWA component in your Astro head for basic Progressive Web App functionality. ```astro --- import { PWA } from "webapp-astro-pwa"; --- ``` -------------------------------- ### PWASetupWindow Component Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/index.md A popover modal component for PWA installation with customizable UI elements like title, description, and button text. ```APIDOC ## PWASetupWindow Component ### Description Popover modal component for PWA installation with customizable UI. ### Import ```typescript import { PWASetupWindow } from "webapp-astro-pwa"; ``` ### Usage ```astro ``` ### Props | Prop | Type | Required | Default | Description | |------|------|----------|---------|-------------| | `title` | `string` | No | — | Title text for the installation prompt | | `description` | `string` | No | — | Description text for the installation prompt | | `btnText` | `string` | No | — | Text displayed on the install button | | `btnStyle` | `object` | No | — | Inline CSS styles for the button | | `background` | `string` | No | — | Background color of the popover | | `hideSvg` | `boolean` | No | — | Whether to hide the SVG icon | | `isShow` | `boolean` | No | Derived from config | Whether to display the popover | | `responsiveBtnStyles` | `{matchMedia: string; styles: object}` | No | — | Media query-specific button style overrides | ### Behavior - Creates a popover modal using HTML `popover="manual"` API - Falls back to polyfill for browsers without native popover support - Shows different content based on browser support: - `#installation-message`: For unsupported browsers - `#installation-page`: For browsers with beforeinstallprompt support - Automatically hides on user action ``` -------------------------------- ### Admin Push Notification Page Setup Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/README.md Configure the push notification sending page for administrators using the SendPushPage component. ```astro --- // /sendpush page import { SendPushPage } from "webapp-astro-pwa"; --- ``` -------------------------------- ### Run PWASetup with Default Settings Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md Use the convenience function `runPWASetup` to initialize PWASetup with default configurations. Pass `true` to enable the setup UI or `false` to skip it. ```javascript // Default setup runPWASetup(true); // Skip setup (already installed) runPWASetup(false); ``` -------------------------------- ### Automatic Setup with Configuration Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/SWUtils.md Initializes service worker functionalities automatically based on settings in pwa.config.json. Handles notification permissions and service worker updates. ```javascript const swUtils = new SWUtils(); // Respects config settings from pwa.config.json swUtils.permisionHandler(); // Handles button and auto-request based on config swUtils.forceUpdate(); // Updates service worker if config enabled ``` -------------------------------- ### Usage Example: getConfigJSON Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/utilities.md Illustrates importing and using the `getConfigJSON` function to read and parse a PWA configuration file from a given path. ```typescript import { getConfigJSON } from "./src/pwa/utilities"; const config = getConfigJSON("/path/to/pwa.config.json"); console.log(config.cacheAssets); // "static-assets" ``` -------------------------------- ### Verify Session Endpoint Example Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/endpoints.md Optional step to verify the user's session using the stored UUID. Retrieves the UUID from local storage. ```javascript const uuid = localStorage.getItem("pwauuid"); const verifyResponse = await fetch( `/pushapi?uuid=${uuid}&checkUuid=true` ); const verified = verifyResponse.ok; ``` -------------------------------- ### Full Featured PWA Configuration with PoweredWebAppBuilder Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PoweredWebAppBuilder.md Configure a comprehensive PWA with auto-generated manifest, install button, push notifications, Firebase integration, and custom manifest/icon injection. This setup is ideal for feature-rich applications. ```javascript PoweredWebAppBuilder({ isManifest: true, createManifest: true, manifestPath: "public/manifest.json", isInstallBtnVisible: true, forceUpdate: true, strategy: "CacheFirst", notification: true, notificationBtn: true, applicationServerKey: "BA1-2-3-4...", manifest: { name: "My App", short_name: "MyApp", description: "A PWA", start_url: "/", display: "standalone", theme_color: "#8936FF", icons: [ /* ... */ ], }, icons: [ /* ... */ ], meta: [ /* ... */ ], firebaseConfig: { /* ... */ }, }) ``` -------------------------------- ### Hide Install Button Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWAInstallPrompt.md Hides a given install button element by applying the 'hidden' attribute. This is useful after an install has been initiated or completed. ```javascript const installPrompt = new PWAInstallPrompt("#install"); const btn = document.getElementById("install"); if (btn) { installPrompt.hideButton(btn); } ``` -------------------------------- ### getInstallPrompt Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md Provides direct access to the internal PWAInstallPrompt object, allowing for manipulation of prompt-related properties and methods. ```APIDOC ## getInstallPrompt(): PWAInstallPromptType ### Description Returns the internal `PWAInstallPrompt` object for direct access. This allows developers to interact with the underlying prompt handler, including its properties and methods. ### Method `getInstallPrompt` ### Returns - **PWAInstallPromptType** - The internal install prompt handler. ### Usage Example ```javascript const setup = new PWASetup(); const promptHandler = setup.getInstallPrompt(); console.log(promptHandler.installPrompt); console.log(promptHandler.btn); promptHandler.checkIsPWAInstalled(); ``` ``` -------------------------------- ### beforeInstallHandler Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWAInstallPrompt.md Callback function to handle the `beforeinstallprompt` event, storing the event for later use. ```APIDOC ## beforeInstallHandler(event: Event, btn: HTMLElement) ### Description Callback function to handle the `beforeinstallprompt` event, storing the event for later use. ### Parameters #### Path Parameters - **event** (Event) - Required - The `beforeinstallprompt` event object. - **btn** (HTMLElement) - Required - The install button element. ``` -------------------------------- ### installPWABtnHandler Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWAInstallPrompt.md Initiates the browser's native PWA installation prompt. It handles the prompt's lifecycle, including user acceptance or dismissal, and performs necessary cleanup. ```APIDOC ## installPWABtnHandler(): Promise ### Description Triggers the browser's PWA install prompt when called. It manages the prompt's lifecycle and cleans up UI elements upon user interaction. ### Returns * `Promise` - Resolves after the prompt interaction is complete. ### Behavior 1. Checks for the availability of the `installPrompt` event. 2. Invokes `prompt()` to display the browser's install dialog. 3. Awaits the `userChoice` promise for user interaction. 4. Removes the button from the DOM and hides the modal if the PWA was accepted or dismissed. ### Usage ```javascript const installPrompt = new PWAInstallPrompt("#install"); const btn = document.getElementById("install"); btn.addEventListener("click", () => { installPrompt.installPWABtnHandler(); }); ``` ### Installation Outcomes ```javascript // Within the installPrompt.userChoice handler: if (result.outcome === "accepted") { console.log("User installed the PWA"); } else if (result.outcome === "dismissed") { console.log("User dismissed the install prompt"); } ``` ``` -------------------------------- ### Check if PWA is Installed Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md Use `getIsInstalled` to determine if the PWA is currently installed and running in standalone mode. This is useful for conditionally rendering UI or logic. ```javascript const setup = new PWASetup(); if (setup.getIsInstalled()) { console.log("Running as installed PWA"); } else { console.log("Running in browser"); } ``` -------------------------------- ### PWABtn Component Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/index.md A standalone install button component for PWA installation. It allows customization of button text, background color, and SVG icon visibility. ```APIDOC ## PWABtn Component ### Description Standalone install button component for PWA installation. ### Import ```typescript import { PWABtn } from "webapp-astro-pwa"; ``` ### Usage ```astro ``` ### Props | Prop | Type | Required | Default | Description | |------|------|----------|---------|-------------| | `btnText` | `string` | No | — | Text displayed on the install button | | `hideSvg` | `boolean` | No | — | Whether to hide the SVG icon on the button | | `isShow` | `boolean` | No | Derived from config | Whether to display the button | | `style` | `object` | No | — | Inline CSS styles for the button | | `responsiveStyles` | `{matchMedia: string; styles: object}` | No | — | Media query-specific style overrides | ### Behavior - Only displays if `isManifest` and `isInstallBtnVisible` are both true in config - Removes button automatically if PWA is already installed - Initializes PWA setup on DOMContentLoaded ``` -------------------------------- ### Export Client-Side Utilities Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/utilities.md Exports a set of client-side utility functions, including checks for install prompt support, PWA installation status, and browser compatibility. ```typescript export { isBeforeInstallPromptSupported, renderPopover, isPWAInstalled, isChromeOrEdge, }; ``` -------------------------------- ### Client-Side Utilities Import Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/README.md Imports various client-side utility functions for PWA features like checking install prompt support, rendering popovers, checking installation status, and browser detection. ```typescript import { isBeforeInstallPromptSupported, renderPopover, isPWAInstalled, isChromeOrEdge, } from "./src/view/utils/utilities"; ``` -------------------------------- ### Integrate PWASetup in Astro Component (PWABtn.astro) Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md Import and use `runPWASetup` within an Astro component to conditionally display the PWA installation button based on a data attribute. ```astro ``` -------------------------------- ### Check if PWA is Installed Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/utilities.md Verifies if the application is currently running in standalone PWA mode using the `display-mode: standalone` media query. This is useful for adapting the UI or behavior based on whether the app is installed. ```typescript function isPWAInstalled(): boolean { return window.matchMedia("(display-mode: standalone)").matches; } ``` ```javascript import { isPWAInstalled } from "./view/utils/utilities"; if (isPWAInstalled()) { console.log("Running as installed PWA"); } else { console.log("Running in web browser"); } ``` -------------------------------- ### Import PWASetup Utilities Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md Import the PWASetup class and the default runPWASetup function from the utility file. ```typescript import { PWASetup } from "./src/view/utils/PWASetup"; import runPWASetup from "./src/view/utils/PWASetup"; ``` -------------------------------- ### Integrate PWASetup in Astro Component (PWASetupWindow.astro) Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWASetup.md Import and instantiate `PWASetup` within an Astro component to manage the PWA setup process, controlling visibility via data attributes. ```astro ``` -------------------------------- ### Build Project Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/README.md Command to build the Astro project for production. ```bash # Build project npm run build ``` -------------------------------- ### hideButton Source: https://github.com/aondodawid/webapp-astro-pwa/blob/master/_autodocs/api-reference/PWAInstallPrompt.md Hides a specified install button element by applying the 'hidden' attribute to it. ```APIDOC ## hideButton(btn: HTMLElement): void ### Description Hides the install button element by adding the `hidden` attribute. ### Parameters #### Path Parameters * **btn** (`HTMLElement`) - Required - Button element to hide ### Usage ```javascript const installPrompt = new PWAInstallPrompt("#install"); const btn = document.getElementById("install"); if (btn) { installPrompt.hideButton(btn); } ``` ```