# Logo upload

> Choose or drop a PNG, JPEG or WebP and get back a small data URI. The image is checked, shrunk and re-encoded in the browser to fit a size limit.

Source: https://platform.azmara.io/docs/components/logo-upload

Group: Inputs · Status: new · Added in @azmr/ui 0.14.0

## Usage

```tsx
import { LogoUpload } from "@azmr/ui/logo-upload";
```

```tsx
"use client";

import { Field } from "@azmr/ui/field";
import { LogoUpload } from "@azmr/ui/logo-upload";
import { useState } from "react";

const LIMIT = 32_768;

export default function LogoUploadDemo() {
  const [logo, setLogo] = useState<string | undefined>();
  return (
    <div className="flex w-full max-w-md flex-col gap-4">
      <Field
        label="Company logo"
        description="PNG, JPEG or WebP. It is shrunk in your browser to fit."
      >
        {(control) => <LogoUpload {...control} value={logo} onValueChange={setLogo} />}
      </Field>
      <p className="text-sm text-muted-foreground">
        Harbour &amp; Pine logo:{" "}
        {logo
          ? `${logo.length.toLocaleString()} of ${LIMIT.toLocaleString()} characters`
          : "none yet"}
      </p>
    </div>
  );
}
```

`LogoUpload` lets someone choose a file or drop one on the box, shows a preview, and lets them replace or remove it. It returns a string through `onValueChange`: a `data:` URI of a small image. It does not save anything. Storing the string, and showing it later, is your app's job.

Put it in a [Field](https://platform.azmara.io/docs/components/field.md) with a function child, so the label, description and error are joined to it:

```tsx
<Field label="Company logo" error={errors.logo}>
  {(control) => <LogoUpload {...control} value={logo} onValueChange={setLogo} />}
</Field>
```

Use `value` and `onValueChange` for a controlled upload, or `defaultValue` to let the component keep the value itself. Passing `value` at all makes it controlled, even as `undefined` or `null`, so state that starts empty (`useState<string>()`) can be passed straight back. `onValueChange(undefined)` means the logo was removed. Add `name` to carry the value in a native form post through a hidden input.

## What it does to the file

Most logo exports and every phone photo are far bigger than a theme, a profile or an API field can hold. The component does the shrinking, so the person never has to:

1. It reads the file's first bytes to see what it is. The extension and the type the browser reports are never trusted, so a `logo.png` that is really something else is refused.
2. It refuses a file over 10 MB before reading it. It reads the image's own header, and refuses one that says it is over 40 million pixels before decoding it, so a tiny file that describes a huge picture costs nothing. It then decodes the image to prove it is one, and checks the decoded size too, for a file whose header could not be read.
3. It draws the image onto a canvas and re-encodes it as WebP (or PNG, in a browser that cannot encode WebP), trying a longest side of 512, then 384, 256, 192, 128, 96 and 64 pixels, and four qualities at each size, until the result fits `maxChars`. Transparency is kept and a small image is never made bigger.

If nothing fits, the component says so and keeps the logo the person already had. It never fetches a URL to read or upload an image. (A value you pass in that is an `https:` URL is shown in the preview, which makes the browser load it.)

**SVG is refused.** An SVG can carry script, so it is never read, drawn or stored. Ask for a PNG, JPEG or WebP; if a logo must be SVG, your app should render it from its own files.

`maxChars` is the most characters the data URI may have. It defaults to 32,768, the limit the `@azmr/ui` theme accepts for an image. Set it to your own storage limit.

## Errors

A refused file shows its message under the controls, in an alert, and calls `onError` with a code. The code is the stable part; change the words with `errors`.

| Code                  | Default message                                                         |
| --------------------- | ----------------------------------------------------------------------- |
| `not-an-image`        | That file is not a PNG, JPEG or WebP image.                             |
| `svg`                 | SVG logos cannot be used here. Export your logo as a PNG, JPEG or WebP. |
| `file-too-large`      | That file is larger than 10 MB. Choose a smaller image.                 |
| `too-many-pixels`     | That image is too large to open. Choose a smaller one.                  |
| `cannot-fit`          | This logo cannot be made small enough. Try a simpler image.             |
| `unsupported-browser` | This browser cannot prepare images. Try a current browser.              |

The error clears, and `onError(undefined)` is called, when a later file works or the logo is removed.

`onBusyChange(true)` is called when a file starts being prepared and `onBusyChange(false)` when the latest choice is done (fitted, refused or failed) the logo is removed, or the control leaves the page mid-preparation. A file that finishes after `disabled` turned on is dropped, never applied. Use it to keep a Save button off until the logo is ready.

## With react-hook-form

```tsx
<FormField
  name="logo"
  label="Company logo"
  render={({ value, onChange, control }) => (
    <LogoUpload {...control} value={value} onValueChange={onChange} />
  )}
/>
```

## Using the shrinking on its own

`shrinkImage(file, maxChars)` is exported for a custom control. It returns `{ dataUri, width, height }` or throws a `ShrinkError` with the same codes. It needs a browser, so call it from an event handler, not while rendering.

## When not to use it

For photos, anything that needs cropping, or a file that must be kept at full quality, upload the original to your own storage. This control is for small images that are stored inline, such as a brand logo.

## Props

| Prop                | Type                                                          | Default                    | Required | Description                                                                                                                                                                                                                                                                                                                                                                                                               |
| ------------------- | ------------------------------------------------------------- | -------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `value`             | `string \| null \| undefined`                                 |                            | No       | The logo, for a controlled upload: a `data:` image or an `https:` URL. `null`, `undefined` or `""` means none. Passing the prop at all, even as `undefined`, makes the upload controlled, so a parent that starts empty and passes its state back works. Leave it out to let the component keep the value itself.                                                                                                         |
| `defaultValue`      | `string`                                                      |                            | No       | The logo an uncontrolled upload starts with.                                                                                                                                                                                                                                                                                                                                                                              |
| `onValueChange`     | `((value: string \| undefined) => void) \| undefined`         |                            | No       | Called with the new data URI after a good upload, and with `undefined` after Remove.                                                                                                                                                                                                                                                                                                                                      |
| `onError`           | `((code: ShrinkErrorCode \| undefined) => void) \| undefined` |                            | No       | Called with a code when a file is refused, and with `undefined` when a later file or Remove clears the error. The component also shows the matching text, so this is for your own records or form state.                                                                                                                                                                                                                  |
| `onBusyChange`      | `((busy: boolean) => void) \| undefined`                      |                            | No       | Called with `true` when a chosen file starts being prepared and with `false` once the latest choice has finished (fitted, refused or failed), Remove was pressed, or the control was removed from the page mid-preparation. A file that a newer choice replaced does not report `false`. A file that finishes after `disabled` turned on is dropped. Use it to keep a Save button off while a logo is still being shrunk. |
| `maxChars`          | `number`                                                      | `32768`                    | No       | The most characters the finished data URI may have. Set it to your storage limit.                                                                                                                                                                                                                                                                                                                                         |
| `name`              | `string`                                                      |                            | No       | Adds a hidden input with this name that carries the value, for a native form post.                                                                                                                                                                                                                                                                                                                                        |
| `disabled`          | `boolean \| undefined`                                        |                            | No       |                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `id`                | `string`                                                      |                            | No       | On the choose button, so a `Field` label points at it.                                                                                                                                                                                                                                                                                                                                                                    |
| `className`         | `string`                                                      |                            | No       |                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `aria-labelledby`   | `string`                                                      |                            | No       |                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `aria-describedby`  | `string`                                                      |                            | No       |                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `aria-invalid`      | `boolean \| undefined`                                        |                            | No       |                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `aria-required`     | `boolean \| undefined`                                        |                            | No       | Marks the logo as required. A button cannot take `aria-required`, so it is not put on the button; `requiredLabel` is read as part of its description instead.                                                                                                                                                                                                                                                             |
| `aria-errormessage` | `string`                                                      |                            | No       |                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `chooseLabel`       | `string`                                                      | `"Choose a logo"`          | No       |                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `replaceLabel`      | `string`                                                      | `"Replace logo"`           | No       |                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `removeLabel`       | `string`                                                      | `"Remove logo"`            | No       |                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `dropLabel`         | `string`                                                      | `"or drop an image here"`  | No       |                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `previewAlt`        | `string`                                                      | `"Logo preview"`           | No       |                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `busyLabel`         | `string`                                                      | `"Preparing your logo..."` | No       |                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `readyLabel`        | `string`                                                      | `"Logo ready"`             | No       |                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `requiredLabel`     | `string`                                                      | `"Required"`               | No       | Read after the button's name when `aria-required` is set.                                                                                                                                                                                                                                                                                                                                                                 |
| `errors`            | `Partial<Record<ShrinkErrorCode, string>>`                    |                            | No       | Text for each refusal. Anything you leave out uses the default.                                                                                                                                                                                                                                                                                                                                                           |

`id` and the `aria-*` props go on the choose button, which is why a `Field` function child can spread its `control` props straight in. `ref` is that button too.

## Accessibility

- Choosing a file is a real button. Dropping is an extra, never the only way, so the control works with a keyboard, a screen reader and a switch.
- The preview has text alternative `previewAlt`. Change it to name the logo, such as "Harbour & Pine logo".
- Progress and success are read politely ("Preparing your logo...", "Logo ready"). A refusal is read as an alert and is part of the button's description.
- After Remove, focus moves to the choose button, so it is not lost.
- A button cannot take `aria-required`, so a required logo is said in the button's description: the words in `requiredLabel`, "Required" by default.
- Disabled turns off every button, the file chooser and dropping.

| Key     | Action                                                            |
| ------- | ----------------------------------------------------------------- |
| `Tab`   | Moves focus to the choose or replace button, then to Remove logo. |
| `Enter` | On the choose or replace button, opens the file chooser.          |
| `Space` | On the choose or replace button, opens the file chooser.          |
