Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Consolidate uploads into one universal FileUploadField

Damian Legawiec2aa20f56397a
diff --git a/packages/dashboard-core/src/components/file-upload-field.tsx b/packages/dashboard-core/src/components/file-upload-field.tsx
new file mode 100644
index 0000000000..cf07234d6a
--- /dev/null
+++ b/packages/dashboard-core/src/components/file-upload-field.tsx
@@ -0,0 +1,239 @@
+import {
+ Attachment,
+ AttachmentAction,
+ AttachmentActions,
+ AttachmentContent,
+ AttachmentDescription,
+ AttachmentMedia,
+ AttachmentTitle,
+ cn,
+ Field,
+ FieldDescription,
+ FieldLabel,
+} from '@spree/dashboard-ui'
+import { FileIcon, UploadCloudIcon, XIcon } from 'lucide-react'
+import { type ReactNode, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+import { useDirectUpload } from '../hooks/use-direct-upload'
+
+/**
+ * Controlled upload state. A field is in exactly one of three states:
+ * - untouched: `signedId == null && !cleared` → caller omits it on save
+ * - uploaded: `signedId` set → caller sends the signed_id
+ * - cleared: `cleared == true` → caller sends null to purge
+ *
+ * `previewUrl` is a transient object URL for the just-picked file (image
+ * uploads); `filename`/`byteSize` describe the picked file for display.
+ */
+export interface FileUploadValue {
+ signedId: string | null
+ previewUrl: string | null
+ cleared: boolean
+ filename?: string | null
+ byteSize?: number | null
+}
+
+export const EMPTY_FILE_UPLOAD_VALUE: FileUploadValue = {
+ signedId: null,
+ previewUrl: null,
+ cleared: false,
+}
+
+export function formatFileSize(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
+}
+
+export interface FileUploadFieldProps {
+ /** Current upload state. */
+ value: FileUploadValue
+ onChange: (value: FileUploadValue) => void
+ /** Accepted file types (input `accept` attribute). */
+ accept: string
+ /** `image` renders a thumbnail preview; `file` renders a type icon. */
+ variant?: 'image' | 'file'
+ /** Icon shown in the attachment media for the `file` variant. */
+ icon?: ReactNode
+ /** URL of the already-persisted attachment, shown until replaced/removed. */
+ serverUrl?: string | null
+ /** Display name for the persisted attachment (file variant). */
+ serverFilename?: string | null
+ label?: string
+ /** Helper text under the dropzone. */
+ help?: string
+ /** Copy inside the dropzone. Defaults to the generic "drop a file" string. */
+ dropLabel?: string
+ /** Copy on the browse chip inside the dropzone. */
+ browseLabel?: string
+ /** Extra classes for the attachment media (e.g. a larger logo preview). */
+ mediaClassName?: string
+ disabled?: boolean
+ /** Re-wrap the picked file before upload (e.g. force a content type). */
+ transformFile?: (file: File) => File
+}
+
+/**
+ * Universal single-file upload field backed by ActiveStorage direct upload.
+ * Picking or dropping a file uploads it immediately; the attached file (or
+ * the persisted server-side one) renders as an `Attachment` with a remove
+ * action. Fully controlled — the consumer maps {@link FileUploadValue} onto
+ * its form and decides how to serialize it (send `signed_id`, send `null`
+ * to clear, or omit).
+ */
+export function FileUploadField({
+ value,
+ onChange,
+ accept,
+ variant = 'file',
+ icon,
+ serverUrl,
+ serverFilename,
+ label,
+ help,
+ dropLabel,
+ browseLabel,
+ mediaClassName,
+ disabled = false,
+ transformFile,
+}: FileUploadFieldProps) {
+ const { t } = useTranslation()
+ const directUpload = useDirectUpload()
+ const [pending, setPending] = useState<File | null>(null)
+
+ const isImage = variant === 'image'
+
+ async function handlePicked(picked: File) {
+ if (disabled || pending) return
+
+ const file = transformFile ? transformFile(picked) : picked
+ setPending(file)
+ try {
+ const result = await directUpload.mutateAsync(file)
+ // Revoke a preview we're replacing in-place; the object URL otherwise
+ // lives in caller-owned state, so its lifetime is their responsibility
+ // (a hidden-then-shown card must not remount with a dead URL).
+ if (value.previewUrl) URL.revokeObjectURL(value.previewUrl)
+ onChange({
+ signedId: result.signedId,
+ previewUrl: isImage ? result.previewUrl : null,
+ cleared: false,
+ filename: file.name,
+ byteSize: file.size,
+ })
+ } catch (err) {
+ toast.error(
+ t('admin.components.file_upload.upload_failed', {
+ message: err instanceof Error ? err.message : String(err),
+ }),
+ )
+ } finally {
+ setPending(null)
+ }
+ }
+
+ function handleRemove() {
+ if (value.previewUrl) URL.revokeObjectURL(value.previewUrl)
+ onChange({ signedId: null, previewUrl: null, cleared: true, filename: null, byteSize: null })
+ }
+
+ // What the attachment row shows: the in-flight pick, the uploaded file, or
+ // the persisted server-side attachment (until the user clears it).
+ const attached = pending
+ ? { state: 'uploading' as const, name: pending.name, size: pending.size, preview: null }
+ : value.signedId
+ ? {
+ state: 'done' as const,
+ name: value.filename ?? null,
+ size: value.byteSize ?? null,
+ preview: value.previewUrl,
+ }
+ : !value.cleared && (serverUrl || serverFilename)
+ ? {
+ state: 'done' as const,
+ name: serverFilename ?? null,
+ size: null,
+ preview: serverUrl ?? null,
+ }
+ : null
+
+ return (
+ <Field>
+ {label && <FieldLabel>{label}</FieldLabel>}
+ <div className="flex flex-col gap-2">
+ {/* A <label> wrapping the file input: clicking anywhere opens the
+ picker natively, no JS forwarding needed. */}
+ <label
+ className={cn(
+ 'flex cursor-pointer flex-col items-center justify-center gap-2 rounded-md border border-border border-dashed bg-muted/40 px-4 py-8 text-center transition-colors hover:bg-muted',
+ (disabled || !!pending) && 'pointer-events-none opacity-60',
+ )}
+ onDragOver={(e) => e.preventDefault()}
+ onDrop={(e) => {
+ e.preventDefault()
+ const dropped = e.dataTransfer.files?.[0]
+ if (dropped) void handlePicked(dropped)
+ }}
+ >
+ <UploadCloudIcon className="size-6 text-muted-foreground" />
+ <span className="text-muted-foreground text-sm">
+ {dropLabel ?? t('admin.components.file_upload.drop_label')}
+ </span>
+ <span className="mt-1 inline-flex h-8 items-center rounded-md border border-border bg-background px-3 font-medium text-sm shadow-xs">
+ {browseLabel ?? t('admin.components.file_upload.browse')}
+ </span>
+ <input
+ type="file"
+ accept={accept}
+ className="hidden"
+ disabled={disabled || !!pending}
+ onChange={(e) => {
+ const picked = e.target.files?.[0]
+ if (picked) void handlePicked(picked)
+ e.target.value = ''
+ }}
+ />
+ </label>
+
+ {attached && (
+ <Attachment className="w-full" state={attached.state}>
+ <AttachmentMedia
+ variant={isImage && attached.preview ? 'image' : 'icon'}
+ className={mediaClassName}
+ >
+ {isImage && attached.preview ? (
+ <img src={attached.preview} alt="" className="size-full object-contain" />
+ ) : (
+ (icon ?? <FileIcon />)
+ )}
+ </AttachmentMedia>
+ <AttachmentContent>
+ <AttachmentTitle>
+ {attached.name ?? t('admin.components.file_upload.attached')}
+ </AttachmentTitle>
+ <AttachmentDescription>
+ {attached.state === 'uploading'
+ ? t('admin.components.file_upload.uploading')
+ : attached.size != null
+ ? formatFileSize(attached.size)
+ : null}
+ </AttachmentDescription>
+ </AttachmentContent>
+ <AttachmentActions>
+ <AttachmentAction
+ aria-label={t('admin.actions.remove')}
+ onClick={handleRemove}
+ disabled={disabled || !!pending}
+ >
+ <XIcon />
+ </AttachmentAction>
+ </AttachmentActions>
+ </Attachment>
+ )}
+
+ {help && <FieldDescription>{help}</FieldDescription>}
+ </div>
+ </Field>
+ )
+}
diff --git a/packages/dashboard-core/src/components/image-upload-field.tsx b/packages/dashboard-core/src/components/image-upload-field.tsx
index 9e866a63e3..fadca412f3 100644
--- a/packages/dashboard-core/src/components/image-upload-field.tsx
+++ b/packages/dashboard-core/src/components/image-upload-field.tsx
@@ -1,35 +1,18 @@
-import { Button, cn, Field, FieldDescription, FieldLabel } from '@spree/dashboard-ui'
-import { ImageIcon, UploadCloudIcon } from 'lucide-react'
-import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { toast } from 'sonner'
-import { useDirectUpload } from '../hooks/use-direct-upload'
+import { FileUploadField, type FileUploadValue } from './file-upload-field'
-/**
- * Controlled upload state. A field is in exactly one of three states:
- * - untouched: `signedId == null && !cleared` → caller omits it on save
- * - uploaded: `signedId` set → caller sends the signed_id
- * - cleared: `cleared == true` → caller sends null to purge
- *
- * `previewUrl` is a transient object URL for the just-picked file; it's only
- * meaningful while `signedId` is set.
- */
-export interface ImageUploadValue {
- signedId: string | null
- previewUrl: string | null
- cleared: boolean
-}
+/** @deprecated Use {@link FileUploadValue} — same shape, universal name. */
+export type ImageUploadValue = FileUploadValue
export interface ImageUploadFieldProps {
- /** Current upload state. */
value: ImageUploadValue
onChange: (value: ImageUploadValue) => void
/** URL of the already-persisted image, shown until the user replaces/removes it. */
serverUrl?: string | null
label?: string
- /** Helper text under the buttons. */
+ /** Helper text under the dropzone. */
help?: string
- /** Square preview + crop hint (e.g. avatars, logos). Defaults to a 16:9-ish box. */
+ /** Square preview (avatars); default is a wider logo-friendly box. */
square?: boolean
/** Accepted MIME types. Defaults to PNG/JPEG/WebP. */
accept?: string
@@ -37,11 +20,8 @@ export interface ImageUploadFieldProps {
}
/**
- * Reusable single-image upload field backed by ActiveStorage direct upload.
- * Fully controlled — it owns the upload/preview/remove UX and reports state via
- * `onChange`; the consumer maps `ImageUploadValue` onto its form and decides how
- * to serialize it (send `signed_id`, send `null` to clear, or omit). Use for
- * category images, store logo, brand assets, etc.
+ * Single-image preset of {@link FileUploadField} — logos, avatars, category
+ * images. Kept as a named export so existing call sites stay drop-in.
*/
export function ImageUploadField({
value,
@@ -54,99 +34,20 @@ export function ImageUploadField({
disabled = false,
}: ImageUploadFieldProps) {
const { t } = useTranslation()
- const directUpload = useDirectUpload()
- const fileInputRef = useRef<HTMLInputElement | null>(null)
- const [uploading, setUploading] = useState(false)
-
- // Show the just-picked file, else the persisted image — unless the user
- // cleared it (then show the empty placeholder even if a serverUrl exists).
- const currentPreview = value.previewUrl ?? (value.cleared ? null : (serverUrl ?? null))
- const hasImage = !!currentPreview
-
- // The object URL lives in caller-owned state (the form), so its lifetime is
- // the caller's responsibility — the field must not revoke it on unmount, or a
- // hidden-then-shown card (e.g. the store-logo card) would remount with a dead
- // URL. We only revoke a URL we're replacing in-place below, within this field.
- async function onFileChange(e: React.ChangeEvent<HTMLInputElement>) {
- const file = e.target.files?.[0]
- if (!file) return
- setUploading(true)
- try {
- const result = await directUpload.mutateAsync(file)
- if (value.previewUrl) URL.revokeObjectURL(value.previewUrl)
- onChange({ signedId: result.signedId, previewUrl: result.previewUrl, cleared: false })
- } catch (err) {
- toast.error(err instanceof Error ? err.message : t('admin.image_upload.upload_failed'))
- } finally {
- setUploading(false)
- if (fileInputRef.current) fileInputRef.current.value = ''
- }
- }
-
- function clear() {
- if (value.previewUrl) URL.revokeObjectURL(value.previewUrl)
- onChange({ signedId: null, previewUrl: null, cleared: true })
- }
return (
- <Field>
- {label && <FieldLabel>{label}</FieldLabel>}
- <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:gap-6">
- <div
- className={cn(
- 'flex shrink-0 items-center justify-center overflow-hidden rounded-md border border-border border-dashed bg-muted transition-colors',
- square ? 'size-24' : 'h-24 w-44',
- )}
- >
- {hasImage ? (
- <img src={currentPreview} alt="" className="size-full object-contain" />
- ) : (
- <div className="flex flex-col items-center gap-2 text-muted-foreground">
- {uploading ? (
- <UploadCloudIcon className="size-6 animate-pulse" />
- ) : (
- <ImageIcon className="size-6" />
- )}
- </div>
- )}
- </div>
- <div className="flex flex-col gap-2">
- <div className="flex flex-wrap items-center gap-2">
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => fileInputRef.current?.click()}
- disabled={uploading || disabled}
- >
- {uploading
- ? t('admin.image_upload.uploading')
- : hasImage
- ? t('admin.image_upload.replace_cta')
- : t('admin.image_upload.upload_cta')}
- </Button>
- {hasImage && (
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={clear}
- disabled={uploading || disabled}
- >
- {t('admin.image_upload.remove_cta')}
- </Button>
- )}
- </div>
- {help && <FieldDescription>{help}</FieldDescription>}
- </div>
- <input
- ref={fileInputRef}
- type="file"
- accept={accept}
- className="hidden"
- onChange={onFileChange}
- />
- </div>
- </Field>
+ <FileUploadField
+ variant="image"
+ value={value}
+ onChange={onChange}
+ accept={accept}
+ serverUrl={serverUrl}
+ label={label}
+ help={help}
+ disabled={disabled}
+ dropLabel={t('admin.components.file_upload.drop_image_label')}
+ browseLabel={t('admin.image_upload.upload_cta')}
+ mediaClassName={square ? 'size-16' : 'h-16 w-28'}
+ />
)
}
diff --git a/packages/dashboard-core/src/components/import-button.tsx b/packages/dashboard-core/src/components/import-button.tsx
index b9121067fc..b7fad4b119 100644
--- a/packages/dashboard-core/src/components/import-button.tsx
+++ b/packages/dashboard-core/src/components/import-button.tsx
@@ -1,12 +1,5 @@
import type { Import, ImportType } from '@spree/admin-sdk'
import {
- Attachment,
- AttachmentAction,
- AttachmentActions,
- AttachmentContent,
- AttachmentDescription,
- AttachmentMedia,
- AttachmentTitle,
Button,
Field,
FieldLabel,
@@ -22,13 +15,14 @@ import {
SheetHeader,
SheetTitle,
} from '@spree/dashboard-ui'
-import { DownloadIcon, FileSpreadsheetIcon, UploadIcon, XIcon } from 'lucide-react'
+import { DownloadIcon, FileSpreadsheetIcon, UploadIcon } from 'lucide-react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { useCreateImport, useDownloadImportTemplate } from '../hooks/use-import'
import type { SubjectName } from '../lib/permissions'
import { Can } from './can'
+import { EMPTY_FILE_UPLOAD_VALUE, FileUploadField, type FileUploadValue } from './file-upload-field'
const DELIMITERS = [
{ value: ',', labelKey: 'comma' },
@@ -39,12 +33,6 @@ const DELIMITERS = [
type Delimiter = (typeof DELIMITERS)[number]['value']
-function formatFileSize(bytes: number): string {
- if (bytes < 1024) return `${bytes} B`
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
-}
-
interface ImportButtonProps {
/** Which dataset to import. Server validates against `Spree::Import.available_types`. */
type: ImportType
@@ -66,13 +54,14 @@ interface ImportButtonProps {
/**
* Toolbar entry point for CSV imports: opens a Sheet with the upload form
- * (file, delimiter, template download). On success the sheet closes and the
- * created import is handed to `onCreated`.
+ * (file, delimiter, template download). The CSV direct-uploads on pick via
+ * `FileUploadField`; submitting creates the import from the signed blob id
+ * and hands it to `onCreated`.
*/
export function ImportButton({ type, subject, onCreated, label }: ImportButtonProps) {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
- const [file, setFile] = useState<File | null>(null)
+ const [file, setFile] = useState<FileUploadValue>(EMPTY_FILE_UPLOAD_VALUE)
const [delimiter, setDelimiter] = useState<Delimiter>(',')
const createImport = useCreateImport()
const downloadTemplate = useDownloadImportTemplate()
@@ -84,14 +73,14 @@ export function ImportButton({ type, subject, onCreated, label }: ImportButtonPr
function handleOpenChange(next: boolean) {
setOpen(next)
- if (!next) setFile(null)
+ if (!next) setFile(EMPTY_FILE_UPLOAD_VALUE)
}
function handleSubmit() {
- if (!file || createImport.isPending) return
+ if (!file.signedId || createImport.isPending) return
createImport.mutate(
- { type, file, preferredDelimiter: delimiter },
+ { type, signedId: file.signedId, preferredDelimiter: delimiter },
{
onSuccess: (imp) => {
handleOpenChange(false)
@@ -141,60 +130,18 @@ export function ImportButton({ type, subject, onCreated, label }: ImportButtonPr
</SheetHeader>
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4">
- {/* A <label> wrapping the file input: clicking anywhere opens the
- picker natively, no JS forwarding needed. */}
- <label
- className="flex cursor-pointer flex-col items-center justify-center gap-2 rounded-md border border-border border-dashed bg-muted/40 px-4 py-10 text-center transition-colors hover:bg-muted"
- onDragOver={(e) => e.preventDefault()}
- onDrop={(e) => {
- e.preventDefault()
- const dropped = e.dataTransfer.files?.[0]
- if (dropped) setFile(dropped)
- }}
- >
- <FileSpreadsheetIcon className="size-6 text-muted-foreground" />
- <span className="text-muted-foreground text-sm">
- {t('admin.components.import_button.drop_label')}
- </span>
- <span className="mt-1 inline-flex h-8 items-center rounded-md border border-border bg-background px-3 font-medium text-sm shadow-xs">
- {t('admin.components.import_button.browse')}
- </span>
- <input
- type="file"
- accept=".csv,text/csv"
- className="hidden"
- onChange={(e) => {
- const picked = e.target.files?.[0]
- if (picked) setFile(picked)
- e.target.value = ''
- }}
- />
- </label>
-
- {file && (
- <Attachment className="w-full" state={createImport.isPending ? 'uploading' : 'done'}>
- <AttachmentMedia>
- <FileSpreadsheetIcon />
- </AttachmentMedia>
- <AttachmentContent>
- <AttachmentTitle>{file.name}</AttachmentTitle>
- <AttachmentDescription>
- {createImport.isPending
- ? t('admin.components.import_button.uploading')
- : formatFileSize(file.size)}
- </AttachmentDescription>
- </AttachmentContent>
- <AttachmentActions>
- <AttachmentAction
- aria-label={t('admin.actions.remove')}
- onClick={() => setFile(null)}
- disabled={createImport.isPending}
- >
- <XIcon />
- </AttachmentAction>
- </AttachmentActions>
- </Attachment>
- )}
+ <FileUploadField
+ value={file}
+ onChange={setFile}
+ accept=".csv,text/csv"
+ variant="file"
+ icon={<FileSpreadsheetIcon />}
+ dropLabel={t('admin.components.import_button.drop_label')}
+ browseLabel={t('admin.components.import_button.browse')}
+ // Windows browsers report `.csv` as `application/vnd.ms-excel`,
+ // which the server's content-type validation rejects.
+ transformFile={(picked) => new File([picked], picked.name, { type: 'text/csv' })}
+ />
<Field>
<FieldLabel>{t('admin.components.import_button.delimiter_label')}</FieldLabel>
@@ -242,10 +189,10 @@ export function ImportButton({ type, subject, onCreated, label }: ImportButtonPr
type="button"
size="sm"
onClick={handleSubmit}
- disabled={!file || createImport.isPending}
+ disabled={!file.signedId || createImport.isPending}
>
{createImport.isPending
- ? t('admin.components.import_button.uploading')
+ ? t('admin.actions.creating')
: t('admin.components.import_button.submit')}
</Button>
</SheetFooter>
diff --git a/packages/dashboard-core/src/hooks/use-import.ts b/packages/dashboard-core/src/hooks/use-import.ts
index 06ff76d9e0..a5efe729c1 100644
--- a/packages/dashboard-core/src/hooks/use-import.ts
+++ b/packages/dashboard-core/src/hooks/use-import.ts
@@ -3,32 +3,26 @@ import { useMutation } from '@tanstack/react-query'
import { adminClient } from '../client'
import { useStore } from '../providers/store-provider'
import { useAuth } from './use-auth'
-import { useDirectUpload } from './use-direct-upload'
const API_BASE_URL = import.meta.env.VITE_SPREE_API_URL || ''
export interface CreateImportInput {
type: ImportType
- file: File
+ /** Signed blob id of the already direct-uploaded CSV (see `FileUploadField`). */
+ signedId: string
preferredDelimiter?: ImportCreateParams['preferred_delimiter']
}
/**
- * Direct-uploads the CSV, then creates the import (returned in the `mapping`
- * state). The file is re-wrapped with an explicit `text/csv` content type —
- * Windows browsers report `.csv` files as `application/vnd.ms-excel`, which
- * the server's content-type validation rejects.
+ * Creates the import from a direct-uploaded CSV; the response is in the
+ * `mapping` state and carries the mapping payload.
*/
export function useCreateImport() {
- const directUpload = useDirectUpload()
const { storeId } = useStore()
return useMutation({
- mutationFn: async ({ type, file, preferredDelimiter }: CreateImportInput): Promise<Import> => {
- const csvFile = new File([file], file.name, { type: 'text/csv' })
- const { signedId } = await directUpload.mutateAsync(csvFile)
-
- return adminClient.imports.create({
+ mutationFn: ({ type, signedId, preferredDelimiter }: CreateImportInput): Promise<Import> =>
+ adminClient.imports.create({
type,
attachment: signedId,
preferred_delimiter: preferredDelimiter,
@@ -36,40 +30,59 @@ export function useCreateImport() {
// appended server-side). Only honored when this origin is on the
// store's allowed-origins list.
results_url: `${window.location.origin}/${storeId}/settings/imports`,
- })
- },
+ }),
})
}
/**
- * Fetches the CSV template for an import type and drives a browser download
- * via a Blob URL — the endpoint is JWT-protected, so a top-level navigation
- * (which cannot carry the in-memory token) does not work.
+ * Authed fetch → Blob URL download. The endpoints are JWT-protected, so a
+ * top-level navigation (which cannot carry the in-memory token) does not work.
*/
+async function downloadFromApi(token: string | null, path: string, fallbackName: string) {
+ const headers: Record<string, string> = {}
+ if (token) headers.Authorization = `Bearer ${token}`
+
+ const response = await fetch(`${API_BASE_URL}${path}`, { headers, credentials: 'include' })
+ if (!response.ok) throw new Error(`Download failed: ${response.status}`)
+
+ const disposition = response.headers.get('Content-Disposition')
+ const filename = disposition?.match(/filename="?([^";]+)"?/)?.[1] ?? fallbackName
+
+ const blob = await response.blob()
+ const objectUrl = URL.createObjectURL(blob)
+ const anchor = document.createElement('a')
+ anchor.href = objectUrl
+ anchor.download = filename
+ document.body.appendChild(anchor)
+ anchor.click()
+ anchor.remove()
+ URL.revokeObjectURL(objectUrl)
+}
+
+/** Downloads the CSV template for an import type. */
export function useDownloadImportTemplate() {
const { token } = useAuth()
return useMutation({
- mutationFn: async (type: ImportType): Promise<void> => {
- const url = `${API_BASE_URL}/api/v3/admin/imports/template?type=${encodeURIComponent(type)}`
- const headers: Record<string, string> = {}
- if (token) headers.Authorization = `Bearer ${token}`
-
- const response = await fetch(url, { headers, credentials: 'include' })
- if (!response.ok) throw new Error(`Template download failed: ${response.status}`)
+ mutationFn: (type: ImportType) =>
+ downloadFromApi(
+ token,
+ `/api/v3/admin/imports/template?type=${encodeURIComponent(type)}`,
+ 'import_template.csv',
+ ),
+ })
+}
- const disposition = response.headers.get('Content-Disposition')
- const filename = disposition?.match(/filename="?([^";]+)"?/)?.[1] ?? 'import_template.csv'
+/** Downloads the originally uploaded CSV of an import — the audit trail. */
+export function useDownloadImportOriginal() {
+ const { token } = useAuth()
- const blob = await response.blob()
- const objectUrl = URL.createObjectURL(blob)
- const anchor = document.createElement('a')
- anchor.href = objectUrl
- anchor.download = filename
- document.body.appendChild(anchor)
- anchor.click()
- anchor.remove()
- URL.revokeObjectURL(objectUrl)
- },
+ return useMutation({
+ mutationFn: (imp: Import) =>
+ downloadFromApi(
+ token,
+ imp.original_file_url ?? `/api/v3/admin/imports/${imp.id}/download`,
+ imp.original_filename ?? 'import.csv',
+ ),
})
}
diff --git a/packages/dashboard-core/src/index.ts b/packages/dashboard-core/src/index.ts
index 74b332e17d..b1e48e88ac 100644
--- a/packages/dashboard-core/src/index.ts
+++ b/packages/dashboard-core/src/index.ts
@@ -22,6 +22,7 @@ export * from './components/country-combobox'
export * from './components/country-state-fields'
export * from './components/currency-select'
export * from './components/export-button'
+export * from './components/file-upload-field'
export * from './components/image-upload-field'
export * from './components/import-button'
export * from './components/locale-select'
diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.json
index bdad335a5e..8abf9e0f3c 100644
--- a/packages/dashboard-core/src/locales/ar.json
+++ b/packages/dashboard-core/src/locales/ar.json
@@ -361,6 +361,14 @@
"channel_select": {
"placeholder": "اختر قناة مبيعات"
},
+ "file_upload": {
+ "attached": "ملف مرفق",
+ "browse": "استعراض الملفات",
+ "drop_image_label": "أسقط صورة هنا، أو انقر للاستعراض",
+ "drop_label": "أسقط ملفًا هنا، أو انقر للاستعراض",
+ "upload_failed": "فشل الرفع: {{message}}",
+ "uploading": "جارٍ الرفع…"
+ },
"locale_select": {
"placeholder": "اختر لغة",
"multi_placeholder": "إضافة لغات…",
@@ -482,8 +490,7 @@
},
"download_template": "تنزيل قالب CSV",
"template_failed": "فشل تنزيل القالب: {{message}}",
- "submit": "رفع ومتابعة",
- "uploading": "جارٍ الرفع…",
+ "submit": "متابعة",
"failed": "فشل الاستيراد: {{message}}"
},
"metadata_card": {
diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.json
index 388cd848ab..8125103b6d 100644
--- a/packages/dashboard-core/src/locales/de.json
+++ b/packages/dashboard-core/src/locales/de.json
@@ -361,6 +361,14 @@
"channel_select": {
"placeholder": "Verkaufskanal auswählen"
},
+ "file_upload": {
+ "attached": "Angehängte Datei",
+ "browse": "Dateien durchsuchen",
+ "drop_image_label": "Bild hier ablegen oder klicken zum Auswählen",
+ "drop_label": "Datei hier ablegen oder klicken zum Auswählen",
+ "upload_failed": "Upload fehlgeschlagen: {{message}}",
+ "uploading": "Wird hochgeladen…"
+ },
"locale_select": {
"placeholder": "Sprache auswählen",
"multi_placeholder": "Sprachen hinzufügen…",
@@ -482,8 +490,7 @@
},
"download_template": "CSV-Vorlage herunterladen",
"template_failed": "Vorlagen-Download fehlgeschlagen: {{message}}",
- "submit": "Hochladen & weiter",
- "uploading": "Wird hochgeladen…",
+ "submit": "Weiter",
"failed": "Import fehlgeschlagen: {{message}}"
},
"metadata_card": {
diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.json
index cc961f6177..5e44d18217 100644
--- a/packages/dashboard-core/src/locales/en.json
+++ b/packages/dashboard-core/src/locales/en.json
@@ -361,6 +361,14 @@
"channel_select": {
"placeholder": "Select a sales channel"
},
+ "file_upload": {
+ "attached": "Attached file",
+ "browse": "Browse files",
+ "drop_image_label": "Drop an image here, or click to browse",
+ "drop_label": "Drop a file here, or click to browse",
+ "upload_failed": "Upload failed: {{message}}",
+ "uploading": "Uploading…"
+ },
"locale_select": {
"placeholder": "Select a locale",
"multi_placeholder": "Add locales…",
@@ -482,8 +490,7 @@
},
"download_template": "Download CSV template",
"template_failed": "Template download failed: {{message}}",
- "submit": "Upload & continue",
- "uploading": "Uploading…",
+ "submit": "Continue",
"failed": "Import failed: {{message}}"
},
"metadata_card": {
diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.json
index 842c276101..c8b05c1da7 100644
--- a/packages/dashboard-core/src/locales/fr.json
+++ b/packages/dashboard-core/src/locales/fr.json
@@ -361,6 +361,14 @@
"channel_select": {
"placeholder": "Sélectionner un canal de vente"
},
+ "file_upload": {
+ "attached": "Fichier joint",
+ "browse": "Parcourir les fichiers",
+ "drop_image_label": "Déposez une image ici ou cliquez pour parcourir",
+ "drop_label": "Déposez un fichier ici ou cliquez pour parcourir",
+ "upload_failed": "Échec du téléversement : {{message}}",
+ "uploading": "Téléversement…"
+ },
"locale_select": {
"placeholder": "Sélectionner une langue",
"multi_placeholder": "Ajouter des langues…",
@@ -482,8 +490,7 @@
},
"download_template": "Télécharger le modèle CSV",
"template_failed": "Échec du téléchargement du modèle : {{message}}",
- "submit": "Téléverser et continuer",
- "uploading": "Téléversement…",
+ "submit": "Continuer",
"failed": "Échec de l'import : {{message}}"
},
"metadata_card": {
diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.json
index d154a3a9c2..0bae5687f7 100644
--- a/packages/dashboard-core/src/locales/pl.json
+++ b/packages/dashboard-core/src/locales/pl.json
@@ -361,6 +361,14 @@
"channel_select": {
"placeholder": "Wybierz kanał sprzedaży"
},
+ "file_upload": {
+ "attached": "Załączony plik",
+ "browse": "Przeglądaj pliki",
+ "drop_image_label": "Upuść obraz tutaj lub kliknij, aby przeglądać",
+ "drop_label": "Upuść plik tutaj lub kliknij, aby przeglądać",
+ "upload_failed": "Przesyłanie nie powiodło się: {{message}}",
+ "uploading": "Przesyłanie…"
+ },
"locale_select": {
"placeholder": "Wybierz język",
"multi_placeholder": "Dodaj języki…",
@@ -482,8 +490,7 @@
},
"download_template": "Pobierz szablon CSV",
"template_failed": "Pobieranie szablonu nie powiodło się: {{message}}",
- "submit": "Prześlij i kontynuuj",
- "uploading": "Przesyłanie…",
+ "submit": "Kontynuuj",
"failed": "Import nie powiódł się: {{message}}"
},
"metadata_card": {
diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.json
index df371751ae..e0a472c3ab 100644
--- a/packages/dashboard-core/src/locales/zh-CN.json
+++ b/packages/dashboard-core/src/locales/zh-CN.json
@@ -361,6 +361,14 @@
"channel_select": {
"placeholder": "选择销售渠道"
},
+ "file_upload": {
+ "attached": "已附加文件",
+ "browse": "浏览文件",
+ "drop_image_label": "将图片拖放到此处,或点击浏览",
+ "drop_label": "将文件拖放到此处,或点击浏览",
+ "upload_failed": "上传失败:{{message}}",
+ "uploading": "正在上传…"
+ },
"locale_select": {
"placeholder": "选择语言区域",
"multi_placeholder": "添加语言区域…",
@@ -482,8 +490,7 @@
},
"download_template": "下载 CSV 模板",
"template_failed": "模板下载失败:{{message}}",
- "submit": "上传并继续",
- "uploading": "正在上传…",
+ "submit": "继续",
"failed": "导入失败:{{message}}"
},
"metadata_card": {
diff --git a/packages/dashboard-ui/src/ui/attachment.tsx b/packages/dashboard-ui/src/ui/attachment.tsx
index a024919c8e..6653888935 100644
--- a/packages/dashboard-ui/src/ui/attachment.tsx
+++ b/packages/dashboard-ui/src/ui/attachment.tsx
@@ -56,7 +56,9 @@ const attachmentMediaVariants = cva(
variants: {
variant: {
icon: 'bg-muted text-muted-foreground',
- image: '*:[img]:aspect-square *:[img]:w-full *:[img]:object-cover',
+ // Image fit is left to the caller's <img> classes — logos want
+ // `object-contain`, photos want `object-cover`.
+ image: 'bg-muted',
},
},
defaultVariants: {
diff --git a/packages/dashboard/e2e/imports.spec.ts b/packages/dashboard/e2e/imports.spec.ts
index 5bb17ef5e2..01a16d538b 100644
--- a/packages/dashboard/e2e/imports.spec.ts
+++ b/packages/dashboard/e2e/imports.spec.ts
@@ -42,7 +42,7 @@ test.describe('csv import', () => {
`e2e-import-bad-${suffix},E2E-IMP-BAD-${suffix},,`,
]),
)
- await page.getByRole('button', { name: /upload & continue/i }).click()
+ await page.getByRole('button', { name: /^continue$/i }).click()
// Mapping step — canonical headers auto-assign, so required fields are
// already satisfied and the sample value from the file is shown.
@@ -96,7 +96,7 @@ test.describe('csv import', () => {
`e2e-import-nomap-${suffix},E2E-IMP-NM-${suffix},No Price ${suffix}`,
]),
)
- await page.getByRole('button', { name: /upload & continue/i }).click()
+ await page.getByRole('button', { name: /^continue$/i }).click()
await expect(page.getByText('Map columns')).toBeVisible({ timeout: 15_000 })
await expect(page.getByRole('button', { name: /start import/i })).toBeDisabled()
diff --git a/packages/dashboard/e2e/store-settings.spec.ts b/packages/dashboard/e2e/store-settings.spec.ts
index 23c27542ff..5dd1b394c4 100644
--- a/packages/dashboard/e2e/store-settings.spec.ts
+++ b/packages/dashboard/e2e/store-settings.spec.ts
@@ -147,7 +147,7 @@ test.describe('store settings — emails', () => {
// use that as a proxy for the card's presence. The CardTitle is rendered as
// a `<div>` so `role=heading` doesn't apply, and matching plain text would
// collide with other strings.
- const uploadCta = page.getByRole('button', { name: /upload image/i })
+ const uploadCta = page.getByText('Upload image')
// Base UI's <Switch> renders a hidden <input> + a visible <button
// role="switch">. The id is on the hidden input, so we drive interaction