Command palette

@yasinsensoy/web

Web · Components

InstallPrompt

"Install the app" card that appears once the app is installable.

44 exports

Live example

Preview

canInstall
no
promptReady
no
guide
null
installed
no

Code

import { InstallPrompt, InstallButton } from "@yasinsensoy/web";

// app/layout.tsx: once, in the root layout
<InstallPrompt position="inline" image="/icon-192.png" />

// In a menu or header; not rendered when it can't be installed:
<InstallButton variant="ghost" size="sm" />

Events

  1. Events appear here when you interact with the preview.

Manual install steps (InstallGuide): iOS, macOS Safari, Android, desktop

Add to home screen

Use it like an app in a few taps.

  1. Tap the browser's Share buttonIn Safari it is in the address bar or the ••• menu.
  2. Choose “Add to Home Screen”Scroll down the list if you don't see it.
  3. Tap “Add” in the top right

Add to home screen

Use it like an app in a few taps.

  1. Open “File” in the menu bar
  2. Choose “Add to Dock” and confirm

Add to home screen

Use it like an app in a few taps.

  1. Open the browser menu (⋮)
  2. Choose “Install app” or “Add to Home screen”

Add to home screen

Use it like an app in a few taps.

  1. Click the install icon in the address bar
  2. Confirm “Install” in the dialog

Import

import {
  InstallGuide,
  InstallPrompt,
  InstallButton,
  OfflineIndicator,
  SafeArea,
  ShareButton,
  ThemeColor,
  UpdatePrompt,
  getInstallGuide,
  setAppBadge,
  useAppBadge,
  useDisplayMode,
  useIsStandalone,
  useInstallPrompt,
  useOnlineStatus,
  useNetworkStatus,
  useServiceWorker,
  share,
  useShare,
  useWakeLock,
} from "@yasinsensoy/web";

InstallPrompt

componentClient component

"Install the app" card that appears once the app is installable.

  • In browsers like Chrome, Edge, Samsung Internet, "Install" opens the browser's install window with one tap.
  • In iOS and macOS Safari, the "How to install?" button shows the steps (InstallGuide).
  • Never shows if the app was opened installed or once it is installed.
  • After "Not now" it doesn't come back for dismissDays days.

Putting it once in the root layout is enough. For the browser to offer install, the site must have a web app manifest (Next.js: app/manifest.ts). Renders nothing on the server and on first hydration.

InstallPrompt({ title, description, image, icon, installLabel, dismissLabel, position, enabled, delay, dismissDays, storageKey, guide: showGuide, onInstall, onDismiss, className, classNames, }: InstallPromptProps): JSX.Element

Examples

// app/layout.tsx
<InstallPrompt image="/icon-192.png" title="Install my store" delay={5000} />

// Inside the page on the settings page:
<InstallPrompt position="inline" dismissLabel={null} storageKey={false} />

InstallGuide

componentClient component

Window showing the steps to add the app to the home screen in environments without the browser's own install prompt (iOS, macOS Safari). Opens from the bottom on mobile. InstallPrompt and InstallButton open it themselves; pass trigger to open it with your own button.

Texts can be changed in the dictionary's ui namespace (installIosShare, installIosAdd…; see UIProvider messages).

InstallGuide({ guide, open, onOpenChange, trigger, title, description, image, }: InstallGuideProps): JSX.Element

Examples

<InstallGuide trigger={<Button variant="link">How to add to iPhone?</Button>} guide="ios" />

InstallButton

componentClient component

"Install the app" button: in a menu, header or settings. If install is not possible (installed, unsupported) it is not rendered at all; in iOS and macOS Safari it opens the steps (InstallGuide). Takes all appearance props of Button.

InstallButton({ fallback, guide: showGuide, onInstall, children, icon, className, ...props }: InstallButtonProps): JSX.Element

Examples

<InstallButton variant="outline" size="sm" />
<InstallButton fallback={<span>App installed ✓</span>}>Install on desktop</InstallButton>

OfflineIndicator

componentClient component

"You're offline" indicator that appears at the screen edge when the connection drops; when it returns it briefly says "You're back online" and disappears. Also announced to screen readers. Renders nothing while online.

Put it once in the root layout. For your own UI, useOnlineStatus.

OfflineIndicator({ variant, side, offlineLabel, onlineLabel, onlineDuration, onChange, className, }: OfflineIndicatorProps): JSX.Element

Examples

<OfflineIndicator />
<OfflineIndicator variant="bar" side="bottom" offlineLabel="Changes will be saved when the connection returns" />

SafeArea

componentServer component

Box that insets content so it doesn't sit under the notch, camera island, rounded corners and home bar. Used for the top header and bottom navigation bar in full screen (PWA) apps.

Edge insets exist only if the page covers the whole screen; in Next.js enable it with export const viewport = { viewportFit: "cover" }. If you only need classes, there are also the pt-safe, pb-safe, px-safe… utilities.

It is a server component; it contains no client code.

SafeArea({ edges, min, as: Comp, style, className, ...props }: SafeAreaProps): JSX.Element

Examples

<SafeArea as="nav" edges={["bottom", "left", "right"]} min="0.5rem"
  className="fixed inset-x-0 bottom-0 border-t bg-background">
  <BottomMenu />
</SafeArea>

ShareButton

componentClient component

Share button. On phones and supporting desktops it opens the system share sheet; if unsupported, it copies the URL to the clipboard and shows a "Link copied" notification. Takes all appearance props of Button. As a function: share.

Notifications need a Toaster in the root layout.

ShareButton({ data, notify, onShare, icon, children, ...props }: ShareButtonProps): JSX.Element

Examples

<ShareButton />
<ShareButton variant="outline" data={{ title: product.name, url: `/product/${product.id}` }}>
  Share product
</ShareButton>

ThemeColor

componentClient component

Binds the <meta name="theme-color"> value to the page theme: the browser's address bar and the installed app's title and status bar change color with the theme (light, dark, custom themes). Renders nothing.

Put it once in the root layout, inside or next to ThemeProvider. It detects theme changes from the class, data-theme and style changes on <html> and from the system light/dark preference.

Note: it replaces the fixed value given with Next.js viewport.themeColor; don't use both.

ThemeColor({ color }: ThemeColorProps): null

Examples

<ThemeProvider>
  <ThemeColor />
  {children}
</ThemeProvider>

<ThemeColor color="var(--ui-card)" />

UpdatePrompt

componentClient component

Registers the service worker and shows a "New version ready — Reload" card when a new version is downloaded. When the user reloads, the waiting version is activated and the page reloads once; if closed with ×, the version activates by itself on the next launch.

Put it once in the root layout. Your service worker file must listen for the SKIP_WAITING message; for details and your own UI see useServiceWorker. If a tool like Serwist or Workbox does the registration itself, pass register={false}.

UpdatePrompt({ title, description, icon, reloadLabel, position, offlineReady, onUpdate, className, classNames, ...options }: UpdatePromptProps): JSX.Element | null

Examples

// app/layout.tsx
<UpdatePrompt url="/sw.js" enabled={process.env.NODE_ENV === "production"} offlineReady />

Detects an environment where the browser doesn't support its own install window (beforeinstallprompt) but allows manual install: all browsers on iOS/iPadOS and macOS Safari. Returns null elsewhere; there install is one tap with useInstallPrompt. Returns null on the server.

Can be called in server components too (it isn't client code); but the result is only meaningful in the browser.

getInstallGuide(nav?: NavigatorLike | undefined): InstallGuideKind | null

Examples

if (getInstallGuide() === "ios") showIosHint();

setAppBadge

function

Sets the badge on the installed app's icon (home screen, Dock, taskbar). If no number is given or it is true, a dot without a number is shown; 0 or false removes the badge. Silently does nothing in unsupported browsers (and in most browsers while open in a tab).

iOS/iPadOS 16.4+ shows it only for apps added to the home screen with notification permission granted.

setAppBadge(count?: number | boolean): Promise<void>

Examples

await setAppBadge(3);
await setAppBadge(0); // removes

useAppBadge

function

Binds the app icon badge to a value: the badge updates as the value changes and is cleared when the component unmounts. Suitable for unread message or pending task counts. See setAppBadge.

useAppBadge(count: number | boolean | null | undefined): void

Examples

const { data } = useUnread();
useAppBadge(data?.count ?? 0);

Tracks which window mode the app was opened in: browser tab ("browser") or installed app ("standalone", "fullscreen"…). The value updates when the user moves the app from a tab to a window.

Returns "browser" on the server and on first hydration. To change only the look, prefer Tailwind's standalone: prefix (standalone:hidden); this hook is needed when behavior changes.

useDisplayMode(): DisplayMode

Examples

const mode = useDisplayMode();
if (mode === "window-controls-overlay") return <TitleBar />;

Returns true if the app was opened as installed (from the home screen, Dock, in an app window). Returns false on the server and on first hydration.

useIsStandalone(): boolean

Examples

const standalone = useIsStandalone();
return standalone ? <BackButton /> : null; // No browser back button

Tracks whether the app is installable and opens the install window. Use it if you build your own button or card; the ready-made ones are InstallPrompt and InstallButton.

For the browser to offer an install window, the site needs a valid web app manifest (app/manifest.ts in Next.js), HTTPS and icons of at least 192 and 512 px. iOS and macOS Safari don't offer a window; there the steps are shown with guide.

If the user rejects the browser's window, Chrome won't offer it again for a while (about three months); so show the prompt at the right moment.

useInstallPrompt(): InstallPromptState

Examples

const { canInstall, promptReady, install } = useInstallPrompt();
if (!canInstall) return null;
return (
  <Button onClick={async () => {
    if ((await install()) === "accepted") toast.success("Installed");
  }}>
    Install
  </Button>
);

Tracks whether the device is connected to a network. Returns true on the server and on first hydration. OfflineIndicator is ready-made for showing it to the user.

Note: true isn't definite proof of internet access (e.g. a captive Wi-Fi); false means the connection is definitely missing.

useOnlineStatus(): boolean

Examples

const online = useOnlineStatus();
<Button disabled={!online} tooltip={!online && "No connection"}>Send</Button>

Tracks the connection status in detail: online or not, estimated speed, data saver. Used to serve lighter content on slow connections. If you only need online/offline, useOnlineStatus re-renders less.

useNetworkStatus(): NetworkStatus

Examples

const { saveData, effectiveType } = useNetworkStatus();
const light = saveData || effectiveType === "2g" || effectiveType === "slow-2g";
return light ? <img src={smallImage} /> : <video src={video} autoPlay />;

Registers the service worker and tracks new versions. The ready-made component for telling the user "New version ready" is UpdatePrompt; use this hook if you build your own UI. Can be called in several places; registration happens once and the state is shared.

When a new version is installed, the browser keeps it waiting (open tabs keep running the old version). update() sends the SKIP_WAITING message to the waiting worker; when the worker activates the page reloads once. For this your service worker file needs this listener:

// public/sw.js
self.addEventListener("message", (event) => {
  if (event.data?.type === "SKIP_WAITING") self.skipWaiting();
});

A new version is checked when the page opens, when returning to the tab and every updateInterval (while online).

useServiceWorker(options?: UseServiceWorkerOptions): ServiceWorkerState

Examples

const { updateAvailable, update } = useServiceWorker({ url: "/sw.js" });
return updateAvailable ? <Button onClick={update}>Update</Button> : null;

share

function

Shares content with the system share sheet; if unsupported (most desktop browsers) it copies the URL to the clipboard. Must be called inside a click. The UI version is ShareButton.

Can be imported in server components too; it is called only in the browser.

share(content?: ShareContent): Promise<ShareResult>

Examples

const result = await share({ title: "My report", url: "/report/42" });
if (result === "copied") toast("Link copied");

useShare

function

Reports share support and provides the share function. Use it if you show a different UI based on support; otherwise share or ShareButton directly is enough.

useShare(): ShareState

Examples

const { supported, share } = useShare();
<Button onClick={() => share({ url })}>{supported ? "Share" : "Copy link"}</Button>

useWakeLock

function

While active is true, prevents the device screen from dimming and locking: for recipe, directions, presentation, payment QR code screens. When the tab goes to the background the browser releases the lock; on returning to the tab the hook reacquires it by itself. Released on unmount.

Silently does nothing in unsupported browsers or battery saver mode; locked stays false.

useWakeLock(active?: boolean): WakeLockState

Examples

const [cooking, setCooking] = useState(false);
const { locked } = useWakeLock(cooking);
<Switch checked={cooking} onCheckedChange={setCooking}
  label={locked ? "Screen is kept on" : "Keep screen on"} />

Props of the InstallGuide component.

NameTypeDefaultDescription
guide?InstallGuideKindSteps to show. If omitted, picked by environment (iOS, macOS Safari); "desktop" if none is found.
open?booleanWhether it is open (controlled).
onOpenChange?(open: boolean) => voidCalled when open/close changes.
trigger?ReactElementElement that opens the window when clicked (uncontrolled use).
title?ReactNodemessages.installGuideTitleTitle.
description?ReactNodemessages.installGuideDescriptionDescription.
image?string | ReactNodeIcon of the window: the app icon (image URL or element).

Props of the InstallPrompt component.

NameTypeDefaultDescription
title?ReactNodemessages.installTitleTitle.
description?ReactNodemessages.installDescriptionDescription.
image?string | ReactNodeApp icon at the left of the card: image URL ("/icon-192.png"), icon name or element. If omitted, a download icon.
icon?IconPropIcon from the library instead of image.
installLabel?ReactNodemessages.installText of the install button.
dismissLabel?ReactNodemessages.notNowText of the dismiss button; hidden with null.
position?PromptPosition"bottom-center"Position of the card. See PromptPosition.
enabled?booleantrueNot shown while false. Use it to show the prompt at the right moment: e.g. when the user comes back a second time or finishes a task.
delay?number0How many ms to wait after it becomes installable before showing.
dismissDays?number14For how many days it is not shown after closing with "Not now" or ×. With 0 it is hidden only while this page is open.
storageKey?string | false"ui-install-prompt"localStorage key where the dismiss period is stored. Pass a different key if the site has several prompts; false stores nothing.
guide?booleantrueIn manually installed environments (iOS, macOS Safari) shows the steps with a "How to install?" button. With false no prompt appears there.
onInstall?(outcome: InstallOutcome) => voidCalled when the user makes a choice in the browser's window.
onDismiss?() => voidCalled when the user closes or dismisses the prompt.
className?stringClasses added to the card element.
classNames?PromptClassNamesClasses added to the inner parts.

Props of the InstallButton component.

Extends: Omit<ButtonAsButtonProps, "onClick" | "href">

NameTypeDefaultDescription
fallback?ReactNodeWhat to render when install is not possible. If omitted, nothing is rendered, so the button only appears when it is useful.
guide?booleantrueIn manually installed environments (iOS, macOS Safari) shows the steps. With false the button isn't rendered there.
onInstall?(outcome: InstallOutcome) => voidCalled when the user makes a choice in the browser's window.

Style of the indicator.

  • pill: small pill floating at the center of the screen.
  • bar: thin strip along the screen edge.
type OfflineIndicatorVariant = "pill" | "bar"

Props of the OfflineIndicator component.

NameTypeDefaultDescription
variant?OfflineIndicatorVariant"pill"Style.
side?"top" | "bottom""top"Which edge of the screen.
offlineLabel?ReactNodemessages.offlineText while offline.
onlineLabel?ReactNodemessages.backOnlineText shown briefly when the connection returns; not shown with null.
onlineDuration?number3000How long (ms) the "back online" text stays on screen.
onChange?(online: boolean) => voidCalled when the connection status changes.
className?stringClasses added to the indicator.

Kind of manual install steps: the path shown to the user when the browser has no install window of its own.

  • ios: iPhone/iPad; Share → Add to Home Screen.
  • macos: macOS Safari; File → Add to Dock.
  • android: Android browser menu (⋮) → Install app.
  • desktop: install icon in the Chrome/Edge address bar.
type InstallGuideKind = "ios" | "macos" | "android" | "desktop"

Window mode the app was opened in; depends on the manifest's display value and how the user opened the app. browser is a normal browser tab; the others are an installed app.

type DisplayMode = "browser" | "standalone" | "minimal-ui" | "fullscreen" | "window-controls-overlay"

Position of the prompt card. inline is rendered in the page flow where it is placed; the others are fixed to the screen. On mobile (below 640 px) fixed cards are always full width and respect the notch/home bar inset.

type PromptPosition = "top-left" | "top-center" | "top-right" | "bottom-left" | "bottom-center" | "bottom-right" | "inline"

Classes that can be passed to the inner parts of the InstallPrompt and UpdatePrompt card.

NameTypeDescription
icon?stringIcon box.
title?stringTitle.
description?stringDescription.
actions?stringButton area.

Edge of the screen.

type SafeAreaEdge = "top" | "right" | "bottom" | "left"

SafeAreaProps

interface

Props of the SafeArea component.

Extends: ComponentProps<"div">

NameTypeDefaultDescription
edges?readonly SafeAreaEdge[]["top", "right", "bottom", "left"]Edges to pad.
min?string"0px"Minimum padding kept even on devices without a notch (CSS length), e.g. "1rem". If the edge inset is larger, that is used.
as?"div" | "header" | "footer" | "main" | "nav" | "section" | "aside""div"Element to render.

Props of the ShareButton component.

Extends: Omit<ButtonAsButtonProps, "onClick" | "href">

NameTypeDefaultDescription
data?ShareContentTitle, text, URL or files to share. If omitted, the current page.
notify?booleantrueWhether to show a notification (toast) when the URL is copied or sharing fails.
onShare?(result: ShareResult) => voidCalled with the result when sharing ends. See ShareResult.

Props of the ThemeColor component.

NameTypeDefaultDescription
color?string"var(--ui-background)"Color for the status bar: any CSS color or variable.

Props of the UpdatePrompt component.

NameTypeDefaultDescription
title?ReactNodemessages.updateTitleTitle.
description?ReactNodemessages.updateDescriptionDescription; hidden with null.
icon?IconProprefresh iconIcon of the card: name or element.
reloadLabel?ReactNodemessages.reloadText of the reload button.
position?PromptPosition"bottom-center"Position of the card. See PromptPosition.
offlineReady?boolean | ReactNodefalseWhether to show a "ready for offline use" notification (toast) when the service worker is installed for the first time. If text is given, it is used.
onUpdate?() => voidCalled when the user chooses to reload, right before the page reloads.
className?stringClasses added to the card element.
classNames?PromptClassNamesClasses added to the inner parts.
url?string"/sw.js"URL of the service worker file. In Next.js public/sw.js → "/sw.js".
scope?stringPath the service worker controls. If omitted, the folder of the file.
type?WorkerType"classic""module" if the file is an ES module.
register?booleantrueWhen false the hook doesn't register the file itself; it tracks the service worker registered by another tool (Serwist, Workbox…).
enabled?booleantrueDoes nothing when false. Usually enabled={process.env.NODE_ENV === "production"} is passed so caching doesn't confuse you during development.
updateInterval?number3600000` (1 hour)How often (ms) to check for a new version while the page stays open. With 0 it is checked only when the page opens and when returning to the tab.

Result of the install request.

type InstallOutcome = /** The user accepted the install. */ "accepted" /** The user closed the browser's window. */ | "dismissed" /** The browser currently doesn't allow one-tap install. */ | "unavailable"

Value returned by the useInstallPrompt hook.

NameTypeDescription
canInstallbooleanWhether install can be offered to the user. true if one-tap install is ready or manual install steps (guide) exist and the app is not yet installed. false on the server and on first hydration.
promptReadybooleanWhether the browser's own install window is ready (Chrome, Edge, Samsung Internet…).
guideInstallGuideKind | nullKind of steps in an environment without one-tap install but with manual install (iOS, macOS Safari); null otherwise. InstallGuide shows the steps.
installedbooleanThe app was opened installed or was installed in this session.
install() => Promise<InstallOutcome>Opens the browser's install window and returns the user's choice. If the window isn't ready it returns "unavailable"; then show the steps if guide exists. Can only be called inside a click.

Estimated speed of the connection (Network Information API).

type ConnectionType = "slow-2g" | "2g" | "3g" | "4g"

NetworkStatus

interface

Value returned by the useNetworkStatus hook.

NameTypeDescription
onlinebooleanWhether the device is connected to a network. true on the server.
effectiveTypeConnectionType | undefinedEstimated speed of the connection. Only Chromium-based browsers report it; undefined in others.
saveDatabooleanWhether the user asked for "data saver". Defer heavy content (video, large images).
downlinknumber | undefinedEstimated download speed (Mbps). undefined if unknown.
rttnumber | undefinedEstimated round-trip time (ms). undefined if unknown.

Options of the useServiceWorker hook.

NameTypeDefaultDescription
url?string"/sw.js"URL of the service worker file. In Next.js public/sw.js → "/sw.js".
scope?stringPath the service worker controls. If omitted, the folder of the file.
type?WorkerType"classic""module" if the file is an ES module.
register?booleantrueWhen false the hook doesn't register the file itself; it tracks the service worker registered by another tool (Serwist, Workbox…).
enabled?booleantrueDoes nothing when false. Usually enabled={process.env.NODE_ENV === "production"} is passed so caching doesn't confuse you during development.
updateInterval?number3600000` (1 hour)How often (ms) to check for a new version while the page stays open. With 0 it is checked only when the page opens and when returning to the tab.

Value returned by the useServiceWorker hook.

NameTypeDescription
supportedbooleanWhether the browser supports service workers. false on the server.
registrationServiceWorkerRegistration | nullThe registration; null if not registered yet.
updateAvailablebooleanA new version is downloaded and waiting to activate.
offlineReadybooleanThe service worker was installed for the first time; the app now opens offline too.
errorunknownThe error, if registration failed.
update() => voidActivates the waiting new version and reloads the page. The service worker must listen for the { type: "SKIP_WAITING" } message (see the hook description).
checkForUpdate() => Promise<void>Checks for a new version right away.

ShareContent

interface

Content to share. If nothing is given, the current page's URL and title are shared.

NameTypeDefaultDescription
title?stringdocument.titleTitle.
text?stringShort text.
url?stringlocation.hrefURL. Relative URLs are resolved against the page URL.
files?File[]Files to share (supported only by most mobile browsers).

Result of sharing.

  • shared: the system share sheet opened and the user picked a target.
  • copied: sharing is unsupported, so the URL (or text) was copied to the clipboard.
  • cancelled: the user closed the share sheet.
  • failed: it could neither be shared nor copied.
type ShareResult = "shared" | "copied" | "cancelled" | "failed"

ShareState

interface

Value returned by the useShare hook.

NameTypeDescription
supportedbooleanWhether there is a system share sheet. If false, share copies the URL; you can pick the button text accordingly ("Copy link"). false on the server.
canShareFiles(files: File[]) => booleanWhether files can also be shared in the given content.
share(content?: ShareContent) => Promise<ShareResult>See share.

WakeLockState

interface

Value returned by the useWakeLock hook.

NameTypeDescription
supportedbooleanWhether the browser supports keeping the screen on. false on the server.
lockedbooleanWhether the screen is currently kept on.