# Avatar upload

> Select a real profile image, preview and crop it locally, then submit the prepared PNG through a native file input.

- Kind: ui · Category: Forms · Interactivity: script
- Install: `npx shadcn@latest add @haze/avatar-upload`
- File: `src/components/haze/ui/avatar-upload.astro`
- npm dependencies: none
- Registry dependencies: @haze/slider, @haze/utils
- Docs page: https://hazeui.com/ui/avatar-upload

## Use when
- A profile form needs a local image preview and a square crop before submission.
- Zoom and crop position should have native keyboard accessible controls.

## Avoid when
- Use file-upload when multiple files or nonimage attachments are accepted.
- Use avatar when the photo is display only.

## Alternatives
- [file-upload](https://hazeui.com/ui/file-upload.md)
- [avatar](https://hazeui.com/ui/avatar.md)
- [slider](https://hazeui.com/ui/slider.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique caller supplied prefix for the control and its associated content. |
| name | `string` | id | no | Name submitted by the native form control. |
| label | `string` | Profile photo | no | Legend for the photo field and crop controls. |
| initials | `string` | ML | no | Fallback initials shown without an image. |
| src | `string` |  | no | Optional previously saved photo to show before selecting a new file. |
| maxBytes | `number` | 5242880 | no | Maximum accepted local file size. |
| disabled | `boolean` | false | no | Prevents user changes through the native disabled state. |
| required | `boolean` | false | no | Requires a new file through native form validation. |
| class | `string` |  | no | Additional classes on this component's outer wrapper. |
| [key: string] | `unknown` |  | no | Additional native file input attributes. |

## Accessibility
- A labelled native file input remains visible and accepts PNG, JPEG and WebP; the preview image is decorative.
- Zoom plus horizontal and vertical crop positions are native range inputs, so cropping has a complete keyboard path.
- Type and size errors are reported in text and through native validity; no upload or progress is simulated.
- Applying the crop prepares a 256 pixel PNG file in the file input and emits haze:avatar-change; submission and persistence belong to the caller's form.
- Replacement, cancellation, reset and Astro page swaps revoke temporary object URLs. If the browser cannot replace the selected file, the original remains selected and the limitation is stated.
- Key Enter / Space on the file input: Open the operating system file chooser.
- Key Arrow keys on crop controls: Adjust zoom or crop position.
- Key Tab, Enter / Space: Apply, cancel or remove the photo.

## Agent prompts

### Install and use

Install the Haze UI component "Avatar upload" with `npx shadcn@latest add @haze/avatar-upload`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import AvatarUpload from "@/components/haze/ui/avatar-upload.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/avatar-upload.md

### Customize with real content

Adapt the Haze avatar-upload ui for our product. Replace the demo values of these props with our real content: id, name, label, initials, src, maxBytes, disabled, required, class, [key: string]. Keep the layout, the heading level rules and these accessibility details: A labelled native file input remains visible and accepts PNG, JPEG and WebP; the preview image is decorative. Zoom plus horizontal and vertical crop positions are native range inputs, so cropping has a complete keyboard path. Type and size errors are reported in text and through native validity; no upload or progress is simulated. Applying the crop prepares a 256 pixel PNG file in the file input and emits haze:avatar-change; submission and persistence belong to the caller's form. Replacement, cancellation, reset and Astro page swaps revoke temporary object URLs. If the browser cannot replace the selected file, the original remains selected and the limitation is stated. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using avatar-upload, check it fits: use it when a profile form needs a local image preview and a square crop before submission.; zoom and crop position should have native keyboard accessible controls.. Avoid it when use file-upload when multiple files or nonimage attachments are accepted.; use avatar when the photo is display only.. Alternatives: @haze/file-upload, @haze/avatar, @haze/slider.

## Example requests that should lead here
- Add a profile photo input with local zoom and crop position controls
- Prepare a square avatar PNG before submitting the profile form

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";
import Slider from "./slider.astro";

interface Props {
  id: string;
  name?: string;
  label?: string;
  initials?: string;
  src?: string;
  maxBytes?: number;
  disabled?: boolean;
  required?: boolean;
  class?: string;
  [key: string]: unknown;
}
const { id, name = id, label = "Profile photo", initials = "ML", src, maxBytes = 5 * 1024 * 1024, disabled, required, class: className, ...rest } = Astro.props;
const limit = Number.isFinite(maxBytes) && maxBytes > 0 ? maxBytes : 5 * 1024 * 1024;
const button = "min-h-8 cursor-pointer rounded-lg border border-frame bg-field px-3 text-[0.8125rem]/5 font-medium text-foreground shadow-key transition-[background-color,scale] duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-75 motion-reduce:transition-none motion-reduce:active:scale-100 disabled:cursor-not-allowed disabled:opacity-50";
---
<fieldset data-haze-avatar-upload data-max-bytes={limit} data-initial-src={src} disabled={disabled} class={cn("grid w-full min-w-0 gap-3", className)}>
  <legend class="mb-3 text-[0.8125rem]/5 font-medium text-foreground">{label}</legend>
  <div class="flex flex-wrap items-center gap-4">
    <div data-avatar-preview aria-hidden="true" class="relative grid size-24 shrink-0 place-items-center overflow-hidden rounded-full border border-frame bg-muted text-lg/7 font-medium text-muted-foreground transition-[width,height] duration-200 ease-snappy data-[editing]:size-40">
      <span data-avatar-initials hidden={!!src}>{initials}</span>
      <img data-avatar-image src={src} alt="" width="256" height="256" hidden={!src} class="absolute inset-0 size-full max-w-none object-cover" />
    </div>
    <p id={`${id}-hint`} class="min-w-0 flex-1 basis-24 text-xs text-muted-foreground">PNG, JPEG or WebP. Up to {Math.round(limit / 1024 / 1024 * 10) / 10} MB. Images are prepared locally.</p>
  </div>
  <div class="grid min-w-0 gap-2"><label for={id} class="text-[0.8125rem]/5 font-medium text-foreground">Choose a photo</label><input id={id} name={name} type="file" accept="image/png,image/jpeg,image/webp" required={required} aria-describedby={`${id}-hint ${id}-status`} class="peer sr-only" {...rest} /><label for={id} aria-hidden="true" class="flex h-10 min-w-0 w-full cursor-pointer items-center gap-2 rounded-lg border border-frame-input bg-field p-1 text-[0.8125rem]/5 text-muted-foreground peer-focus-visible:outline-2 peer-focus-visible:outline-offset-1 peer-focus-visible:outline-ring peer-disabled:cursor-not-allowed peer-disabled:opacity-50"><span class="inline-flex h-8 shrink-0 items-center rounded-sm border border-frame bg-field px-2 font-medium text-foreground">Choose file</span><span data-avatar-filename class="min-w-0 truncate">No file chosen</span></label></div>
  <div data-avatar-crop hidden class="grid min-w-0 gap-3 rounded-xl border border-border bg-card p-3">
    <div class="grid gap-1"><label for={`${id}-zoom`} class="text-[0.8125rem]/5 font-medium text-foreground">Zoom</label><Slider id={`${id}-zoom`} name={`${name}-zoom`} min={1} max={3} step={0.05} value={1} data-avatar-zoom /></div>
    <div class="grid gap-1"><label for={`${id}-horizontal`} class="text-[0.8125rem]/5 font-medium text-foreground">Horizontal position</label><Slider id={`${id}-horizontal`} name={`${name}-horizontal`} min={0} max={100} value={50} data-avatar-horizontal /></div>
    <div class="grid gap-1"><label for={`${id}-vertical`} class="text-[0.8125rem]/5 font-medium text-foreground">Vertical position</label><Slider id={`${id}-vertical`} name={`${name}-vertical`} min={0} max={100} value={50} data-avatar-vertical /></div>
    <div class="flex flex-wrap gap-2"><button type="button" data-avatar-apply class={button}>Apply crop</button><button type="button" data-avatar-cancel class={button}>Cancel</button></div>
  </div>
  <button type="button" data-avatar-remove hidden class={cn(button, "justify-self-start")}>Remove photo</button>
  <p id={`${id}-status`} data-avatar-status role="status" class="text-xs text-muted-foreground">Submit your form to upload the selected file.</p>
</fieldset>
<script>
  function enhance(root: HTMLFieldSetElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const input = root.querySelector<HTMLInputElement>("input[type=file]");
    const image = root.querySelector<HTMLImageElement>("[data-avatar-image]");
    const initials = root.querySelector<HTMLElement>("[data-avatar-initials]");
    const preview = root.querySelector<HTMLElement>("[data-avatar-preview]");
    const crop = root.querySelector<HTMLElement>("[data-avatar-crop]");
    const status = root.querySelector<HTMLElement>("[data-avatar-status]");
    const remove = root.querySelector<HTMLButtonElement>("[data-avatar-remove]");
    const zoom = root.querySelector<HTMLInputElement>("[data-avatar-zoom]");
    const horizontal = root.querySelector<HTMLInputElement>("[data-avatar-horizontal]");
    const vertical = root.querySelector<HTMLInputElement>("[data-avatar-vertical]");
    if (!input || !image || !initials || !preview || !crop || !status || !remove || !zoom || !horizontal || !vertical) return;
    let objectUrl: string | null = null;
    let original: File | null = null;
    let revision = 0;
    const release = () => { if (objectUrl) URL.revokeObjectURL(objectUrl); objectUrl = null; };
    const showInitial = () => {
      release(); original = null; image.onload = null; image.onerror = null; crop.hidden = true; preview.removeAttribute("data-editing");
      image.removeAttribute("style"); image.classList.add("object-cover");
      const src = root.dataset.initialSrc; image.hidden = !src; initials.hidden = !!src;
      if (src) image.src = src; else image.removeAttribute("src");
      remove.hidden = !src;
    };
    const render = () => {
      if (!original || !image.naturalWidth || !image.naturalHeight) return;
      const ratio = image.naturalWidth / image.naturalHeight;
      const width = Math.max(1, ratio) * zoom.valueAsNumber;
      const height = Math.max(1, 1 / ratio) * zoom.valueAsNumber;
      image.style.width = `${width * 100}%`; image.style.height = `${height * 100}%`;
      image.style.left = `${(1 - width) * horizontal.valueAsNumber}%`; image.style.top = `${(1 - height) * vertical.valueAsNumber}%`;
      zoom.setAttribute("aria-valuetext", `${Math.round(zoom.valueAsNumber * 100)} percent`);
    };
    [zoom, horizontal, vertical].forEach((control) => control.addEventListener("input", render));
    const fileName = root.querySelector<HTMLElement>("[data-avatar-filename]");
    const syncName = () => { if (fileName) fileName.textContent = input.files?.[0]?.name ?? "No file chosen"; };
    input.addEventListener("change", () => {
      syncName();
      const file = input.files?.[0]; const token = ++revision;
      input.setCustomValidity("");
      if (!file) { showInitial(); status.textContent = "No new photo selected."; return; }
      if (!["image/png", "image/jpeg", "image/webp"].includes(file.type) || file.size > Number(root.dataset.maxBytes)) {
        showInitial(); input.value = ""; input.setCustomValidity("Choose a PNG, JPEG or WebP image within the size limit."); status.textContent = input.validationMessage; input.reportValidity(); return;
      }
      release(); original = file; objectUrl = URL.createObjectURL(file);
      image.onload = () => {
        if (token !== revision) return;
        zoom.value = "1"; horizontal.value = "50"; vertical.value = "50";
        [zoom, horizontal, vertical].forEach((control) => control.dispatchEvent(new Event("input", { bubbles: true })));
        image.hidden = false; initials.hidden = true; crop.hidden = false; preview.setAttribute("data-editing", ""); remove.hidden = false;
        render(); status.textContent = "Adjust the crop, then apply it. The photo stays on this device until you submit.";
      };
      image.onerror = () => { if (token !== revision) return; showInitial(); input.value = ""; status.textContent = "This image could not be read. Choose another file."; };
      image.src = objectUrl;
    });
    root.querySelector<HTMLButtonElement>("[data-avatar-apply]")!.addEventListener("click", () => {
      if (!original || !image.complete || root.disabled) return;
      const canvas = document.createElement("canvas"); canvas.width = canvas.height = 256;
      const context = canvas.getContext("2d"); if (!context) return;
      const scale = Math.max(256 / image.naturalWidth, 256 / image.naturalHeight) * zoom.valueAsNumber;
      const width = image.naturalWidth * scale, height = image.naturalHeight * scale;
      context.drawImage(image, (256 - width) * horizontal.valueAsNumber / 100, (256 - height) * vertical.valueAsNumber / 100, width, height);
      const token = ++revision;
      canvas.toBlob((blob) => {
        if (!blob || token !== revision) return;
        const file = new File([blob], `${original?.name.replace(/\.[^.]+$/, "") || "avatar"}.png`, { type: "image/png" });
        try { const transfer = new DataTransfer(); transfer.items.add(file); input.files = transfer.files; }
        catch { status.textContent = "This browser cannot replace the file with its crop. The original image is still selected."; return; }
        release(); objectUrl = URL.createObjectURL(blob); original = null; image.onload = null; image.onerror = null; image.src = objectUrl; image.removeAttribute("style");
        crop.hidden = true; preview.removeAttribute("data-editing");
        status.textContent = "Cropped photo ready. Submit your form to upload it.";
        root.dispatchEvent(new CustomEvent("haze:avatar-change", { bubbles: true, detail: { file } })); syncName(); input.focus();
      }, "image/png");
    });
    root.querySelector<HTMLButtonElement>("[data-avatar-cancel]")!.addEventListener("click", () => { revision++; input.value = ""; showInitial(); status.textContent = "Photo change canceled."; syncName(); input.focus(); });
    remove.addEventListener("click", () => {
      revision++; input.value = ""; input.setCustomValidity(""); release(); original = null; crop.hidden = true; preview.removeAttribute("data-editing"); image.hidden = true; image.removeAttribute("src"); initials.hidden = false; remove.hidden = true;
      status.textContent = "Photo removed from this form."; root.dispatchEvent(new CustomEvent("haze:avatar-remove", { bubbles: true })); syncName(); input.focus();
    });
    root.form?.addEventListener("reset", () => queueMicrotask(() => { revision++; input.setCustomValidity(""); syncName(); showInitial(); status.textContent = "Photo selection reset."; }));
    root.setAttribute("data-enhanced", ""); remove.hidden = !root.dataset.initialSrc;
    root.addEventListener("haze:dispose", release);
  }
  const init = () => document.querySelectorAll<HTMLFieldSetElement>("[data-haze-avatar-upload]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-avatar-upload-listener")) {
    document.documentElement.setAttribute("data-haze-avatar-upload-listener", "");
    document.addEventListener("astro:page-load", init);
    document.addEventListener("astro:before-swap", () => document.querySelectorAll("[data-haze-avatar-upload]").forEach((root) => root.dispatchEvent(new Event("haze:dispose"))));
  }
</script>
```
