{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "attachment",
  "title": "Attachment",
  "description": "A file attached to a chat message, or waiting to be sent with one: an icon for its kind, its name and size.",
  "registryDependencies": [
    "@ouro/lib-class-name-check",
    "@ouro/lib-cn",
    "@ouro/lib-env",
    "@ouro/lib-focus-handoff",
    "@ouro/lib-refs",
    "@ouro/lib-use-dev-messages"
  ],
  "files": [
    {
      "path": "registry/ouro/components/ouro/message/attachment.tsx",
      "content": "\"use client\";\n\nimport type { HTMLAttributes, JSX, MouseEvent, ReactNode, Ref } from \"react\";\nimport { useFocusHandoff } from \"@/registry/ouro/lib/ouro/focus-handoff\";\nimport { useMergedRef } from \"@/registry/ouro/lib/ouro/refs\";\nimport { useAppearanceClassNameCheck } from \"@/registry/ouro/lib/ouro/class-name-check\";\nimport { cn } from \"@/registry/ouro/lib/ouro/cn\";\nimport { useDevWarnings } from \"@/registry/ouro/lib/ouro/use-dev-messages\";\n\n/** What kind of file an attachment is, which picks its icon. */\nexport type AttachmentKind = \"doc\" | \"sheet\" | \"slides\" | \"pdf\" | \"image\" | \"video\" | \"audio\" | \"zip\" | \"code\" | \"file\";\n\n/** The props Attachment adds to the `<div>` attributes it passes through. */\nexport interface AttachmentOwnProps {\n  /**\n   * The file's name, as the user sees it: \"menu.pdf\". Required, so every file has a name.\n   *\n   * @claim \"Required, so every file has a\" registry/ouro/components/ouro/message/attachment.test-d.ts verify:fileLine(registry/ouro/components/ouro/message/attachment.test-d.ts, /expectTypeOf<\\{\\shref:\\s\"\\/menu\\.pdf\"\\s\\}>\\(\\)\\.not\\.toExtend<AttachmentProps>/)\n   */\n  name: string;\n  /** Where the file opens or downloads. With it, the attachment is a link named by the file and its size. */\n  href?: string | undefined;\n  /** Downloads the file instead of opening it (the link's `download` attribute). Needs `href`. */\n  download?: boolean | undefined;\n  /** The file's size in bytes (`file.size`), shown as \"1.2 MB\". */\n  size?: number | undefined;\n  /** The file's MIME type (`file.type`). With the name's extension, it picks the icon: \"application/pdf\" or \"menu.pdf\" shows a PDF's. */\n  contentType?: string | undefined;\n  /**\n   * The kind of file, for its icon, when the type and the name do not say: a document, a spreadsheet, slides, a PDF,\n   * an image, a video, audio, an archive, code, or any other file.\n   * @default from `contentType`, then the name's extension, else \"file\"\n   */\n  kind?: AttachmentKind | (string & { 'Use \"doc\", \"sheet\", \"slides\", \"pdf\", \"image\", \"video\", \"audio\", \"zip\", \"code\" or \"file\"': never }) | undefined;\n  /** An icon to show instead of the one for the file's kind, such as the app's own file-type icons. */\n  icon?: ReactNode;\n  /**\n   * Opens the file in the app, for example in a `Lightbox`. Without `href` the attachment is a button that calls it.\n   * With `href` it stays a link: a plain click calls it instead of following the link, and a click with a modifier\n   * key (a new tab, a new window) or the middle button follows the link as usual.\n   */\n  onOpen?: ((event: MouseEvent<HTMLElement>) => void) | undefined;\n  /** Shows a remove button, which calls this. Use it while composing a message, before it is sent. */\n  onRemove?: (() => void) | undefined;\n  /** The remove button's accessible name, for other languages. @default (name) => `Remove ${name}` */\n  removeLabel?: ((name: string) => string) | undefined;\n  /**\n   * Writes `size` for other languages or units.\n   * @default \"512 B\", \"2 kB\", \"1.2 MB\", in steps of 1024\n   * @claim \"in steps of 1024\" registry/ouro/components/ouro/message/attachment.test.tsx verify:testExists(registry/ouro/components/ouro/message/attachment.test.tsx::Attachment > names the file and gives its size in readable units) verify:fileLine(registry/ouro/components/ouro/message/attachment.test.tsx, /\\[2048,\\s\"2\\skB\"\\]/)\n   */\n  formatSize?: ((bytes: number) => string) | undefined;\n  /** Layout only: margins, width (`mt-2`). Appearance classes warn in development. */\n  className?: string | undefined;\n  ref?: Ref<HTMLDivElement> | undefined;\n\n  /** Not a prop. The file's name is `name`: `<Attachment name=\"menu.pdf\" />`. */\n  fileName?: { 'Use <Attachment name=\"menu.pdf\" />': never };\n  /** Not a prop. The file's name is `name`: `<Attachment name=\"menu.pdf\" />`. */\n  filename?: { 'Use <Attachment name=\"menu.pdf\" />': never };\n  /** Not a prop. The file's address is `href`: `<Attachment name=\"menu.pdf\" href=\"/menu.pdf\" />`. */\n  url?: { 'Use <Attachment name=\"menu.pdf\" href=\"/menu.pdf\" />': never };\n  /** Not a prop. Use `onRemove`: `<Attachment name=\"menu.pdf\" onRemove={remove} />`. */\n  onDelete?: { 'Use <Attachment name=\"menu.pdf\" onRemove={remove} />': never };\n  /** Not a prop. Use `onRemove`: `<Attachment name=\"menu.pdf\" onRemove={remove} />`. */\n  onDismiss?: { 'Use <Attachment name=\"menu.pdf\" onRemove={remove} />': never };\n}\n\n/** Props for {@link Attachment}: its own props and the `<div>` attributes it passes through. */\nexport type AttachmentProps = Omit<HTMLAttributes<HTMLDivElement>, keyof AttachmentOwnProps> & AttachmentOwnProps;\n\nconst units = [\"B\", \"kB\", \"MB\", \"GB\", \"TB\"] as const;\nconst oneDecimal = new Intl.NumberFormat(\"en\", { maximumFractionDigits: 1 });\n\n/**\n * \"512 B\", \"2 kB\", \"1.2 MB\": steps of 1024, at most one decimal.\n *\n * @claim \"steps of 1024, at most one decimal\" registry/ouro/components/ouro/message/attachment.test.tsx verify:testExists(registry/ouro/components/ouro/message/attachment.test.tsx::Attachment > names the file and gives its size in readable units)\n * @claim \"steps of 1024, at most one decimal\" registry/ouro/components/ouro/message/attachment.test.tsx verify:fileLine(registry/ouro/components/ouro/message/attachment.test.tsx, /\\[2048,\\s\"2\\skB\"\\]/)\n */\nfunction defaultFormatSize(bytes: number): string {\n  let value = bytes;\n  let unit = 0;\n  while (value >= 1024 && unit < units.length - 1) {\n    value /= 1024;\n    unit += 1;\n  }\n  return `${oneDecimal.format(value)} ${units[unit]}`;\n}\n\nconst validSize = (size: number | undefined): size is number => typeof size === \"number\" && Number.isFinite(size) && size >= 0;\n\nconst focusRing = \"outline-ring outline-offset-2 focus-visible:outline-2 focus-visible:outline-solid\";\n\nconst kinds = [\"doc\", \"sheet\", \"slides\", \"pdf\", \"image\", \"video\", \"audio\", \"zip\", \"code\", \"file\"] as const;\n\n/** A kind's MIME types, space-separated, beyond the image, video and audio families. */\nconst typeSources: ReadonlyArray<readonly [AttachmentKind, string]> = [\n  [\"pdf\", \"application/pdf\"],\n  [\n    \"doc\",\n    \"application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document application/vnd.oasis.opendocument.text application/rtf text/plain text/markdown\",\n  ],\n  [\"sheet\", \"application/vnd.ms-excel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet application/vnd.oasis.opendocument.spreadsheet text/csv\"],\n  [\"slides\", \"application/vnd.ms-powerpoint application/vnd.openxmlformats-officedocument.presentationml.presentation application/vnd.oasis.opendocument.presentation\"],\n  [\"zip\", \"application/zip application/x-7z-compressed application/vnd.rar application/gzip application/x-tar\"],\n  [\"code\", \"application/json text/javascript text/html text/css application/xml text/xml\"],\n];\n\n/** A kind's file name extensions, space-separated. */\nconst extensionSources: ReadonlyArray<readonly [AttachmentKind, string]> = [\n  [\"pdf\", \"pdf\"],\n  [\"doc\", \"doc docx odt rtf txt md pages\"],\n  [\"sheet\", \"xls xlsx ods csv tsv numbers\"],\n  [\"slides\", \"ppt pptx odp key\"],\n  [\"image\", \"png jpg jpeg gif webp svg heic avif bmp tif tiff\"],\n  [\"video\", \"mp4 mov webm mkv avi m4v\"],\n  [\"audio\", \"mp3 wav m4a ogg flac aac\"],\n  [\"zip\", \"zip 7z rar gz tgz tar bz2 xz\"],\n  [\"code\", \"js jsx ts tsx json py rb go rs java c cpp h cs swift kt sh yml yaml toml html css xml sql php\"],\n];\nconst lookup = (sources: ReadonlyArray<readonly [AttachmentKind, string]>) => new Map(sources.flatMap(([kind, list]) => list.split(\" \").map((key) => [key, kind] as const)));\nconst byType = lookup(typeSources);\nconst byExtension = lookup(extensionSources);\n\n/**\n * The kind from the MIME type (its whole family for images, video and audio), then from the name's extension.\n *\n * @claim \"The kind from the MIME type\" registry/ouro/components/ouro/message/attachment.test.tsx verify:testExists(registry/ouro/components/ouro/message/attachment.test.tsx::Attachment > picks the icon from the MIME type, then the name's extension)\n */\nfunction kindOf(contentType: string | undefined, name: string): AttachmentKind {\n  // Stryker disable next-line StringLiteral: without a type, any string that is no MIME type gives the same answer.\n  const type = (contentType ?? \"\").split(\";\")[0]!.trim().toLowerCase();\n  const family = type.split(\"/\")[0]!;\n  if (family === \"image\" || family === \"video\" || family === \"audio\") return family;\n  const dot = name.lastIndexOf(\".\");\n  return byType.get(type) ?? (dot > 0 ? byExtension.get(name.slice(dot + 1).toLowerCase()) : undefined) ?? \"file\";\n}\n\n/**\n * A file attached to a chat message, or waiting to be sent with one: an icon for its kind,\n * its name and size. With `href` it is a link that opens or downloads the file; with\n * `onOpen` it opens the file in the app, such as in a `Lightbox`; with `onRemove` it has a\n * remove button, named after the file, for the composer. Long names truncate.\n *\n * Use `Link` instead for a link that is not a file, and `Avatar` for a person's picture.\n *\n * @group Chat\n * @see https://ui.ouroboros.bot/docs/attachment\n *\n * @example\n * <Attachment name=\"menu.pdf\" size={file.size} contentType={file.type} href={file.url} />\n * <Attachment name={file.name} size={file.size} onRemove={() => remove(file)} />\n * <Attachment name=\"crumb.jpg\" contentType=\"image/jpeg\" href={file.url} onOpen={() => showInLightbox(file)} />\n */\nexport function Attachment(props: AttachmentProps): JSX.Element {\n  const {\n    name: nameProp,\n    href,\n    download,\n    size,\n    contentType,\n    kind: kindProp,\n    icon,\n    onOpen,\n    onRemove,\n    removeLabel = (file: string) => `Remove ${file}`,\n    formatSize = defaultFormatSize,\n    className,\n    ref,\n    // Guard props (hint types), dropped here so they never reach the DOM.\n    fileName,\n    filename,\n    url,\n    onDelete,\n    onDismiss,\n    ...rest\n  } = props;\n  const name = nameProp ?? \"\";\n  const kind: AttachmentKind = (kinds as readonly string[]).includes(kindProp as string) ? (kindProp as AttachmentKind) : kindOf(contentType, name);\n  useAppearanceClassNameCheck(\n    \"Attachment\",\n    className,\n    process.env.NODE_ENV !== \"production\"\n      ? (token: string) => `<div className=\"${token}\"><Attachment /></div>`\n      : /* istanbul ignore next @preserve -- production only */ \"\",\n  );\n  useDevWarnings(\n    \"Attachment\",\n    process.env.NODE_ENV !== \"production\"\n      ? () => [\n          nameProp === undefined && [\"name is missing, so the file has no name\", '<Attachment name=\"menu.pdf\" />'],\n          (fileName !== undefined || filename !== undefined) && [`${fileName !== undefined ? \"fileName\" : \"filename\"} is not a prop`, '<Attachment name=\"menu.pdf\" />'],\n          url !== undefined && [\"url is not a prop\", '<Attachment name=\"menu.pdf\" href=\"/menu.pdf\" />'],\n          (onDelete !== undefined || onDismiss !== undefined) && [\n            `${onDelete !== undefined ? \"onDelete\" : \"onDismiss\"} is not a prop`,\n            '<Attachment name=\"menu.pdf\" onRemove={remove} />',\n          ],\n          download !== undefined && href === undefined && [\"download needs href, the file to download\", '<Attachment name=\"menu.pdf\" href=\"/menu.pdf\" download />'],\n          size !== undefined && !validSize(size) && [`size={${String(size)}} is not a byte count`, '<Attachment name=\"menu.pdf\" size={file.size} />'],\n          kindProp !== undefined && kind !== kindProp && [`kind=\"${String(kindProp)}\" is not a kind; use \"doc\", \"sheet\", \"slides\", \"pdf\", \"image\", \"video\", \"audio\", \"zip\", \"code\" or \"file\"`, '<Attachment name=\"notes\" kind=\"doc\" />'],\n        ]\n      : /* istanbul ignore next @preserve -- production only */ undefined,\n  );\n  const body = (\n    <>\n      {icon === undefined || icon === null || icon === false ? (\n        <FileIcon kind={kind} />\n      ) : (\n        <span aria-hidden=\"true\" data-ouro-attachment-icon={kind} className=\"flex size-5 shrink-0 items-center justify-center text-muted-foreground [&_svg]:size-5\">\n          {icon}\n        </span>\n      )}\n      <span data-ouro-attachment-name=\"\" title={name} className=\"min-w-0 flex-1 truncate font-medium\">\n        {name}\n      </span>\n      {validSize(size) && (\n        <>\n          {/* A space, so the link's name reads \"menu.pdf 2 kB\". */}\n          <span className=\"sr-only\"> </span>\n          <span data-ouro-attachment-size=\"\" className=\"shrink-0 text-muted-foreground tabular-nums\">\n            {formatSize(size)}\n          </span>\n        </>\n      )}\n    </>\n  );\n  const inner = \"flex min-h-11 min-w-0 flex-1 items-center gap-2 px-3 pointer-fine:min-h-9\";\n  const openableClass = \"press rounded-[inherit] text-inherit no-underline pointer-fine:hover:bg-accent pointer-fine:hover:text-accent-foreground motion-safe:active:scale-(--ouro-press-scale)\";\n  // A remove button that removes the attachment hands its focus to the next one, or the one before.\n  const merged = useMergedRef(ref, useFocusHandoff<HTMLDivElement>());\n  return (\n    <div\n      {...rest}\n      ref={merged}\n      data-ouro=\"attachment\"\n      className={cn(\n        \"relative box-border inline-flex max-w-full min-w-0 items-center rounded-ouro-lg border border-solid border-border bg-card\",\n        \"align-middle text-base text-card-foreground pointer-fine:text-sm\",\n        className,\n      )}\n    >\n      {href !== undefined ? (\n        <a\n          href={href}\n          download={download || undefined}\n          data-ouro-control=\"attachment\"\n          data-ouro-part=\"link\"\n          onClick={\n            onOpen &&\n            ((event) => {\n              // A new tab or window, or a download, is the link's own job.\n              if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;\n              event.preventDefault();\n              onOpen(event);\n            })\n          }\n          className={cn(inner, openableClass, focusRing)}\n        >\n          {body}\n        </a>\n      ) : onOpen ? (\n        <button type=\"button\" data-ouro-control=\"attachment\" data-ouro-part=\"open\" onClick={onOpen} className={cn(inner, openableClass, \"m-0 cursor-pointer border-0 bg-transparent text-start font-[inherit]\", focusRing)}>\n          {body}\n        </button>\n      ) : (\n        <span className={inner}>{body}</span>\n      )}\n      {onRemove && (\n        <button\n          type=\"button\"\n          aria-label={removeLabel(name)}\n          data-ouro-control=\"attachment\"\n          data-ouro-part=\"remove\"\n          onClick={onRemove}\n          className={cn(\n            \"press relative m-0 box-border inline-flex size-11 shrink-0 pointer-fine:me-1.5 pointer-fine:size-7 items-center justify-center rounded-ouro-md border-0 bg-transparent p-0\",\n            \"cursor-pointer text-muted-foreground touch-manipulation pointer-fine:hover:bg-accent pointer-fine:hover:text-accent-foreground\",\n            \"motion-safe:active:scale-(--ouro-press-scale)\",\n            focusRing,\n          )}\n        >\n          <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" className=\"size-4\">\n            <path d=\"M4 4l8 8M12 4l-8 8\" />\n          </svg>\n        </button>\n      )}\n    </div>\n  );\n}\n\n// The page every document-like kind draws, with its corner folded.\nconst page = \"M11.5 2.5H6a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V7zM11.5 2.5V7H16\";\n\n/** A kind's drawing, a single path on the icon's grid. */\nconst glyphs: Readonly<Record<AttachmentKind, string>> = {\n  file: page,\n  doc: `${page}M7 10.5h6M7 13.5h4`,\n  sheet: `${page}M7 10h6v4.5H7zM10 10v4.5M7 12.25h6`,\n  slides: `${page}M7 10h6v3.5H7zM8.5 15.5h3`,\n  pdf: `${page}M2.5 10.5h8v4h-8z`,\n  code: `${page}M8.5 10l-1.5 2 1.5 2M11.5 10l1.5 2-1.5 2`,\n  zip: `${page}M10 2.5v1.5M10 5.5v1.5M10 8.5v1.5M8.75 11.5h2.5v2.5h-2.5z`,\n  image: \"M5 3.5h10a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-9a2 2 0 0 1 2-2zM6 8a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0-3 0zM3.5 14.5l4-4 3 3 2-2 4 4\",\n  video: \"M4.5 4.5h11a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2h-11a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2zM8.5 7.5v5l4-2.5z\",\n  audio: \"M8 14.5V5l8-1.5V13M8 14.5a2 2 0 1 1-4 0a2 2 0 1 1 4 0zM16 13a2 2 0 1 1-4 0a2 2 0 1 1 4 0z\",\n};\n\n// Documents, spreadsheets, slides and PDFs take the colors people know them by, from the theme's tokens;\n// the rest stay muted.\nconst kindToneClass: Readonly<Record<AttachmentKind, string>> = {\n  doc: \"text-primary\",\n  sheet: \"text-success\",\n  slides: \"text-warning\",\n  pdf: \"text-destructive\",\n  image: \"text-muted-foreground\",\n  video: \"text-muted-foreground\",\n  audio: \"text-muted-foreground\",\n  zip: \"text-muted-foreground\",\n  code: \"text-muted-foreground\",\n  file: \"text-muted-foreground\",\n};\n\n/** The drawing for the file's kind. */\nfunction FileIcon({ kind }: { kind: AttachmentKind }): JSX.Element {\n  return (\n    <svg\n      aria-hidden=\"true\"\n      data-ouro-attachment-icon={kind}\n      viewBox=\"0 0 20 20\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.5\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      className={cn(\"size-5 shrink-0\", kindToneClass[kind])}\n    >\n      <path d={glyphs[kind]} />\n    </svg>\n  );\n}\n",
      "type": "registry:ui",
      "target": "@components/ouro/message/attachment.tsx"
    }
  ],
  "docs": "A file attached to a chat message, or waiting to be sent with one: an icon for its kind, its name and size. Import: import { Attachment } from \"@/components/ouro/message/attachment\", with @/components replaced by your components alias (aliases.components in components.json, such as ~/components). Also installed: the helpers it imports in lib/ouro. Needs ouro-base in your stylesheet: add that item once per app, from the same place as this one, if you have not. Docs: https://ui.ouroboros.bot/docs/attachment.md Ouro UI v1.3.257.",
  "type": "registry:ui"
}