{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "avatar-upload",
  "type": "registry:ui",
  "title": "Avatar Upload",
  "description": "A profile photo the reader can set, change or take away: the round photo as it will appear, a Choose photo button, and Remove once there is a photo. Dropping an image on the photo works too.",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "form",
    "pattern"
  ],
  "dependencies": [],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/avatar.json",
    "https://ds.interlace.tools/r/button.json",
    "https://ds.interlace.tools/r/button-variants.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/file-drop.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/patterns/avatar-upload.tsx",
      "target": "components/ui/patterns/avatar-upload.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/avatar-upload v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/avatar-upload\n// What changed since: https://ds.interlace.tools/c/avatar-upload#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — AvatarUpload\n *\n * A profile photo the reader can set, change or take away: the round photo\n * as it will appear, a Choose photo button, and Remove once there is a photo.\n * Dropping an image on the photo works too.\n *\n * ## Content first\n *\n * Choose photo is a `<label>` around a real `<input type=\"file\">`, so the\n * picker opens on a press, on Enter and on Space, a screen reader hears a\n * file field named \"Choose photo\", and the file posts with a form under\n * `name`. Dropping a file on the photo is a shortcut to the same field.\n *\n * ## Value\n *\n * `src` is the photo the reader already has. `value` is what they did here:\n * `undefined` while they changed nothing (the `src` photo shows), a `File`\n * once they chose one (a preview of it shows), and `null` once they removed\n * the photo (the fallback shows, usually initials). `onValueChange` hears\n * each change, so a save can tell \"new photo\", \"no photo\" and \"as it was\"\n * apart. The preview is an object URL, revoked when it is replaced or the\n * component goes.\n *\n * ## Rules\n *\n * The file is checked with `checkFiles` from `file-drop` (`accept`, default\n * `image/*`, and `maxSize`). A file that breaks a rule is not taken; the\n * reason is said in a polite live region under the buttons, in words\n * `messages` can replace, and `onReject` hears it.\n *\n * ## Motion\n *\n * The photo's ring answers a drag over it, timed by `--duration-fast` on\n * `--ease-enter`. The buttons press in. Nothing else moves.\n *\n * ## MIN_VIEWPORT — 320\n *\n * The photo sits beside its buttons; at 320px both still fit on one line\n * at the default size.\n *\n * ## Anatomy\n *\n *   AvatarUpload                  (div — data-slot=\"avatar-upload\", data-min-viewport=320)\n *     ├─ photo                    (div — data-slot=\"avatar-upload-photo\", data-dragging; drop target)\n *     │   └─ Avatar               (AvatarImage of the preview or `src`, AvatarFallback)\n *     └─ div\n *         ├─ actions              (data-slot=\"avatar-upload-actions\")\n *         │   ├─ label            (data-slot=\"avatar-upload-choose\": input[type=file] laid unseen over it + text)\n *         │   └─ Button?          (data-slot=\"avatar-upload-remove\")\n *         ├─ hint?                (data-slot=\"avatar-upload-hint\", the input's description)\n *         └─ status               (p aria-live=polite — data-slot=\"avatar-upload-status\")\n *\n * | Rule | Concept                 | Where in this file                                   |\n * | ---- | ----------------------- | ---------------------------------------------------- |\n * | R4   | Extends native el       | `div` props; the input is a native file input         |\n * | R6   | data-slot per part      | avatar-upload / -photo / -actions / -choose / -remove |\n * | R7   | cn + ...rest            | `cn(BASE, className)` + `{...props}`                  |\n * | R14  | Declares min viewport   | `data-min-viewport` + exported const                  |\n * | R19  | Tokens only             | `--avatar-upload-size`, `--ring`, `--primary`         |\n * | R25  | Client component        | the chosen file and its preview live in the browser   |\n * | R26  | A11y from native el     | label + file input; live status; a named Remove       |\n */\n\nimport { cn } from '@/lib/utils';\nimport { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';\nimport { Button } from '@/components/ui/button';\nimport { buttonVariants } from '@/components/ui/button-variants';\nimport { checkFiles, formatBytes, type FileRejection } from '@/components/ui/file-drop';\n\n/** Smallest viable viewport (CSS px) for this pattern. */\nexport const MIN_VIEWPORT = 320 as const;\n\nexport interface AvatarUploadMessages {\n  /** A file that isn't an image this field takes. */\n  type?: (file: File) => string;\n  /** A file over `maxSize`. */\n  size?: (file: File, maxSize: number) => string;\n}\n\nconst DEFAULT_MESSAGES: Required<AvatarUploadMessages> = {\n  type: (file) => `${file.name} isn't an image this field takes.`,\n  size: (file, max) => `${file.name} is larger than ${formatBytes(max)}.`,\n};\n\nexport interface AvatarUploadProps extends Omit<React.ComponentPropsWithoutRef<'div'>, 'defaultValue' | 'onChange'> {\n  /** The photo the reader already has. */\n  src?: string;\n  /** What shows with no photo, usually initials. */\n  fallback?: React.ReactNode;\n  /** The photo's text alternative, e.g. the person's name. */\n  alt?: string;\n  /** What the reader did here: `undefined` unchanged, a `File` chosen, `null` removed (controlled). */\n  value?: File | null;\n  /** The same at first (uncontrolled). */\n  defaultValue?: File | null;\n  /** Called with the chosen file, or `null` when the photo is removed. */\n  onValueChange?: (file: File | null) => void;\n  /** Called with a file turned away, and why. */\n  onReject?: (rejection: FileRejection<File>) => void;\n  /** The `accept` attribute, checked again on every pick and drop. @default 'image/*' */\n  accept?: string;\n  /** The largest file, in bytes. */\n  maxSize?: number;\n  /** The field name the file posts under with a form. */\n  name?: string;\n  disabled?: boolean;\n  /** One line on what it takes, e.g. \"JPG or PNG, up to 2 MB\". */\n  hint?: React.ReactNode;\n  /** The choose button's words. @default 'Choose photo' */\n  chooseLabel?: React.ReactNode;\n  /** The remove button's words. @default 'Remove' */\n  removeLabel?: React.ReactNode;\n  /** The sentences said when a file is turned away. */\n  messages?: AvatarUploadMessages;\n}\n\n/** Put `file` on the input, so a form posts what the photo shows. Skipped where DataTransfer can't be built. */\nfunction syncInput(input: HTMLInputElement | null, file: File | null | undefined) {\n  if (!input || typeof DataTransfer === 'undefined') return;\n  const transfer = new DataTransfer();\n  if (file) transfer.items.add(file);\n  input.files = transfer.files;\n}\n\n/** An object URL for `file`, revoked when the file changes or the component goes. */\nfunction usePreview(file: File | null | undefined): string | undefined {\n  const [url, setUrl] = React.useState<string>();\n  React.useEffect(() => {\n    if (!file || typeof URL.createObjectURL !== 'function') {\n      setUrl(undefined);\n      return;\n    }\n    const next = URL.createObjectURL(file);\n    setUrl(next);\n    return () => URL.revokeObjectURL(next);\n  }, [file]);\n  return url;\n}\n\nexport function AvatarUpload(allProps: AvatarUploadProps) {\n  const {\n    src,\n    fallback,\n    alt = '',\n    value,\n    defaultValue,\n    onValueChange,\n    onReject,\n    accept = 'image/*',\n    maxSize,\n    name,\n    disabled = false,\n    hint,\n    chooseLabel = 'Choose photo',\n    removeLabel = 'Remove',\n    messages,\n    className,\n    ...props\n  } = allProps;\n  const id = React.useId();\n  const input = React.useRef<HTMLInputElement>(null);\n  const [own, setOwn] = React.useState<File | null | undefined>(defaultValue);\n  // `value={undefined}` still means \"unchanged\", so the prop being passed is what makes it controlled.\n  const controlled = Object.hasOwn(allProps, 'value');\n  const current = controlled ? value : own;\n  const [dragging, setDragging] = React.useState(false);\n  const [status, setStatus] = React.useState('');\n  const say = { ...DEFAULT_MESSAGES, ...messages };\n  const preview = usePreview(current);\n  const shown = current === null ? undefined : (preview ?? (current ? undefined : src));\n  const hasPhoto = current === null ? false : Boolean(current) || Boolean(src);\n\n  const commit = (next: File | null) => {\n    if (!controlled) setOwn(next);\n    syncInput(input.current, next);\n    onValueChange?.(next);\n  };\n\n  const take = (file: File | undefined) => {\n    if (!file) return;\n    const { accepted, rejected } = checkFiles([file], { accept, maxSize });\n    if (accepted[0]) {\n      commit(accepted[0]);\n      setStatus('');\n      return;\n    }\n    const rejection = rejected[0]!;\n    setStatus(rejection.reason === 'type' ? say.type(file) : say.size(file, maxSize!));\n    syncInput(input.current, current);\n    onReject?.(rejection);\n  };\n\n  const hintId = hint ? `${id}-hint` : undefined;\n  const statusId = `${id}-status`;\n\n  return (\n    <div\n      data-slot=\"avatar-upload\"\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('flex items-center gap-4 [--avatar-upload-size:4.5rem]', className)}\n      {...props}\n    >\n      <div\n        data-slot=\"avatar-upload-photo\"\n        data-dragging={dragging ? '' : undefined}\n        onDragEnter={(event) => {\n          if (disabled) return;\n          event.preventDefault();\n          setDragging(true);\n        }}\n        onDragOver={(event) => {\n          if (disabled) return;\n          event.preventDefault();\n        }}\n        onDragLeave={(event) => {\n          if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;\n          setDragging(false);\n        }}\n        onDrop={(event) => {\n          if (disabled) return;\n          event.preventDefault();\n          setDragging(false);\n          take(event.dataTransfer.files[0]);\n        }}\n        className={cn(\n          'ring-border ring-offset-background shrink-0 rounded-full ring-1 ring-offset-2',\n          'transition-[box-shadow] duration-(--duration-fast) ease-enter',\n          'data-[dragging]:ring-primary data-[dragging]:ring-2',\n        )}\n      >\n        <Avatar className=\"size-(--avatar-upload-size)\">\n          {shown ? <AvatarImage src={shown} alt={alt} className=\"object-cover\" /> : null}\n          <AvatarFallback className=\"text-lg\">{fallback}</AvatarFallback>\n        </Avatar>\n      </div>\n\n      <div className=\"flex min-w-0 flex-col gap-1.5\">\n        <div data-slot=\"avatar-upload-actions\" className=\"flex flex-wrap items-center gap-2\">\n          <label\n            data-slot=\"avatar-upload-choose\"\n            data-disabled={disabled ? '' : undefined}\n            className={cn(\n              buttonVariants({ variant: 'outline', size: 'sm' }),\n              'relative cursor-pointer',\n              'has-[input:focus-visible]:ring-ring has-[input:focus-visible]:ring-offset-background has-[input:focus-visible]:ring-2 has-[input:focus-visible]:ring-offset-2',\n              'data-[disabled]:pointer-events-none data-[disabled]:opacity-50',\n            )}\n          >\n            <input\n              ref={input}\n              type=\"file\"\n              name={name}\n              accept={accept}\n              disabled={disabled}\n              aria-describedby={cn(hintId, status ? statusId : undefined) || undefined}\n              // Laid over the whole button, unseen, so the focus ring the button draws is the field's own.\n              className=\"absolute inset-0 size-full cursor-pointer opacity-0\"\n              onChange={(event) => take(event.currentTarget.files?.[0])}\n            />\n            {chooseLabel}\n          </label>\n          {hasPhoto ? (\n            <Button\n              type=\"button\"\n              variant=\"ghost\"\n              size=\"sm\"\n              data-slot=\"avatar-upload-remove\"\n              disabled={disabled}\n              onClick={() => {\n                commit(null);\n                setStatus('');\n                input.current?.focus();\n              }}\n            >\n              {removeLabel}\n            </Button>\n          ) : null}\n        </div>\n        {hint ? (\n          <p id={hintId} data-slot=\"avatar-upload-hint\" className=\"text-muted-foreground text-sm\">\n            {hint}\n          </p>\n        ) : null}\n        <p\n          id={statusId}\n          data-slot=\"avatar-upload-status\"\n          aria-live=\"polite\"\n          className={cn('text-destructive text-sm', !status && 'sr-only')}\n        >\n          {status}\n        </p>\n      </div>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "tier": "pattern",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.0.0",
    "since": null
  },
  "docs": "## @interlace/avatar-upload\n\nInstalled to `components/ui/patterns/avatar-upload.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/patterns/avatar-upload';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/avatar-upload\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
