{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "install-prompt",
  "type": "registry:ui",
  "title": "Install Prompt",
  "description": "An offer to add the site to the home screen, made once, politely, and only where it can work. Browsers that support it hand over their install dialog (`beforeinstallprompt`), and the Install button opens it. Safari on an iPhone or iPad has no such dialog…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "feedback",
    "pattern"
  ],
  "dependencies": [],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/button.json",
    "https://ds.interlace.tools/r/cn.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/patterns/install-prompt.tsx",
      "target": "components/ui/patterns/install-prompt.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/install-prompt v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/install-prompt\n// What changed since: https://ds.interlace.tools/c/install-prompt#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — InstallPrompt, useInstallPrompt\n *\n * An offer to add the site to the home screen, made once, politely, and\n * only where it can work. Browsers that support it hand over their install\n * dialog (`beforeinstallprompt`), and the Install button opens it. Safari on\n * an iPhone or iPad has no such dialog, so the offer says how instead: the\n * Share button, then Add to Home Screen. Nothing shows when the page is\n * already running as an installed app, after it is installed, or for\n * `dismissDays` after the reader says Not now.\n *\n * `useInstallPrompt()` gives the same state to a control of your own, such\n * as an Install item in a settings list.\n *\n * ## Anatomy\n *\n *   <section data-slot=\"install-prompt\" data-platform=\"prompt|ios\" aria-labelledby>\n *     <span data-slot=\"install-prompt-icon\">{icon}</span>\n *     <div><h2>{title}</h2><p>{description | iOS steps}</p></div>\n *     <div data-slot=\"install-prompt-actions\">[Install] [Not now]</div>\n *   </section>\n *\n * ## Motion\n *\n * It rises 8px and fades in (200ms, `--ease-enter`) when it appears, never\n * on first paint (it only appears after the browser offers the install), and\n * is simply there under reduced motion.\n *\n * ## MIN_VIEWPORT — 320\n *\n * The actions sit under the words in a narrow container and beside them\n * from 28rem (`@container`).\n *\n * | Rule | Concept                 | Where in this file                              |\n * | ---- | ----------------------- | ----------------------------------------------- |\n * | R4   | Extends native el       | `React.ComponentProps<'section'>`               |\n * | R6   | data-slot per part      | install-prompt, -icon, -actions                 |\n * | R7   | className merged + rest | `cn(BASE, className)` + `{...props}`            |\n * | R14  | Declares min viewport   | `data-min-viewport` + exported const            |\n * | R25  | Client component        | browser install events, storage                 |\n * | R26  | A11y                    | a named region, real buttons, words not icons   |\n */\n\nimport { cn } from '@/lib/utils';\nimport { Button } from '@/components/ui/button';\n\nexport const MIN_VIEWPORT = 320 as const;\n\n/** The event Chromium browsers fire when the page can be installed. */\ninterface BeforeInstallPromptEvent extends Event {\n  prompt: () => Promise<void>;\n  userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>;\n}\n\nexport type InstallPlatform = 'prompt' | 'ios' | null;\n\nexport interface UseInstallPromptOptions {\n  /** Where the Not now choice is remembered (localStorage). @default 'interlace:install-dismissed' */\n  storageKey?: string;\n  /** Days to stay quiet after Not now. @default 30 */\n  dismissDays?: number;\n}\n\nexport interface InstallPromptState {\n  /** How this browser installs: its own dialog, the iOS Share sheet, or not at all. */\n  platform: InstallPlatform;\n  /** The page runs as an installed app (standalone display mode). */\n  installed: boolean;\n  /** Whether to offer the install: possible here, not installed, not recently dismissed. */\n  canInstall: boolean;\n  /** Open the browser's install dialog. Resolves to whether the reader accepted. */\n  install: () => Promise<boolean>;\n  /** Not now: stay quiet for `dismissDays`. */\n  dismiss: () => void;\n}\n\nconst DAY = 86_400_000;\n\nfunction readStorage(key: string): string | null {\n  try {\n    return window.localStorage.getItem(key);\n  } catch {\n    return null;\n  }\n}\n\nfunction writeStorage(key: string, value: string) {\n  try {\n    window.localStorage.setItem(key, value);\n  } catch {\n    // Private mode or storage off: the offer just comes back next visit.\n  }\n}\n\nfunction isStandalone(): boolean {\n  const nav = navigator as Navigator & { standalone?: boolean };\n  return nav.standalone === true || window.matchMedia?.('(display-mode: standalone)').matches === true;\n}\n\n/** Safari on iOS and iPadOS, which installs from the Share sheet only. */\nexport function isIosSafari(userAgent: string, maxTouchPoints: number): boolean {\n  const ios = /iPad|iPhone|iPod/.test(userAgent) || (/Macintosh/.test(userAgent) && maxTouchPoints > 1);\n  const otherBrowser = /CriOS|FxiOS|EdgiOS|OPiOS|GSA\\//.test(userAgent);\n  return ios && !otherBrowser && /Safari\\//.test(userAgent);\n}\n\nexport function useInstallPrompt({\n  storageKey = 'interlace:install-dismissed',\n  dismissDays = 30,\n}: UseInstallPromptOptions = {}): InstallPromptState {\n  const [deferred, setDeferred] = React.useState<BeforeInstallPromptEvent | null>(null);\n  const [ios, setIos] = React.useState(false);\n  const [installed, setInstalled] = React.useState(false);\n  const [dismissed, setDismissed] = React.useState(true);\n\n  React.useEffect(() => {\n    setInstalled(isStandalone());\n    setIos(isIosSafari(navigator.userAgent, navigator.maxTouchPoints ?? 0));\n    const at = Number(readStorage(storageKey));\n    setDismissed(Number.isFinite(at) && at > 0 && Date.now() - at < dismissDays * DAY);\n    const onPrompt = (event: Event) => {\n      // Keep the browser's mini-bar away; the offer is ours to make.\n      event.preventDefault();\n      setDeferred(event as BeforeInstallPromptEvent);\n    };\n    const onInstalled = () => {\n      setInstalled(true);\n      setDeferred(null);\n    };\n    window.addEventListener('beforeinstallprompt', onPrompt);\n    window.addEventListener('appinstalled', onInstalled);\n    return () => {\n      window.removeEventListener('beforeinstallprompt', onPrompt);\n      window.removeEventListener('appinstalled', onInstalled);\n    };\n  }, [storageKey, dismissDays]);\n\n  const platform: InstallPlatform = deferred ? 'prompt' : ios ? 'ios' : null;\n\n  const install = React.useCallback(async () => {\n    if (!deferred) return false;\n    await deferred.prompt();\n    const { outcome } = await deferred.userChoice;\n    // A prompt can be used once.\n    setDeferred(null);\n    return outcome === 'accepted';\n  }, [deferred]);\n\n  const dismiss = React.useCallback(() => {\n    writeStorage(storageKey, String(Date.now()));\n    setDismissed(true);\n  }, [storageKey]);\n\n  return { platform, installed, canInstall: platform !== null && !installed && !dismissed, install, dismiss };\n}\n\nexport interface InstallPromptLabels {\n  /** @default 'Install the app' */\n  title: string;\n  /** @default 'Open it from your home screen, full screen, like any other app.' */\n  description: string;\n  /** @default 'Install' */\n  install: string;\n  /** @default 'Not now' */\n  dismiss: string;\n  /** Before the Share icon on iOS. @default 'Tap' */\n  iosBefore: string;\n  /** The Share icon's name on iOS. @default 'Share' */\n  iosShare: string;\n  /** After the Share icon on iOS. @default 'then Add to Home Screen.' */\n  iosAfter: string;\n}\n\nconst LABELS: InstallPromptLabels = {\n  title: 'Install the app',\n  description: 'Open it from your home screen, full screen, like any other app.',\n  install: 'Install',\n  dismiss: 'Not now',\n  iosBefore: 'Tap',\n  iosShare: 'Share',\n  iosAfter: 'then Add to Home Screen.',\n};\n\nexport interface InstallPromptProps\n  extends Omit<React.ComponentProps<'section'>, 'title'>,\n    UseInstallPromptOptions {\n  /** The app's icon, decorative. */\n  icon?: React.ReactNode;\n  /** Words, in the page's language. */\n  labels?: Partial<InstallPromptLabels>;\n  /** After the reader answers the browser's dialog. */\n  onInstallChoice?: (accepted: boolean) => void;\n}\n\nconst ShareIcon = () => (\n  <svg\n    aria-hidden\n    focusable=\"false\"\n    viewBox=\"0 0 24 24\"\n    fill=\"none\"\n    stroke=\"currentColor\"\n    strokeWidth={2}\n    strokeLinecap=\"round\"\n    strokeLinejoin=\"round\"\n    className=\"inline size-4 align-[-0.125em]\"\n  >\n    <path d=\"M12 3v12\" />\n    <path d=\"m8 7 4-4 4 4\" />\n    <path d=\"M6 11H5a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-8a1 1 0 0 0-1-1h-1\" />\n  </svg>\n);\n\nfunction InstallPrompt({\n  icon,\n  labels: labelsProp,\n  storageKey,\n  dismissDays,\n  onInstallChoice,\n  className,\n  ...props\n}: InstallPromptProps) {\n  const labels = { ...LABELS, ...labelsProp };\n  const { platform, canInstall, install, dismiss } = useInstallPrompt({ storageKey, dismissDays });\n  const titleId = React.useId();\n  if (!canInstall) return null;\n  return (\n    <section\n      data-slot=\"install-prompt\"\n      data-min-viewport={String(MIN_VIEWPORT)}\n      data-platform={platform}\n      aria-labelledby={titleId}\n      className={cn(\n        '@container bg-card text-card-foreground border-border rounded-lg border p-4 shadow-sm',\n        'motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-bottom-2 motion-safe:duration-(--duration-medium) motion-safe:ease-enter',\n        className,\n      )}\n      {...props}\n    >\n      <div className=\"flex flex-col gap-3 @md:flex-row @md:items-center\">\n        <div className=\"flex min-w-0 flex-1 gap-3\">\n          {icon ? (\n            <span\n              aria-hidden\n              data-slot=\"install-prompt-icon\"\n              className=\"flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-md [&_img]:size-full [&_svg]:size-6\"\n            >\n              {icon}\n            </span>\n          ) : null}\n          <div className=\"min-w-0\">\n            <h2 id={titleId} className=\"text-base font-semibold\">\n              {labels.title}\n            </h2>\n            <p className=\"text-muted-foreground text-sm\">\n              {platform === 'ios' ? (\n                <>\n                  {labels.iosBefore} <ShareIcon />\n                  <span className=\"text-foreground font-medium\"> {labels.iosShare}</span> {labels.iosAfter}\n                </>\n              ) : (\n                labels.description\n              )}\n            </p>\n          </div>\n        </div>\n        <div data-slot=\"install-prompt-actions\" className=\"flex flex-wrap items-center justify-end gap-2\">\n          <Button variant=\"ghost\" size=\"sm\" onClick={dismiss}>\n            {labels.dismiss}\n          </Button>\n          {platform === 'prompt' ? (\n            <Button\n              size=\"sm\"\n              onClick={async () => {\n                // Call install() first: `onInstallChoice?.(await install())` would skip it.\n                const accepted = await install();\n                onInstallChoice?.(accepted);\n              }}\n            >\n              {labels.install}\n            </Button>\n          ) : null}\n        </div>\n      </div>\n    </section>\n  );\n}\nInstallPrompt.displayName = 'InstallPrompt';\n\nexport { InstallPrompt };\n"
    }
  ],
  "meta": {
    "tier": "pattern",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.0.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/install-prompt\n\nInstalled to `components/ui/patterns/install-prompt.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/patterns/install-prompt';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/install-prompt\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
