# Product Editor

> The add and edit product page for a store admin. Handles unsaved changes, SKU errors from the server and someone else editing at once.

Canonical: https://hextaui.com/blocks/product-editor
Last updated: 2026-10-29

## Overview

Product Editor is the page a merchant uses to add or change a product: title and description, media, pricing with live profit and margin, stock per location, shipping, variants, a search result preview, and a rail for status, sales channels, type, vendor, collections and tags. It renders the page frame with breadcrumb, status badge, Preview and a menu for Duplicate, Archive and Delete, and leaves the sidebar to you.

Every edit goes into one draft. The save bar slides up when the draft differs from the saved product and goes away again if you undo your edits by hand, because the check is a deep compare. ⌘S saves, Discard asks first, and Preview or the breadcrumb nudge the bar instead of leaving. A second try within a few seconds asks whether to leave without saving. onSave can return field errors, which are shown on their fields while the first one scrolls into view and gets focus, or a conflict, which turns the bar into “Leo Park changed this product 2 min ago” with Review changes and Overwrite.

MediaUploader takes drops, pastes and the file picker. The first image is the large featured tile. You can drag tiles and the rest move out of the way as you go, or press Space, the arrow keys and Space again. Each upload shows its own progress. A failed one stays in place with Retry, unsupported types and files over the size limit are named in a message, and removed images come back with Undo.

VariantMatrix edits up to three options as value chips that you can reorder, rename and remove, and keeps one row for every combination. Rows are grouped by an option with a summary like “$48–$96 · 12 in stock”. You can set price or stock for a whole group or a selection, delete a combination and restore it with the same SKU, filter rows, and work through hundreds of variants because collapsed groups don’t render and long groups load 25 rows at a time.

## Installation

### Step 1: Get HextaUI Pro

One payment unlocks every block, including future ones. [See pricing](https://hextaui.com/pricing).

### Step 2: Add the Pro registry to components.json

```json title="components.json"
{
  "registries": {
    "@hextaui-pro": {
      "url": "https://hextaui.com/r/pro/{name}.json",
      "headers": {
        "Authorization": "Bearer ${HEXTAUI_PRO_TOKEN}"
      }
    }
  }
}
```

### Step 3: Add your token

Create a token on your [account page](https://hextaui.com/account) and put it in `.env.local` as `HEXTAUI_PRO_TOKEN`.

### Step 4: Add the block

```bash
npx shadcn@latest add @hextaui-pro/product-editor
```

## Usage

### Save with Shopify’s productSet

Map the draft to a ProductSetInput and send it in one mutation. userErrors come back as field errors, so a taken SKU lands on its variant row, and a 409 from your route becomes the concurrent edit state.

```tsx
"use client"

import { ProductEditor, type ProductEditorProps } from "@/components/blocks/product-editor/product-editor"
import type { ProductDraft } from "@/components/blocks/product-editor/product-draft"

const productSet = `
  mutation ProductSet($input: ProductSetInput!, $identifier: ProductSetIdentifiers) {
    productSet(input: $input, identifier: $identifier, synchronous: true) {
      product { id updatedAt }
      userErrors { field message code }
    }
  }
`

type UserError = { field: string[] | null; message: string; code: string | null }

function toProductSetInput(draft: ProductDraft) {
  return {
    title: draft.title,
    descriptionHtml: draft.description,
    handle: draft.handle,
    status: draft.status.toUpperCase(),
    productType: draft.productType,
    vendor: draft.vendor,
    tags: draft.tags,
    seo: { title: draft.seoTitle, description: draft.seoDescription },
    productOptions: draft.options.map((option, position) => ({
      name: option.name,
      position: position + 1,
      values: option.values.map((name) => ({ name })),
    })),
    variants: draft.variants.map((variant) => ({
      id: variant.id.startsWith("gid://") ? variant.id : undefined,
      sku: variant.sku,
      price: variant.price.amount,
      compareAtPrice: variant.compareAtPrice?.amount ?? null,
      optionValues: draft.options.map((option) => ({
        optionName: option.name,
        name: variant.selectedOptions[option.name],
      })),
      inventoryQuantities: Object.entries(variant.quantities).map(([locationId, quantity]) => ({
        locationId,
        name: "available",
        quantity,
      })),
    })),
  }
}

function fieldKey(draft: ProductDraft, error: UserError) {
  const [, , index, field] = error.field ?? []
  const variant = draft.variants[Number(index)]
  if (error.field?.[1] === "variants" && variant) return `variant:${variant.id}:${field === "price" ? "price" : "sku"}`
  return error.field?.[1] ?? "title"
}

const onSave: ProductEditorProps["onSave"] = async (draft, { overwrite }) => {
  const response = await fetch("/api/shopify/admin", {
    method: "POST",
    headers: { "Content-Type": "application/json", "If-Match": overwrite ? "*" : draft.id },
    body: JSON.stringify({ query: productSet, variables: { input: toProductSetInput(draft), identifier: { id: draft.id } } }),
  })
  if (response.status === 409) {
    const latest = (await response.json()) as { author: string; updatedAt: string; product: ProductDraft }
    return { conflict: { author: latest.author, at: latest.updatedAt, value: latest.product } }
  }
  if (!response.ok) throw new Error("Shopify didn’t answer. Try again.")
  const { data } = (await response.json()) as { data: { productSet: { userErrors: UserError[] } } }
  const errors = data.productSet.userErrors
  if (errors.length > 0) {
    return { errors: Object.fromEntries(errors.map((error) => [fieldKey(draft, error), error.message])) }
  }
}

export function ShopifyProductPage({ product }: { product: ProductDraft }) {
  return (
    <ProductEditor
      product={product}
      onSave={onSave}
      locations={[{ id: "gid://shopify/Location/1", name: "Brooklyn studio" }]}
      channels={[{ id: "online-store", name: "Online Store" }]}
      store={{ name: "Halden", domain: "halden.co" }}
    />
  )
}
```

### Save through the Medusa admin API

Update the product, then batch the variants. Throw with the API’s message and the save bar shows it with Try again. onNavigate hands guarded links to the Next.js router.

```tsx
"use client"

import { useRouter } from "next/navigation"

import { ProductEditor } from "@/components/blocks/product-editor/product-editor"
import type { ProductDraft } from "@/components/blocks/product-editor/product-draft"

async function medusa(path: string, body: unknown) {
  const response = await fetch(`${process.env.NEXT_PUBLIC_MEDUSA_URL}/admin${path}`, {
    method: "POST",
    credentials: "include",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  })
  const json = await response.json()
  if (!response.ok) throw new Error(json.message ?? "Medusa couldn’t save the product.")
  return json
}

export function MedusaProductPage({ product }: { product: ProductDraft }) {
  const router = useRouter()

  return (
    <ProductEditor
      product={product}
      locations={[{ id: "sloc_01", name: "Brooklyn studio" }]}
      channels={[{ id: "sc_01", name: "Webshop" }]}
      store={{ name: "Halden", domain: "halden.co" }}
      onNavigate={(href) => router.push(href)}
      onSave={async (draft) => {
        await medusa(`/products/${draft.id}`, {
          title: draft.title,
          description: draft.description,
          handle: draft.handle,
          status: draft.status === "active" ? "published" : draft.status === "draft" ? "draft" : "rejected",
          tags: draft.tags.map((value) => ({ value })),
          options: draft.options.map((option) => ({ title: option.name, values: option.values })),
        })
        await medusa(`/products/${draft.id}/variants/batch`, {
          update: draft.variants.map((variant) => ({
            id: variant.id,
            sku: variant.sku,
            options: variant.selectedOptions,
            prices: [{ currency_code: variant.price.currencyCode.toLowerCase(), amount: Number(variant.price.amount) }],
          })),
        })
      }}
    />
  )
}
```

### Upload media to S3 with presigned URLs

Ask your server for a presigned PUT URL, send the file with XMLHttpRequest so progress reaches each tile, and return the public URL. Aborting the signal cancels the request when a tile is removed.

```tsx
"use client"

import { MediaUploader, type MediaUploadContext } from "@/components/blocks/product-editor/media-uploader"
import type { MediaItem } from "@/components/blocks/product-editor/product-draft"

function put(url: string, file: File, { onProgress, signal }: MediaUploadContext) {
  return new Promise<void>((resolve, reject) => {
    const request = new XMLHttpRequest()
    request.open("PUT", url)
    request.setRequestHeader("Content-Type", file.type)
    request.upload.onprogress = (event) => event.lengthComputable && onProgress(event.loaded / event.total)
    request.onload = () => (request.status < 300 ? resolve() : reject(new Error(`Upload failed with ${request.status}.`)))
    request.onerror = () => reject(new Error("The connection dropped during the upload."))
    signal.addEventListener("abort", () => request.abort())
    request.send(file)
  })
}

async function uploadToS3(file: File, context: MediaUploadContext) {
  const response = await fetch("/api/uploads", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name: file.name, type: file.type, size: file.size }),
    signal: context.signal,
  })
  if (!response.ok) throw new Error("Couldn’t start the upload.")
  const { uploadUrl, publicUrl, key } = (await response.json()) as {
    uploadUrl: string
    publicUrl: string
    key: string
  }
  await put(uploadUrl, file, context)
  return { id: key, src: publicUrl }
}

export function ProductMedia({
  value,
  onValueChange,
}: {
  value: MediaItem[]
  onValueChange: (value: MediaItem[]) => void
}) {
  return (
    <MediaUploader
      value={value}
      onValueChange={onValueChange}
      onUpload={uploadToS3}
      maxSize={20 * 1024 * 1024}
    />
  )
}
```

## Anatomy

The parts you compose, from the outside in.

| Part | Description |
| --- | --- |
| `ProductEditor` | The page: header, main column of cards, right rail, save bar and dialogs. |
| `DraftSaveBar` | The floating bar for unsaved changes, save progress, errors and conflicts. |
| `useDraft` | Saved value, draft, deep dirty check, validation, save, discard and conflict state. |
| `MediaUploader` | Drop zone and sortable image grid with uploads and alt text. |
| `VariantMatrix` | Options editor and the grouped variant table. |
| `SeoPreview` | A search result snippet with title, description and URL fields. |
| `TagsInput` | Free-form tags as removable chips. |
| `product-draft helpers` | ProductDraft types, combination helpers, validateProduct, getProfit and describeProductChanges. |

## API reference

### ProductEditor

Also takes div props.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `product` | `ProductDraft` | – | The saved product. A new value replaces the draft when there are no unsaved changes. |
| `onSave` | `(draft, { overwrite, redirectFrom }) => void \| { errors?, conflict?, value? } \| Promise<…>` | – | Save the draft. Return errors keyed by field, such as sku or variant:ID:sku, a conflict, or the saved value. Throw to show the message in the save bar. |
| `conflict` | `{ author; at; value?; changes? } \| null` | – | Someone else’s newer version, for example from a live subscription. Without changes, the review dialog works them out from value. |
| `onUpload` | `(file, { onProgress, signal }) => Promise<{ src; id? }>` | – | Upload one image. Without it, images stay as local previews. |
| `locations` | `{ id; name; description? }[]` | – | Stock locations for quantities. |
| `channels` | `{ id; name; description? }[]` | – | Sales channels shown as checkboxes. |
| `collections` | `string[]` | – | Collections to choose from. |
| `store` | `{ name; domain }` | – | Used in the search preview and URL field. |
| `backHref` | `string` | `"/products"` | The breadcrumb link. |
| `onNavigate` | `(href: string) => void` | – | Called for the breadcrumb once it’s safe to leave. |
| `onPreview, onDuplicate, onArchive, onDelete` | `() => void \| Promise<void>` | – | Header actions. Preview and Duplicate are guarded by unsaved changes. Without onArchive, Archive sets the status in the draft. |
| `onDirtyChange` | `(dirty: boolean) => void` | – | Called when the draft becomes dirty or clean, for router blockers. |
| `onConflictResolve` | `(resolution: "theirs" \| "overwrite") => void` | – | Called when the merchant keeps their colleague’s version or overwrites it. |
| `locale` | `Intl.LocalesArgument` | `"en-US"` | Locale for money, numbers and relative times. |
| `saveBarLabels` | `Partial<SaveBarLabels>` | – | Words in the save bar. |

### MediaUploader

Also takes div props.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `MediaItem[]` | – | Images in order. The first is featured. |
| `onValueChange` | `(value: MediaItem[]) => void` | – | Called after a reorder, upload, alt text change or removal. |
| `onUpload` | `(file, { onProgress, signal }) => Promise<{ src; id?; width?; height? }>` | – | Upload a file and report progress from 0 to 1. Throw to fail the tile with your message. |
| `onUploadingChange` | `(count: number) => void` | – | How many uploads are running. |
| `accept` | `string[]` | `JPG, PNG, WebP, GIF, AVIF` | Accepted MIME types. |
| `maxSize` | `number` | `20 MB` | Largest file in bytes. |
| `maxFiles` | `number` | `250` | Most images in total. |
| `labels` | `Partial<MediaUploaderLabels>` | – | Words for tiles, errors and announcements. |

### VariantMatrix

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `{ options; variants; price; compareAtPrice; sku; barcode; quantities }` | – | The draft, or any object with these fields. |
| `onValueChange` | `(value) => void` | – | Called with the whole updated value. |
| `locations` | `InventoryLocation[]` | – | Locations for the stock column. |
| `media` | `MediaItem[]` | – | Images for variant thumbnails. |
| `trackQuantity` | `boolean` | `true` | Shows the stock column and summaries. |
| `errors` | `Record<string, string>` | – | Errors keyed variant:ID:price or variant:ID:sku. Groups holding them open. |
| `pageSize` | `number` | `25` | Rows shown per group before Show more. |

### useDraft

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `Value` | – | The saved value. |
| `onSave` | `(value, { overwrite }) => DraftSaveResult` | – | Save and return errors, a conflict or the saved value. |
| `validate` | `(value) => Record<string, string>` | – | Errors found before saving. |
| `normalize` | `(value) => Value` | – | Clean the draft before it is validated and saved. |
| `conflict` | `DraftConflict \| null` | – | An outside conflict to show. |

## Keyboard

| Key | Action |
| --- | --- |
| `Meta` `S` | Saves the product when there are unsaved changes. Ctrl+S on Windows and Linux. |
| `Space` | On an image or option value, picks it up or drops it. |
| `ArrowLeft` `ArrowRight` `ArrowUp` `ArrowDown` | Moves a picked-up image or value one place. |
| `Home` `End` | Moves a picked-up image or value to the start or end. |
| `Escape` | Cancels a move and puts the item back. |
| `Enter` | On an option value, renames it. In the add value field, adds the value and its variants. |
| `Backspace` | On an option value or tag, removes it. In an empty add field, moves to the last chip. |
| `Meta` `B` | In the description, wraps the selection in bold. Meta+I does italic. |

## Accessibility

- The save bar is a region named Unsaved changes. A polite live region says its state once, focus is never moved when it appears, and save failures are sent to an alert region.
- Images and option values are sortable buttons with instructions linked through aria-describedby. Pick up, every move, drop and cancel are announced, such as “Image “Ash vase” moved to position 2 of 7.”
- Server errors set aria-invalid on the field, show the message next to it and move focus to the first one. Upload problems and rejected files are announced and named in words, never only by color.
- The variant table uses table, row and cell roles with labelled checkboxes and inputs, such as “Price, Sand / Small”. Group toggles set aria-expanded, and motion falls back to fades or nothing under reduced motion.

## Built with

The free HextaUI components Product Editor is made from. Each one installs on its own.

- [Alert dialog](https://hextaui.com/docs/alert-dialog) - A confirmation dialog for destructive or important actions that waits for async work, and becomes a bottom sheet on phones.
- [Badge](https://hextaui.com/docs/badge) - Status labels with colored dots, removable tags that slide closed and counts that roll to their new value.
- [Breadcrumb](https://hextaui.com/docs/breadcrumb) - A trail of links to the current page that wraps safely, mirrors in right-to-left layouts and expands collapsed segments in place.
- [Button](https://hextaui.com/docs/button) - Buttons in every variant and size, with a built-in loading, success and error flow that skips the spinner for fast requests.
- [Card](https://hextaui.com/docs/card) - A surface for grouping content, with three variants, edge-to-edge media, concentric radii and whole-card links.
- [Checkbox](https://hextaui.com/docs/checkbox) - A checkbox whose check draws in, with indeterminate parents, groups and labels that share its hover.
- [Collapsible](https://hextaui.com/docs/collapsible) - A panel that shows and hides with height motion you can reverse mid-way, without jumping the layout.
- [Combobox](https://hextaui.com/docs/combobox) - A filterable select with chips, groups and async results, in a popup that resizes as you type.
- [Dialog](https://hextaui.com/docs/dialog) - A window over the page for forms and focused tasks, with a pinned header and footer, nesting, and a swipeable bottom sheet on phones.
- [Dropdown menu](https://hextaui.com/docs/dropdown-menu) - A menu of actions and options behind a button, with groups, submenus, checkbox and radio items, and shortcuts.
- [Field](https://hextaui.com/docs/field) - Labels, descriptions and errors wired to their control, with validation states and layouts for forms.
- [Input](https://hextaui.com/docs/input) - A text input with three sizes, invalid and read-only states, native validation styling and a 16px touch font so phones never zoom in.
- [Input group](https://hextaui.com/docs/input-group) - An input with icons, text, buttons or a keyboard hint attached, sharing one border and focus ring.
- [Number flow](https://hextaui.com/docs/number-flow) - Animated numbers where only the changed digits spin, with any Intl format and locale.
- [Popover](https://hextaui.com/docs/popover) - A floating panel anchored to a trigger that resizes smoothly with its content and follows the trigger’s direction.
- [Progress](https://hextaui.com/docs/progress) - A bar or ring that shows how far a task has come, eases between updates and slides while the total is unknown.
- [Select](https://hextaui.com/docs/select) - Pick one or more options from a list that opens on the current value, with typeahead, groups and form support.
- [Switch](https://hextaui.com/docs/switch) - An on/off toggle you can tap, press or drag, with a thumb that stretches under your finger and an optional pending state for saves.
- [Textarea](https://hextaui.com/docs/textarea) - Multi-line text that grows smoothly with what you write between a minimum and maximum number of rows, with counters, validation and a submit shortcut.
- [Toast](https://hextaui.com/docs/toast) - Brief messages that stack neatly, expand on hover, swipe away, and turn a loading state into success or error in place.

## Code

13 files, added to components/blocks/product-editor.
