{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "story-frame",
  "title": "Story Frame",
  "description": "A 9:16 story preview that is the exported PNG itself, with Share (the phone's share sheet, Instagram included), Download and Copy link, and the safe area the apps draw over.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "@corsair-ui/utils",
    "@corsair-ui/button",
    "@corsair-ui/story-export"
  ],
  "files": [
    {
      "path": "registry/default/ui/story-frame.tsx",
      "content": "\"use client\";\n\nimport { CheckIcon, DownloadIcon, LinkIcon, ShareIcon } from \"lucide-react\";\nimport { useEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from \"react\";\n\nimport {\n  canShareStory,\n  downloadStory,\n  loadFont,\n  renderStorySvg,\n  shareStory,\n  STORY_SAFE_AREA,\n  STORY_SIZE,\n  svgToPng,\n  type StoryFont,\n  type StoryShareResult,\n} from \"@/registry/default/lib/story-export\";\nimport { cn } from \"@/registry/default/lib/utils\";\nimport { Button } from \"@/registry/default/ui/button\";\n\n/** A font to fetch for a story: where it is, and how the story names it. */\ninterface StoryFontSource extends Omit<StoryFont, \"data\"> {\n  url: string;\n}\n\n/**\n * Fetches the fonts a story uses, once. `fonts` is null until all of them\n * have loaded, which is what `StoryFrame` waits for.\n *\n * @example\n * const { fonts } = useStoryFonts([\n *   { name: \"Barlow\", url: \"/fonts/Barlow-Regular.ttf\", weight: 400 },\n *   { name: \"Barlow\", url: \"/fonts/Barlow-Bold.ttf\", weight: 700 },\n * ]);\n */\nfunction useStoryFonts(sources: StoryFontSource[]) {\n  const [state, setState] = useState<{\n    key: string;\n    fonts: StoryFont[] | null;\n    error: Error | null;\n  }>({ key: \"\", fonts: null, error: null });\n  // A new array each render must not refetch: the sources themselves decide.\n  const key = JSON.stringify(sources);\n\n  useEffect(() => {\n    let active = true;\n    const wanted: StoryFontSource[] = JSON.parse(key);\n    Promise.all(\n      wanted.map(async ({ url, ...font }) => ({ ...font, data: await loadFont(url) }))\n    ).then(\n      (fonts) => {\n        if (active) setState({ key, fonts, error: null });\n      },\n      (error: unknown) => {\n        if (active) setState({ key, fonts: null, error: toError(error) });\n      }\n    );\n    return () => {\n      active = false;\n    };\n  }, [key]);\n\n  return state.key === key\n    ? { fonts: state.fonts, error: state.error }\n    : { fonts: null, error: null };\n}\n\nfunction toError(error: unknown) {\n  return error instanceof Error ? error : new Error(String(error));\n}\n\ntype StoryImageStatus = \"rendering\" | \"ready\" | \"error\";\n\ninterface StoryImage {\n  status: StoryImageStatus;\n  /** The latest PNG, kept while a newer one renders. */\n  blob: Blob | null;\n  /** An object URL for `blob`, revoked when it is replaced or on unmount. */\n  url: string | null;\n  error: Error | null;\n}\n\n/**\n * Renders a story to a PNG whenever it changes, a moment after the last\n * change. Unchanged stories are not drawn again. For a layout of your own\n * around the image; `StoryFrame` uses it.\n */\nfunction useStoryImage(\n  story: ReactNode,\n  {\n    fonts,\n    width = STORY_SIZE.width,\n    height = STORY_SIZE.height,\n    delay = 120,\n  }: { fonts: StoryFont[] | null | undefined; width?: number; height?: number; delay?: number }\n): StoryImage {\n  const [image, setImage] = useState<StoryImage>({\n    status: \"rendering\",\n    blob: null,\n    url: null,\n    error: null,\n  });\n  const drawn = useRef<string | null>(null);\n  const current = useRef<string | null>(null);\n\n  useEffect(() => {\n    if (!fonts) return;\n    let cancelled = false;\n    const timer = setTimeout(async () => {\n      try {\n        const svg = await renderStorySvg(story, { fonts, width, height });\n        if (cancelled || svg === drawn.current) return;\n        setImage((previous) => ({ ...previous, status: \"rendering\" }));\n        const blob = await svgToPng(svg, width, height);\n        if (cancelled) return;\n        const url = URL.createObjectURL(blob);\n        const previous = current.current;\n        drawn.current = svg;\n        current.current = url;\n        setImage({ status: \"ready\", blob, url, error: null });\n        if (previous) URL.revokeObjectURL(previous);\n      } catch (error) {\n        if (!cancelled)\n          setImage((previous) => ({ ...previous, status: \"error\", error: toError(error) }));\n      }\n    }, delay);\n    return () => {\n      cancelled = true;\n      clearTimeout(timer);\n    };\n  }, [story, fonts, width, height, delay]);\n\n  useEffect(\n    () => () => {\n      if (current.current) URL.revokeObjectURL(current.current);\n    },\n    []\n  );\n\n  return image;\n}\n\ninterface StoryFrameLabels {\n  share: string;\n  download: string;\n  copyLink: string;\n  copied: string;\n  safeArea: string;\n  /** Announced while the image is drawn. */\n  rendering: string;\n  /** Announced once the image is ready. */\n  ready: string;\n  error: string;\n  shared: string;\n  downloaded: string;\n  /** Under the buttons when there is a link: how to put it on the story. */\n  linkHint: string;\n}\n\nconst DEFAULT_LABELS: StoryFrameLabels = {\n  share: \"Share\",\n  download: \"Download\",\n  copyLink: \"Copy link\",\n  copied: \"Link copied\",\n  safeArea: \"Safe area\",\n  rendering: \"Drawing the story\",\n  ready: \"Story ready\",\n  error: \"The story could not be drawn.\",\n  shared: \"Story shared\",\n  downloaded: \"Story downloaded\",\n  linkHint: \"Sharing copies the link too: add a link sticker to the story and paste it.\",\n};\n\ntype StoryFrameResult = StoryShareResult | \"downloaded\";\n\ninterface StoryFrameProps extends Omit<ComponentProps<\"div\">, \"children\" | \"onError\"> {\n  /**\n   * The story: an element in the subset Satori supports (inline styles,\n   * flexbox), such as a `Story`.\n   */\n  story: ReactNode;\n  /** The fonts the story uses. Null or undefined while they load. */\n  fonts: StoryFont[] | null | undefined;\n  /** What the image shows, for screen readers. */\n  alt: string;\n  /** Put on the clipboard when sharing, and copied by its own button. */\n  link?: string;\n  /** Name of the shared or downloaded file. */\n  fileName?: string;\n  /** Title some share sheets show. */\n  shareTitle?: string;\n  width?: number;\n  height?: number;\n  /** Shows the bands apps draw over at first. */\n  defaultShowSafeArea?: boolean;\n  labels?: Partial<StoryFrameLabels>;\n  onShare?: (result: StoryFrameResult) => void;\n  onError?: (error: Error) => void;\n  /** More buttons, after the built-in ones. */\n  children?: ReactNode;\n}\n\n/**\n * A story preview with what it takes to post it: on phones, Share opens the\n * share sheet with the PNG (Instagram, WhatsApp, the photo library); where\n * sharing files is not possible, Download saves it. With a `link`, sharing\n * also puts it on the clipboard, ready for a link sticker, since Instagram\n * does not take links from other apps.\n *\n * The preview is the exported image itself, drawn with Satori a moment after\n * the story changes, so what you see is what gets posted. The image is ready\n * before Share is pressed, as browsers only open the share sheet straight\n * from a tap. \"Safe area\" shows the bands the apps draw over.\n *\n * `data-state` is `rendering`, `ready` or `error`; the parts are\n * `story-frame-preview`, `story-frame-safe-area` and `story-frame-actions`.\n *\n * @example\n * const story = useMemo(() => <Story theme=\"midnight\">…</Story>, []);\n * <StoryFrame\n *   story={story}\n *   alt={storyAlt(story)}\n *   fonts={fonts}\n *   link=\"https://example.com/book?via=story\"\n *   fileName=\"free-today.png\"\n * />\n */\nfunction StoryFrame({\n  story,\n  fonts,\n  alt,\n  link,\n  fileName = \"story.png\",\n  shareTitle,\n  width = STORY_SIZE.width,\n  height = STORY_SIZE.height,\n  defaultShowSafeArea = false,\n  labels: labelsProp,\n  onShare,\n  onError,\n  className,\n  children,\n  ...props\n}: StoryFrameProps) {\n  const labels = { ...DEFAULT_LABELS, ...labelsProp };\n  const image = useStoryImage(story, { fonts, width, height });\n  const [showSafeArea, setShowSafeArea] = useState(defaultShowSafeArea);\n  const [copied, setCopied] = useState(false);\n  const [announcement, setAnnouncement] = useState(\"\");\n  const copiedTimer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  const reported = useRef<Error | null>(null);\n\n  const file = useMemo(\n    () => (image.blob ? new File([image.blob], fileName, { type: \"image/png\" }) : null),\n    [image.blob, fileName]\n  );\n  const canShare = useMemo(() => (file ? canShareStory(file) : false), [file]);\n  const status: StoryImageStatus = fonts ? image.status : \"rendering\";\n\n  useEffect(() => {\n    if (image.error && reported.current !== image.error) {\n      reported.current = image.error;\n      onError?.(image.error);\n    }\n  }, [image.error, onError]);\n\n  useEffect(() => () => clearTimeout(copiedTimer.current), []);\n\n  const markCopied = () => {\n    setCopied(true);\n    clearTimeout(copiedTimer.current);\n    copiedTimer.current = setTimeout(() => setCopied(false), 1600);\n  };\n\n  const copyLink = async () => {\n    if (!link) return false;\n    try {\n      await navigator.clipboard.writeText(link);\n      markCopied();\n      return true;\n    } catch {\n      return false;\n    }\n  };\n\n  const download = () => {\n    if (!image.blob) return;\n    downloadStory(image.blob, fileName);\n    setAnnouncement(labels.downloaded);\n    onShare?.(\"downloaded\");\n  };\n\n  const share = async () => {\n    if (!file) return;\n    // Started first and not awaited: the share sheet has to open within the tap.\n    const copying = link ? copyLink() : Promise.resolve(false);\n    try {\n      const result = await shareStory({ file, title: shareTitle });\n      await copying;\n      if (result === \"unsupported\") {\n        download();\n        return;\n      }\n      if (result === \"shared\") setAnnouncement(labels.shared);\n      onShare?.(result);\n    } catch (error) {\n      onError?.(toError(error));\n    }\n  };\n\n  const copy = async () => {\n    if (await copyLink()) setAnnouncement(labels.copied);\n  };\n\n  const safe = {\n    top: `${(STORY_SAFE_AREA.top / STORY_SIZE.height) * 100}%`,\n    bottom: `${(STORY_SAFE_AREA.bottom / STORY_SIZE.height) * 100}%`,\n    side: `${(STORY_SAFE_AREA.side / STORY_SIZE.width) * 100}%`,\n  };\n\n  return (\n    <div\n      data-slot=\"story-frame\"\n      data-state={status}\n      className={cn(\"flex w-full max-w-xs flex-col items-center gap-4\", className)}\n      {...props}\n    >\n      <div\n        data-slot=\"story-frame-preview\"\n        aria-busy={status === \"rendering\" || undefined}\n        className=\"bg-muted relative w-full overflow-hidden rounded-2xl border\"\n        style={{ aspectRatio: `${width} / ${height}` }}\n      >\n        {image.url ? (\n          <img\n            src={image.url}\n            alt={alt}\n            width={width}\n            height={height}\n            className={cn(\n              \"block size-full object-cover\",\n              status === \"rendering\" && \"opacity-70 motion-safe:transition-opacity\"\n            )}\n          />\n        ) : (\n          <div aria-hidden=\"true\" className=\"bg-muted size-full motion-safe:animate-pulse\" />\n        )}\n        {showSafeArea ? (\n          <div\n            data-slot=\"story-frame-safe-area\"\n            aria-hidden=\"true\"\n            className=\"pointer-events-none absolute inset-0\"\n          >\n            <div\n              className=\"bg-destructive/25 border-destructive/60 absolute inset-x-0 top-0 border-b border-dashed\"\n              style={{ height: safe.top }}\n            />\n            <div\n              className=\"bg-destructive/25 border-destructive/60 absolute inset-x-0 bottom-0 border-t border-dashed\"\n              style={{ height: safe.bottom }}\n            />\n            <div\n              className=\"border-destructive/60 absolute border-x border-dashed\"\n              style={{ top: safe.top, bottom: safe.bottom, left: safe.side, right: safe.side }}\n            />\n          </div>\n        ) : null}\n        {status === \"error\" ? (\n          <p\n            role=\"alert\"\n            className=\"bg-background/90 text-destructive absolute inset-x-3 bottom-3 rounded-md px-3 py-2 text-sm\"\n          >\n            {labels.error}\n          </p>\n        ) : null}\n      </div>\n\n      <div\n        data-slot=\"story-frame-actions\"\n        className=\"flex flex-wrap items-center justify-center gap-2\"\n      >\n        {canShare ? (\n          <Button type=\"button\" onClick={share} disabled={!file}>\n            <ShareIcon aria-hidden=\"true\" />\n            {labels.share}\n          </Button>\n        ) : null}\n        <Button\n          type=\"button\"\n          // A Button variant, not a class.\n          // tailwind-compat-ignore-next-line\n          variant={canShare ? \"outline\" : \"default\"}\n          onClick={download}\n          disabled={!image.blob}\n        >\n          <DownloadIcon aria-hidden=\"true\" />\n          {labels.download}\n        </Button>\n        {link ? (\n          <Button\n            type=\"button\"\n            variant=\"outline\"\n            onClick={copy}\n            data-state={copied ? \"copied\" : \"idle\"}\n          >\n            {copied ? <CheckIcon aria-hidden=\"true\" /> : <LinkIcon aria-hidden=\"true\" />}\n            {copied ? labels.copied : labels.copyLink}\n          </Button>\n        ) : null}\n        <Button\n          type=\"button\"\n          variant=\"ghost\"\n          aria-pressed={showSafeArea}\n          onClick={() => setShowSafeArea((shown) => !shown)}\n        >\n          {labels.safeArea}\n        </Button>\n        {children}\n      </div>\n\n      {link && canShare ? (\n        <p className=\"text-muted-foreground text-center text-sm text-pretty\">{labels.linkHint}</p>\n      ) : null}\n\n      <span role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n        {announcement ||\n          (status === \"ready\" ? labels.ready : status === \"rendering\" ? labels.rendering : \"\")}\n      </span>\n    </div>\n  );\n}\n\nexport {\n  StoryFrame,\n  useStoryFonts,\n  useStoryImage,\n  type StoryFontSource,\n  type StoryFrameLabels,\n  type StoryFrameProps,\n  type StoryFrameResult,\n  type StoryImage,\n  type StoryImageStatus,\n};\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}