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.

Refactor custom fields components to be more universal (#14230)

Damian Legawiec3a8e7afec86b
diff --git a/packages/dashboard-core/src/hooks/use-custom-fields.ts b/packages/dashboard-core/src/hooks/use-custom-fields.ts
index 4d3412bb4f..aa33aa11ec 100644
--- a/packages/dashboard-core/src/hooks/use-custom-fields.ts
+++ b/packages/dashboard-core/src/hooks/use-custom-fields.ts
@@ -124,8 +124,9 @@ export function useDeleteCustomFieldDefinitionForSettings() {
}
// ---------------------------------------------------------------------------
-// Drawer-only variants — pinned to a single `resourceType`. Existing call
-// sites (product/order/customer detail pages) keep these.
+// Resource-scoped create — pins invalidation to a single `resourceType` so the
+// inline custom-fields card's definitions query re-validates the moment a field
+// is created in place (the create-definition sheet on a record detail page).
// ---------------------------------------------------------------------------
export function useCreateCustomFieldDefinition(resourceType: string) {
@@ -139,26 +140,3 @@ export function useCreateCustomFieldDefinition(resourceType: string) {
},
})
}
-
-export function useUpdateCustomFieldDefinition(resourceType: string) {
- const queryClient = useQueryClient()
- return useMutation({
- mutationFn: ({ id, ...params }: { id: string } & CustomFieldDefinitionUpdateParams) =>
- adminClient.customFieldDefinitions.update(id, params),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: definitionsKey(resourceType) })
- queryClient.invalidateQueries({ queryKey: customFieldDefinitionsRootKey })
- },
- })
-}
-
-export function useDeleteCustomFieldDefinition(resourceType: string) {
- const queryClient = useQueryClient()
- return useMutation({
- mutationFn: (id: string) => adminClient.customFieldDefinitions.delete(id),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: definitionsKey(resourceType) })
- queryClient.invalidateQueries({ queryKey: customFieldDefinitionsRootKey })
- },
- })
-}
diff --git a/packages/dashboard-core/src/lib/permissions.ts b/packages/dashboard-core/src/lib/permissions.ts
index 9c1f43e617..7b1ac2dd3b 100644
--- a/packages/dashboard-core/src/lib/permissions.ts
+++ b/packages/dashboard-core/src/lib/permissions.ts
@@ -16,8 +16,10 @@ export const Subject = {
AllowedOrigin: 'Spree::AllowedOrigin',
Store: 'Spree::Store',
Channel: 'Spree::Channel',
- Taxon: 'Spree::Taxon',
- Taxonomy: 'Spree::Taxonomy',
+ // Categories are Spree::Category < Spree::Taxon; abilities are published under
+ // the Spree::Taxon subject, so the value stays 'Spree::Taxon' while the key
+ // reads as the user-facing resource name.
+ Category: 'Spree::Taxon',
OptionType: 'Spree::OptionType',
OptionValue: 'Spree::OptionValue',
TaxCategory: 'Spree::TaxCategory',
diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.json
index b844cd931a..dea833d53c 100644
--- a/packages/dashboard-core/src/locales/ar.json
+++ b/packages/dashboard-core/src/locales/ar.json
@@ -104,7 +104,8 @@
"delete_confirm_message": "هل أنت متأكد؟ لا يمكن التراجع عن هذا الإجراء.",
"adjust_search_or_filters": "جرّب تعديل البحث أو عوامل التصفية",
"default": "افتراضي",
- "cancel": "إلغاء"
+ "cancel": "إلغاء",
+ "empty_value": "—"
},
"color_picker": {
"no_color": "بدون لون"
@@ -319,6 +320,12 @@
"storefront_visible": {
"label": "مرئي في المتجر",
"help": "عند الإيقاف، يرى موظفو الإدارة فقط هذا الخيار (طلبات المكتب الخلفي، الإدخال اليدوي)."
+ },
+ "pretty_name": {
+ "label": "الاسم الكامل"
+ },
+ "permalink": {
+ "label": "الرابط الدائم"
}
},
"components": {
diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.json
index 44ceedc65c..69097a5052 100644
--- a/packages/dashboard-core/src/locales/de.json
+++ b/packages/dashboard-core/src/locales/de.json
@@ -104,7 +104,8 @@
"delete_confirm_message": "Sind Sie sicher? Diese Aktion kann nicht rückgängig gemacht werden.",
"adjust_search_or_filters": "Passen Sie Ihre Suche oder Filter an",
"default": "Standard",
- "cancel": "Abbrechen"
+ "cancel": "Abbrechen",
+ "empty_value": "—"
},
"color_picker": {
"no_color": "Keine Farbe"
@@ -319,6 +320,12 @@
"storefront_visible": {
"label": "Im Shop sichtbar",
"help": "Wenn deaktiviert, sehen nur Admin-Mitarbeiter diese Option (Backoffice-Bestellungen, manuelle Eingabe)."
+ },
+ "pretty_name": {
+ "label": "Vollständiger Name"
+ },
+ "permalink": {
+ "label": "Permalink"
}
},
"components": {
diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.json
index 80c78ca5f3..53dec39846 100644
--- a/packages/dashboard-core/src/locales/en.json
+++ b/packages/dashboard-core/src/locales/en.json
@@ -104,7 +104,8 @@
"delete_confirm_message": "Are you sure? This action cannot be undone.",
"adjust_search_or_filters": "Try adjusting your search or filters",
"default": "Default",
- "cancel": "Cancel"
+ "cancel": "Cancel",
+ "empty_value": "—"
},
"color_picker": {
"no_color": "No color"
@@ -319,6 +320,12 @@
"storefront_visible": {
"label": "Visible on storefront",
"help": "When off, only admin staff see this option (back-office orders, manual entry)."
+ },
+ "pretty_name": {
+ "label": "Full name"
+ },
+ "permalink": {
+ "label": "Permalink"
}
},
"components": {
diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.json
index e517b524f0..d3a49d39c8 100644
--- a/packages/dashboard-core/src/locales/fr.json
+++ b/packages/dashboard-core/src/locales/fr.json
@@ -104,7 +104,8 @@
"delete_confirm_message": "Êtes-vous sûr ? Cette action est irréversible.",
"adjust_search_or_filters": "Essayez d’ajuster votre recherche ou vos filtres",
"default": "Par défaut",
- "cancel": "Annuler"
+ "cancel": "Annuler",
+ "empty_value": "—"
},
"color_picker": {
"no_color": "Aucune couleur"
@@ -319,6 +320,12 @@
"storefront_visible": {
"label": "Visible sur la boutique",
"help": "Si désactivé, seuls les administrateurs voient cette option (commandes back-office, saisie manuelle)."
+ },
+ "pretty_name": {
+ "label": "Nom complet"
+ },
+ "permalink": {
+ "label": "Lien permanent"
}
},
"components": {
diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.json
index 0bff78c31e..706f0e4e93 100644
--- a/packages/dashboard-core/src/locales/pl.json
+++ b/packages/dashboard-core/src/locales/pl.json
@@ -104,7 +104,8 @@
"delete_confirm_message": "Czy na pewno? Tej operacji nie można cofnąć.",
"adjust_search_or_filters": "Spróbuj dostosować wyszukiwanie lub filtry",
"default": "Domyślny",
- "cancel": "Anuluj"
+ "cancel": "Anuluj",
+ "empty_value": "—"
},
"color_picker": {
"no_color": "Brak koloru"
@@ -319,6 +320,12 @@
"storefront_visible": {
"label": "Widoczny w sklepie",
"help": "Gdy wyłączone, tylko personel administracyjny widzi tę opcję (zamówienia back-office, ręczne wprowadzanie)."
+ },
+ "pretty_name": {
+ "label": "Pełna nazwa"
+ },
+ "permalink": {
+ "label": "Odnośnik"
}
},
"components": {
diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.json
index be8a5fc0a7..109bbeb853 100644
--- a/packages/dashboard-core/src/locales/zh-CN.json
+++ b/packages/dashboard-core/src/locales/zh-CN.json
@@ -104,7 +104,8 @@
"delete_confirm_message": "确定吗?此操作无法撤销。",
"adjust_search_or_filters": "请尝试调整搜索或筛选条件",
"default": "默认",
- "cancel": "取消"
+ "cancel": "取消",
+ "empty_value": "—"
},
"color_picker": {
"no_color": "无颜色"
@@ -319,6 +320,12 @@
"storefront_visible": {
"label": "在 storefront 可见",
"help": "关闭后,仅后台员工可见此选项(后台订单、手动录入)。"
+ },
+ "pretty_name": {
+ "label": "完整名称"
+ },
+ "permalink": {
+ "label": "固定链接"
}
},
"components": {
diff --git a/packages/dashboard-ui/src/ui/rich-text-editor.tsx b/packages/dashboard-ui/src/ui/rich-text-editor.tsx
index bee7cdae4c..47cfcf822d 100644
--- a/packages/dashboard-ui/src/ui/rich-text-editor.tsx
+++ b/packages/dashboard-ui/src/ui/rich-text-editor.tsx
@@ -21,9 +21,9 @@ interface RichTextEditorProps {
value?: string
onChange?: (html: string) => void
/**
- * Fires when the editor loses focus. Useful for commit-on-blur flows
- * (e.g. ApiBackedCustomFieldsProvider) where onChange is only for
- * live updates and persistence happens once the user moves away.
+ * Fires when the editor loses focus. Useful for commit-on-blur flows where
+ * onChange is only for live updates and persistence happens once the user
+ * moves away.
*/
onBlur?: () => void
placeholder?: string
diff --git a/packages/dashboard/e2e/products-custom-fields.spec.ts b/packages/dashboard/e2e/products-custom-fields.spec.ts
index ce7dd60e72..fdd50ea2fc 100644
--- a/packages/dashboard/e2e/products-custom-fields.spec.ts
+++ b/packages/dashboard/e2e/products-custom-fields.spec.ts
@@ -52,7 +52,7 @@ test.describe('product custom fields — new product', () => {
})
test.describe('product custom fields — existing product', () => {
- test('saves a value on blur and round-trips through reload', async ({ page }) => {
+ test('persists a value on form save and round-trips through reload', async ({ page }) => {
const creds = await login(page)
const suffix = Date.now()
const fieldLabel = `E2E Fit ${suffix}`
@@ -72,14 +72,13 @@ test.describe('product custom fields — existing product', () => {
const input = cfCard.getByLabel(new RegExp(`^${fieldLabel}$`, 'i'))
await expect(input).toBeVisible({ timeout: 15_000 })
await input.fill('Slim')
- await input.blur()
-
- // Wait for the inline-autosave pending mark on this row's label to clear.
- // The widget renders a "…" span beside the label while the mutation is in
- // flight (custom-fields-inline.tsx); polling on its absence is the
- // user-visible "saved" signal, no fixed sleep required.
- const labelLocator = cfCard.locator('label', { hasText: new RegExp(`^${fieldLabel}\\s*…?$`) })
- await expect(labelLocator.getByText('…')).toHaveCount(0, { timeout: 15_000 })
+
+ // Form mode: custom fields persist with the product's own Save, not on blur.
+ const saveButton = page.getByRole('button', { name: /save product/i })
+ await saveButton.click()
+ // Save re-baselines the form to a clean (non-dirty) state, disabling the
+ // button — the user-visible "saved" signal, no fixed sleep required.
+ await expect(saveButton).toBeDisabled({ timeout: 30_000 })
await page.reload()
diff --git a/packages/dashboard/src/components/spree/categories/category-form.tsx b/packages/dashboard/src/components/spree/categories/category-form.tsx
index b413cf18ba..4667b9ca71 100644
--- a/packages/dashboard/src/components/spree/categories/category-form.tsx
+++ b/packages/dashboard/src/components/spree/categories/category-form.tsx
@@ -10,12 +10,18 @@ import {
FieldGroup,
FieldLabel,
Input,
+ MetadataCard,
RichTextEditor,
Textarea,
} from '@spree/dashboard-ui'
import type { UseFormReturn } from 'react-hook-form'
import { Controller } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
+import {
+ CustomFieldsInlineCard,
+ FormBackedCustomFieldsProvider,
+} from '@/components/spree/custom-fields/custom-fields-inline'
+import { ResourceTranslationsCard } from '@/components/spree/translations/resource-translations-card'
import { categoryAutocompleteProps } from '@/hooks/use-categories'
import type { CategoryFormValues } from '@/schemas/category'
import { CategoryImageField } from './category-image-field'
@@ -80,7 +86,26 @@ export function CategoryMain({
</CardContent>
</Card>
- {category && <CategoryProductsCard categoryId={category.id} />}
+ {category && (
+ <>
+ <CategoryProductsCard categoryId={category.id} />
+ {/*
+ Form-backed: custom field values ride along in the category form and
+ persist on the page's Save. Definitions are scoped to Spree::Taxon
+ (the category route maps to the Taxon class server-side).
+ */}
+ <FormBackedCustomFieldsProvider form={form} resourceType="Spree::Taxon">
+ <CustomFieldsInlineCard />
+ </FormBackedCustomFieldsProvider>
+ <ResourceTranslationsCard resourceType="category" resourceId={category.id} />
+ <MetadataCard
+ metadata={category.metadata}
+ title={t('admin.components.metadata_card.title')}
+ emptyTitle={t('admin.components.metadata_card.empty_title')}
+ emptyDescription={t('admin.components.metadata_card.empty_description')}
+ />
+ </>
+ )}
</>
)
}
diff --git a/packages/dashboard/src/components/spree/categories/category-list.tsx b/packages/dashboard/src/components/spree/categories/category-list.tsx
index 1858adedf1..1fb915213d 100644
--- a/packages/dashboard/src/components/spree/categories/category-list.tsx
+++ b/packages/dashboard/src/components/spree/categories/category-list.tsx
@@ -81,7 +81,7 @@ export function CategoryList({
{
key: 'delete',
destructive: true,
- visible: permissions.can('destroy', Subject.Taxon),
+ visible: permissions.can('destroy', Subject.Category),
disabled: deleting,
onSelect: () => onDelete(category),
},
diff --git a/packages/dashboard/src/components/spree/categories/category-translations-dialog.tsx b/packages/dashboard/src/components/spree/categories/category-translations-dialog.tsx
deleted file mode 100644
index ff41d54166..0000000000
--- a/packages/dashboard/src/components/spree/categories/category-translations-dialog.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import type { TranslatableField } from '@spree/admin-sdk'
-import { useTranslation } from 'react-i18next'
-import { ResourceTranslationsDialog } from '@/components/spree/translations/resource-translations-dialog'
-import { useCategoryTranslations } from '@/hooks/use-translations'
-
-interface CategoryTranslationsDialogProps {
- categoryId: string
- open: boolean
- onOpenChange: (open: boolean) => void
-}
-
-/**
- * Category translations editor — a thin adapter over the generic
- * <ResourceTranslationsDialog>. Fetches the category's translation matrix and
- * saves all locales in one batch.
- */
-export function CategoryTranslationsDialog({
- categoryId,
- open,
- onOpenChange,
-}: CategoryTranslationsDialogProps) {
- const { t } = useTranslation()
- const { data, isLoading, isError, refetch } = useCategoryTranslations(categoryId)
-
- const fieldLabel = (resourceType: string, field: TranslatableField) =>
- t([`admin.fields.${resourceType}.${field.key}.label`, `admin.fields.${field.key}.label`], {
- defaultValue: field.key,
- })
-
- return (
- <ResourceTranslationsDialog
- open={open}
- onOpenChange={onOpenChange}
- data={data}
- isLoading={isLoading}
- isError={isError}
- fieldLabel={fieldLabel}
- onSaved={() => refetch()}
- />
- )
-}
diff --git a/packages/dashboard/src/components/spree/categories/category-tree.tsx b/packages/dashboard/src/components/spree/categories/category-tree.tsx
index f753b89557..fa9801b6e3 100644
--- a/packages/dashboard/src/components/spree/categories/category-tree.tsx
+++ b/packages/dashboard/src/components/spree/categories/category-tree.tsx
@@ -158,7 +158,7 @@ export function CategoryTree({
depth={node.id === activeId && projection ? projection.depth : node.depth}
collapsed={collapsed.has(node.id)}
onToggle={() => toggle(node.id)}
- canDestroy={permissions.can('destroy', Subject.Taxon)}
+ canDestroy={permissions.can('destroy', Subject.Category)}
deleting={deleting}
onEdit={() => onEdit(categoriesById.get(node.id) as Category)}
onTranslate={() => onTranslate(categoriesById.get(node.id) as Category)}
diff --git a/packages/dashboard/src/components/spree/custom-fields/custom-fields-card.tsx b/packages/dashboard/src/components/spree/custom-fields/custom-fields-card.tsx
deleted file mode 100644
index 2ccd9dfd24..0000000000
--- a/packages/dashboard/src/components/spree/custom-fields/custom-fields-card.tsx
+++ /dev/null
@@ -1,130 +0,0 @@
-import type { CustomFieldOwnerType } from '@spree/admin-sdk'
-import { useCustomFieldDefinitions, useCustomFields } from '@spree/dashboard-core'
-import {
- Button,
- Card,
- CardContent,
- CardHeader,
- CardTitle,
- Empty,
- EmptyDescription,
- EmptyHeader,
- EmptyMedia,
- EmptyTitle,
- Skeleton,
-} from '@spree/dashboard-ui'
-import { PencilIcon, TagIcon } from 'lucide-react'
-import { Fragment, useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import { CustomFieldsDrawer } from './custom-fields-drawer'
-
-interface CustomFieldsCardProps {
- ownerType: CustomFieldOwnerType
- ownerId: string
- /** Plural display label, e.g. "products". */
- resourceLabel: string
-}
-
-export function CustomFieldsCard({ ownerType, ownerId, resourceLabel }: CustomFieldsCardProps) {
- const { t } = useTranslation()
- const [open, setOpen] = useState(false)
- const { data: definitionsResp, isLoading: defsLoading } = useCustomFieldDefinitions(ownerType)
- const { data: valuesResp, isLoading: valsLoading } = useCustomFields(ownerType, ownerId)
-
- const definitions = definitionsResp?.data ?? []
- const values = valuesResp?.data ?? []
- const valueByDefinition = new Map(values.map((v) => [v.custom_field_definition_id, v]))
- const isLoading = defsLoading || valsLoading
-
- const setCount = definitions.filter((d) => {
- const v = valueByDefinition.get(d.id)?.value
- return v !== null && v !== undefined && v !== ''
- }).length
-
- return (
- <>
- <Card>
- <CardHeader className="flex flex-row items-center justify-between gap-2 space-y-0">
- <CardTitle>{t('admin.pages.products.section_custom_fields')}</CardTitle>
- <Button type="button" variant="outline" size="sm" onClick={() => setOpen(true)}>
- <PencilIcon className="size-4" />
- {definitions.length === 0
- ? t('admin.components.custom_fields_card.set_up')
- : t('admin.actions.edit')}
- </Button>
- </CardHeader>
- <CardContent>
- {isLoading ? (
- <div className="flex flex-col gap-2">
- <Skeleton className="h-4 w-3/4" />
- <Skeleton className="h-4 w-1/2" />
- </div>
- ) : definitions.length === 0 ? (
- <Empty className="border-0 p-0">
- <EmptyHeader>
- <EmptyMedia variant="icon">
- <TagIcon />
- </EmptyMedia>
- <EmptyTitle>{t('admin.components.custom_fields_card.empty_title')}</EmptyTitle>
- <EmptyDescription>
- {t('admin.components.custom_fields_card.empty_description')}
- </EmptyDescription>
- </EmptyHeader>
- </Empty>
- ) : (
- <div className="flex flex-col gap-3">
- <dl className="grid grid-cols-[minmax(160px,1fr)_2fr] gap-x-4 gap-y-2 text-sm">
- {definitions.map((def) => {
- const value = valueByDefinition.get(def.id)?.value
- return (
- <Fragment key={def.id}>
- <dt className="flex flex-col">
- <span className="font-medium">{def.label}</span>
- <code className="text-xs text-muted-foreground">
- {def.namespace}.{def.key}
- </code>
- </dt>
- <dd className="text-foreground/90 break-words">
- {formatValue(value, def.field_type, t)}
- </dd>
- </Fragment>
- )
- })}
- </dl>
- {setCount < definitions.length && (
- <p className="text-xs text-muted-foreground border-t pt-2">
- {t('admin.components.custom_fields_card.not_yet_set', {
- count: definitions.length - setCount,
- total: definitions.length,
- })}
- </p>
- )}
- </div>
- )}
- </CardContent>
- </Card>
-
- <CustomFieldsDrawer
- open={open}
- onOpenChange={setOpen}
- ownerType={ownerType}
- ownerId={ownerId}
- resourceLabel={resourceLabel}
- />
- </>
- )
-}
-
-function formatValue(value: unknown, fieldType: string, t: (key: string) => string): string {
- if (value === null || value === undefined || value === '') return '—'
- if (fieldType === 'boolean') return value ? t('admin.common.yes') : t('admin.common.no')
- if (fieldType === 'rich_text' && typeof value === 'string') {
- // Plain-text preview of HTML for the summary row. DOMParser handles
- // nested/malformed tags correctly — a single-pass regex strip can leak
- // tags via patterns like `<scr<script>ipt>` (CodeQL js/incomplete-multi-character-sanitization).
- const text = new DOMParser().parseFromString(value, 'text/html').body.textContent ?? ''
- return text.trim() || '—'
- }
- if (fieldType === 'json') return typeof value === 'string' ? value : JSON.stringify(value)
- return String(value)
-}
diff --git a/packages/dashboard/src/components/spree/custom-fields/custom-fields-drawer.tsx b/packages/dashboard/src/components/spree/custom-fields/custom-fields-drawer.tsx
deleted file mode 100644
index 1b8fe44d99..0000000000
--- a/packages/dashboard/src/components/spree/custom-fields/custom-fields-drawer.tsx
+++ /dev/null
@@ -1,413 +0,0 @@
-import type { CustomFieldOwnerType } from '@spree/admin-sdk'
-import {
- useCreateCustomField,
- useCustomFieldDefinitions,
- useCustomFields,
- useDeleteCustomField,
- useUpdateCustomField,
-} from '@spree/dashboard-core'
-import {
- Button,
- Empty,
- EmptyContent,
- EmptyDescription,
- EmptyHeader,
- EmptyTitle,
- Field,
- FieldLabel,
- Sheet,
- SheetContent,
- SheetFooter,
- SheetHeader,
- SheetTitle,
- Skeleton,
-} from '@spree/dashboard-ui'
-import { ArrowLeftIcon, CheckCircle2Icon, Loader2Icon, PlusIcon } from 'lucide-react'
-import { type ReactNode, useEffect, useMemo, useState } from 'react'
-import { useForm } from 'react-hook-form'
-import { useTranslation } from 'react-i18next'
-import { toast } from 'sonner'
-import { DefinitionForm } from './definition-form'
-import { ValueInput } from './value-input'
-
-type View = 'values' | 'new-definition' | 'definition-created'
-
-interface CustomFieldsDrawerProps {
- open: boolean
- onOpenChange: (open: boolean) => void
- ownerType: CustomFieldOwnerType
- ownerId: string
- /** Display name for the resource type (e.g., "products"). */
- resourceLabel: string
-}
-
-export function CustomFieldsDrawer({
- open,
- onOpenChange,
- ownerType,
- ownerId,
- resourceLabel,
-}: CustomFieldsDrawerProps) {
- const { t } = useTranslation()
- const [view, setView] = useState<View>('values')
- const [lastCreatedDefinitionId, setLastCreatedDefinitionId] = useState<string | null>(null)
-
- // Reset to values view when the drawer reopens
- useEffect(() => {
- if (open) setView('values')
- }, [open])
-
- const header =
- view === 'values' ? (
- <SheetTitle>{t('admin.components.custom_fields.title')}</SheetTitle>
- ) : (
- <SheetTitle className="flex gap-2 items-center">
- <Button
- type="button"
- variant="ghost"
- size="icon-sm"
- onClick={() => setView('values')}
- aria-label={t('admin.actions.back')}
- >
- <ArrowLeftIcon className="size-4" />
- </Button>
- {view === 'new-definition'
- ? t('admin.components.custom_fields.new_definition_title')
- : t('admin.components.custom_fields.definition_created_title')}
- </SheetTitle>
- )
-
- return (
- <Sheet open={open} onOpenChange={onOpenChange}>
- <SheetContent side="right" showCloseButton className="overflow-hidden">
- {view === 'values' && (
- <ValuesView
- ownerType={ownerType}
- ownerId={ownerId}
- resourceLabel={resourceLabel}
- onAddDefinition={() => setView('new-definition')}
- highlightedDefinitionId={lastCreatedDefinitionId}
- onClearHighlight={() => setLastCreatedDefinitionId(null)}
- onClose={() => onOpenChange(false)}
- header={header}
- />
- )}
- {view === 'new-definition' && (
- <NewDefinitionView
- resourceType={ownerType}
- header={header}
- onCancel={() => setView('values')}
- onSuccess={(id) => {
- setLastCreatedDefinitionId(id)
- setView('definition-created')
- toast.success(t('admin.components.custom_fields.definition_created_toast'))
- }}
- />
- )}
- {view === 'definition-created' && (
- <>
- <SheetHeader>{header}</SheetHeader>
- <div className="flex-1 overflow-y-auto p-4">
- <DefinitionCreatedView
- onAddAnother={() => setView('new-definition')}
- onSetValues={() => setView('values')}
- />
- </div>
- </>
- )}
- </SheetContent>
- </Sheet>
- )
-}
-
-// ---------------------------------------------------------------------------
-// New-definition view — owns the SheetHeader, body, and SheetFooter so the
-// submit button is inside the same <form> as the inputs (no cross-DOM tricks).
-// ---------------------------------------------------------------------------
-
-function NewDefinitionView({
- resourceType,
- header,
- onCancel,
- onSuccess,
-}: {
- resourceType: CustomFieldOwnerType
- header: React.ReactNode
- onCancel: () => void
- onSuccess: (id: string) => void
-}) {
- const { t } = useTranslation()
- return (
- <DefinitionForm
- resourceType={resourceType}
- onSuccess={onSuccess}
- renderShell={({ fields, submitButton }) => (
- <>
- <SheetHeader className="h-13 py-3">{header}</SheetHeader>
- <div className="flex-1 overflow-y-auto p-4">{fields}</div>
- <SheetFooter>
- <Button type="button" variant="outline" size="sm" onClick={onCancel}>
- {t('admin.actions.cancel')}
- </Button>
- {submitButton}
- </SheetFooter>
- </>
- )}
- />
- )
-}
-
-// ---------------------------------------------------------------------------
-// Values view
-// ---------------------------------------------------------------------------
-
-interface ValuesViewProps {
- ownerType: CustomFieldOwnerType
- ownerId: string
- resourceLabel: string
- onAddDefinition: () => void
- highlightedDefinitionId: string | null
- onClearHighlight: () => void
- onClose: () => void
- header: ReactNode
-}
-
-function ValuesView({
- ownerType,
- ownerId,
- resourceLabel,
- onAddDefinition,
- highlightedDefinitionId,
- onClearHighlight,
- onClose,
- header,
-}: ValuesViewProps) {
- const { t } = useTranslation()
- const { data: definitionsResp, isLoading: defsLoading } = useCustomFieldDefinitions(ownerType)
- const { data: valuesResp, isLoading: valsLoading } = useCustomFields(ownerType, ownerId)
- const createValue = useCreateCustomField(ownerType, ownerId)
- const updateValue = useUpdateCustomField(ownerType, ownerId)
- const deleteValue = useDeleteCustomField(ownerType, ownerId)
-
- const definitions = useMemo(() => definitionsResp?.data ?? [], [definitionsResp])
- const values = useMemo(() => valuesResp?.data ?? [], [valuesResp])
-
- // Build a map: definitionId → value record
- const valueByDefinition = useMemo(
- () => new Map(values.map((v) => [v.custom_field_definition_id, v])),
- [values],
- )
-
- // Default values keyed by definition id
- const defaultFormValues = useMemo(() => {
- const next: Record<string, unknown> = {}
- for (const def of definitions) {
- next[def.id] = valueByDefinition.get(def.id)?.value ?? null
- }
- return next
- }, [definitions, valueByDefinition])
-
- const form = useForm<Record<string, unknown>>({
- defaultValues: defaultFormValues,
- })
-
- // Reset form when definitions or stored values change
- useEffect(() => {
- form.reset(defaultFormValues)
- }, [defaultFormValues, form])
-
- const isLoading = defsLoading || valsLoading
- const isSaving = createValue.isPending || updateValue.isPending || deleteValue.isPending
-
- if (isLoading) {
- return (
- <>
- <SheetHeader>{header}</SheetHeader>
- <div className="flex-1 overflow-y-auto p-4">
- <div className="flex flex-col gap-4">
- <Skeleton className="h-20 w-full rounded-md" />
- <Skeleton className="h-20 w-full rounded-md" />
- </div>
- </div>
- </>
- )
- }
-
- if (definitions.length === 0) {
- return (
- <>
- <SheetHeader>{header}</SheetHeader>
- <div className="flex-1 overflow-y-auto p-4">
- <Empty>
- <EmptyHeader>
- <EmptyTitle>
- {t('admin.components.custom_fields.empty_title', { resource: resourceLabel })}
- </EmptyTitle>
- <EmptyDescription>
- {t('admin.components.custom_fields.empty_description')}
- </EmptyDescription>
- </EmptyHeader>
- <EmptyContent>
- <Button type="button" size="sm" onClick={onAddDefinition}>
- <PlusIcon className="size-4" />
- {t('admin.components.custom_fields.create_definition')}
- </Button>
- </EmptyContent>
- </Empty>
- </div>
- </>
- )
- }
-
- const onSubmit = form.handleSubmit(async (formValues) => {
- const tasks: Promise<unknown>[] = []
- for (const def of definitions) {
- const submitted = formValues[def.id]
- const existing = valueByDefinition.get(def.id)
- const isEmpty = submitted === null || submitted === undefined || submitted === ''
-
- if (existing) {
- if (isEmpty) {
- tasks.push(deleteValue.mutateAsync(existing.id))
- } else if (submitted !== existing.value) {
- tasks.push(updateValue.mutateAsync({ id: existing.id, value: submitted }))
- }
- } else if (!isEmpty) {
- tasks.push(
- createValue.mutateAsync({
- custom_field_definition_id: def.id,
- value: submitted,
- }),
- )
- }
- }
-
- if (tasks.length === 0) {
- onClose()
- return
- }
-
- try {
- await Promise.all(tasks)
- toast.success(t('admin.components.custom_fields.values_saved'))
- onClose()
- } catch (err) {
- const message =
- err instanceof Error ? err.message : t('admin.components.custom_fields.values_save_failed')
- toast.error(message)
- }
- })
-
- return (
- <form
- onSubmit={(e) => {
- // The drawer is portaled out of the DOM but React bubbles synthetic
- // events through the React tree, so without this guard the outer
- // product form's onSubmit also fires. Hard-stop here.
- e.stopPropagation()
- onSubmit(e)
- }}
- className="flex h-full flex-col"
- >
- <SheetHeader>{header}</SheetHeader>
- <div className="flex-1 overflow-y-auto p-4">
- <div className="flex flex-col gap-5">
- {definitions.map((def) => {
- const isHighlighted = def.id === highlightedDefinitionId
- return (
- <Field
- key={def.id}
- className={
- isHighlighted
- ? 'rounded-md ring-2 ring-primary/40 ring-offset-2 transition-shadow'
- : undefined
- }
- >
- <div className="flex items-baseline justify-between">
- <FieldLabel htmlFor={`cf-${def.id}`}>
- <span className="font-medium">{def.label}</span>{' '}
- <code className="text-xs text-muted-foreground">
- {def.namespace}.{def.key}
- </code>
- </FieldLabel>
- {!def.storefront_visible && (
- <span className="text-xs text-muted-foreground">
- {t('admin.components.custom_fields.admin_only')}
- </span>
- )}
- </div>
- <ValueInput
- control={form.control}
- name={def.id}
- fieldType={def.field_type}
- id={`cf-${def.id}`}
- />
- </Field>
- )
- })}
- </div>
-
- <div className="mt-6 flex items-center justify-start border-t pt-4">
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={() => {
- onClearHighlight()
- onAddDefinition()
- }}
- >
- <PlusIcon className="size-4" />
- {t('admin.components.custom_fields.add_another_field')}
- </Button>
- </div>
- </div>
-
- <SheetFooter>
- <Button type="button" variant="outline" onClick={onClose}>
- {t('admin.actions.cancel')}
- </Button>
- <Button type="submit" disabled={isSaving}>
- {isSaving && <Loader2Icon className="size-4 animate-spin" />}
- {t('admin.actions.save')}
- </Button>
- </SheetFooter>
- </form>
- )
-}
-
-// ---------------------------------------------------------------------------
-// Definition created view
-// ---------------------------------------------------------------------------
-
-function DefinitionCreatedView({
- onAddAnother,
- onSetValues,
-}: {
- onAddAnother: () => void
- onSetValues: () => void
-}) {
- const { t } = useTranslation()
- return (
- <div className="flex flex-col items-center gap-4 py-8 text-center">
- <CheckCircle2Icon className="size-10 text-emerald-500" />
- <div className="flex flex-col gap-1">
- <p className="text-base font-medium">
- {t('admin.components.custom_fields.definition_created_title')}
- </p>
- <p className="text-sm text-muted-foreground">
- {t('admin.components.custom_fields.definition_created_hint')}
- </p>
- </div>
- <div className="mt-2 flex gap-2">
- <Button type="button" variant="outline" size="sm" onClick={onAddAnother}>
- <PlusIcon className="size-4" />
- {t('admin.components.custom_fields.create_another')}
- </Button>
- <Button type="button" size="sm" onClick={onSetValues}>
- {t('admin.components.custom_fields.set_values')}
- </Button>
- </div>
- </div>
- )
-}
diff --git a/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsx b/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsx
index 11b7884f7c..39f2705923 100644
--- a/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsx
+++ b/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsx
@@ -1,22 +1,32 @@
-// Inline custom-fields editor — generic-context shape, two providers.
+// Inline custom-fields editor — generic-context shape, two providers, two
+// predictable save modes (never on-blur). This is the single custom-fields
+// surface across the dashboard — products, categories, customers, orders.
//
// The card is purely presentational and reads everything from context. State
-// is dependency-injected by the provider above it: `FormBackedProvider` writes
-// to a parent product form (works pre-save), `ApiBackedProvider` reads/writes
-// the dedicated /custom_fields endpoints (commit-on-blur for existing
-// products). Same UI, swappable behaviour.
+// and persistence are dependency-injected by the provider above it:
+// - `FormBackedCustomFieldsProvider` keeps fields editable inline and writes
+// into a parent page form's `custom_fields[]` (products, categories) — values
+// persist only on that page's Save.
+// - `EditableApiCustomFieldsProvider` shows a read-only display with an Edit
+// button (orders, customers) and batches changed fields to the
+// /custom_fields endpoints on the card's own Save.
+// Neither persists on blur; the provider advertises its behaviour via `mode`.
+//
+// The empty state opens a sheet to create the first definition in place; on
+// success the sheet closes and the definitions query re-validates, so the card
+// re-renders with the new field ready to edit (no redirect to settings).
//
// Composition refs:
-// - state-context-interface: `{ state, actions, meta }`
+// - state-context-interface: `{ state, actions, meta, mode }`
// - state-decouple-implementation: card never touches the form or the SDK
-// - patterns-explicit-variants: two named providers, no `mode` prop
-//
-// See packages/dashboard/src/components/spree/custom-fields/ for the full
-// drawer that we're replacing; this lives next to it until call sites flip.
+// - patterns-explicit-variants: two named providers + a `mode` discriminator
+import { zodResolver } from '@hookform/resolvers/zod'
import type { CustomField, CustomFieldDefinition, CustomFieldOwnerType } from '@spree/admin-sdk'
import {
+ mapSpreeErrorsToForm,
useCreateCustomField,
+ useCreateCustomFieldDefinition,
useCustomFieldDefinitions,
useCustomFields,
useUpdateCustomField,
@@ -37,27 +47,30 @@ import {
FieldLabel,
Input,
RichTextEditor,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
Skeleton,
Switch,
Textarea,
} from '@spree/dashboard-ui'
import { Link, useParams } from '@tanstack/react-router'
-import i18n from 'i18next'
-import { TagIcon } from 'lucide-react'
-import {
- createContext,
- type ReactNode,
- useCallback,
- useContext,
- useEffect,
- useMemo,
- useRef,
- useState,
-} from 'react'
-import type { UseFormReturn } from 'react-hook-form'
+import { Loader2Icon, PencilIcon, PlusIcon, TagIcon } from 'lucide-react'
+import { createContext, type ReactNode, useCallback, useContext, useMemo, useState } from 'react'
+import { type UseFormReturn, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
-import type { CustomFieldFormValues, ProductFormValues } from '@/schemas/product'
+import { DefinitionFormFields } from '@/components/spree/custom-fields/definition-form'
+import {
+ CUSTOM_FIELD_DEFINITION_DEFAULTS,
+ type CustomFieldDefinitionFormValues,
+ customFieldDefinitionSchema,
+ customFieldDefinitionValuesToCreateParams,
+} from '@/schemas/custom-field-definition'
+import type { CustomFieldFormValues } from '@/schemas/product'
// ---------------------------------------------------------------------------
// Generic context interface — providers implement this, the card consumes it.
@@ -66,35 +79,53 @@ import type { CustomFieldFormValues, ProductFormValues } from '@/schemas/product
interface CustomFieldsState {
/** Draft values keyed by definition id. Always reflects what the UI shows. */
values: Record<string, unknown>
- /** Definition ids whose commit is currently in-flight (per-field spinner). */
- pending: Set<string>
}
interface CustomFieldsActions {
- /** Update the draft value for a definition. Doesn't necessarily persist. */
+ /** Update the draft value for a definition. Persistence is deferred to Save. */
setValue: (definitionId: string, value: unknown) => void
- /**
- * Persist the value for this definition. No-op for form-backed.
- *
- * `nextValue` lets immediate-save widgets (boolean toggle, JSON blur)
- * pass the just-changed value directly — React hasn't flushed `setValue`
- * by the time `commit()` runs back-to-back with `onChange()`, so reading
- * the draft from state would persist the previous value. When omitted,
- * the current draft from state is used (commit-on-blur from text/number
- * widgets, where the blur already saw the post-render state).
- */
- commit: (definitionId: string, nextValue?: unknown) => Promise<void>
}
interface CustomFieldsMeta {
definitions: CustomFieldDefinition[]
isLoading: boolean
+ /**
+ * Resource type the definitions belong to (e.g. `Spree::Product`,
+ * `Spree::Taxon`). Drives the in-place "create definition" sheet and its
+ * query invalidation — note this is the *definition* owner, which can differ
+ * from the value owner (`ownerType`), as for categories where definitions
+ * live under `Spree::Taxon` but values under `Spree::Category`.
+ */
+ resourceType: string
+ /** Plural, human-readable resource name for empty-state copy (e.g. "orders"). */
+ resourceLabel?: string
}
+/**
+ * How the card persists. Two surfaces, two predictable behaviours — never
+ * on-blur:
+ * - `form`: fields are always editable inline; nothing persists until the
+ * parent page form's Save (values live in `form.custom_fields[]`).
+ * - `editable`: read-only display by default; an Edit button reveals inputs and
+ * a card-level Save batches all changed values to the API, then returns to
+ * display. For pages with no page-wide form (orders, customers).
+ */
+type CustomFieldsMode =
+ | { kind: 'form' }
+ | {
+ kind: 'editable'
+ isEditing: boolean
+ saving: boolean
+ startEdit: () => void
+ cancel: () => void
+ save: () => void
+ }
+
interface CustomFieldsContextValue {
state: CustomFieldsState
actions: CustomFieldsActions
meta: CustomFieldsMeta
+ mode: CustomFieldsMode
}
const CustomFieldsContext = createContext<CustomFieldsContextValue | null>(null)
@@ -125,30 +156,46 @@ function valuesEqual(a: unknown, b: unknown): boolean {
}
// ---------------------------------------------------------------------------
-// Provider A: form-backed.
-// Reads from / writes to `form.values.custom_fields[]`. `commit` is a no-op —
-// the parent product form save flushes everything.
+// Provider A: form-backed (mode `form`).
+// Reads from / writes to `form.values.custom_fields[]` via `setValue`. Nothing
+// persists here — the parent page form's Save flushes everything.
// ---------------------------------------------------------------------------
-interface FormBackedProviderProps {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- form: UseFormReturn<ProductFormValues, any, any>
+// The minimal form shape the provider drives: any RHF form whose values carry a
+// `custom_fields[]` array. Both ProductFormValues and CategoryFormValues satisfy
+// this. The provider is generic over the concrete form type because RHF's
+// `UseFormReturn` is invariant — a wider form is NOT assignable to a narrowed
+// `UseFormReturn<CustomFieldsFormShape>`, so we infer `T` per call site instead
+// and narrow internally for the `custom_fields`-only field operations.
+export interface CustomFieldsFormShape {
+ custom_fields?: CustomFieldFormValues[]
+}
+
+interface FormBackedProviderProps<T extends CustomFieldsFormShape> {
+ form: UseFormReturn<T>
resourceType: string
+ /** Plural, human-readable resource name for empty-state copy. */
+ resourceLabel?: string
children: ReactNode
}
-export function FormBackedCustomFieldsProvider({
+export function FormBackedCustomFieldsProvider<T extends CustomFieldsFormShape>({
form,
resourceType,
+ resourceLabel,
children,
-}: FormBackedProviderProps) {
+}: FormBackedProviderProps<T>) {
+ // The provider only ever touches the `custom_fields` field; narrow to the
+ // shared shape so the field-path operations type-check uniformly regardless
+ // of the concrete form `T`. Memoized on `form` so it's a stable dependency.
+ const cfForm = useMemo(() => form as unknown as UseFormReturn<CustomFieldsFormShape>, [form])
const { data: definitionsResponse, isLoading } = useCustomFieldDefinitions(resourceType)
// Memoize against the fetched array's identity. Without this the `?? []`
// fallback returns a fresh array on every render, which propagates into the
// context value and triggers every consumer to re-render unnecessarily.
const definitions = useMemo(() => definitionsResponse?.data ?? [], [definitionsResponse?.data])
- const watchedCustomFields = form.watch('custom_fields') ?? []
+ const watchedCustomFields = cfForm.watch('custom_fields') ?? []
const values = useMemo<Record<string, unknown>>(() => {
const out: Record<string, unknown> = {}
watchedCustomFields.forEach((cf) => {
@@ -159,7 +206,7 @@ export function FormBackedCustomFieldsProvider({
const setValue = useCallback(
(definitionId: string, value: unknown) => {
- const current = form.getValues('custom_fields') ?? []
+ const current = cfForm.getValues('custom_fields') ?? []
const idx = current.findIndex((cf) => cf.custom_field_definition_id === definitionId)
const next: CustomFieldFormValues[] = [...current]
if (idx === -1) {
@@ -167,157 +214,187 @@ export function FormBackedCustomFieldsProvider({
} else {
next[idx] = { ...next[idx], value }
}
- form.setValue('custom_fields', next, { shouldDirty: true })
+ cfForm.setValue('custom_fields', next, { shouldDirty: true })
},
- [form],
+ [cfForm],
)
- // Form-backed scope persists via the parent form save — commit is just
- // surface for the API-backed twin so the card stays implementation-agnostic.
- const commit = useCallback(async () => {}, [])
-
const ctx = useMemo<CustomFieldsContextValue>(
() => ({
- state: { values, pending: new Set() },
- actions: { setValue, commit },
- meta: { definitions, isLoading },
+ state: { values },
+ actions: { setValue },
+ meta: { definitions, isLoading, resourceType, resourceLabel },
+ mode: { kind: 'form' },
}),
- [values, setValue, commit, definitions, isLoading],
+ [values, setValue, definitions, isLoading, resourceType, resourceLabel],
)
return <CustomFieldsContext value={ctx}>{children}</CustomFieldsContext>
}
// ---------------------------------------------------------------------------
-// Provider B: API-backed.
-// Reads via `useCustomFields`, writes via per-field create/update mutations on
-// commit. Local draft state lets the cell show the user's keystrokes without
-// flickering on every server round-trip.
+// Provider B: editable API-backed (display/edit mode).
+// Reads via `useCustomFields`. Default view is read-only; an explicit Edit
+// reveals inputs and a card-level Save batches all changed values to the API
+// (create or update per field, in parallel). No on-blur persistence — Save is
+// the only write. For pages with no page-wide form (orders, customers).
// ---------------------------------------------------------------------------
-interface ApiBackedProviderProps {
+interface EditableApiProviderProps {
ownerType: CustomFieldOwnerType
ownerId: string
resourceType: string
+ /** Plural, human-readable resource name for empty-state copy. */
+ resourceLabel?: string
children: ReactNode
}
-export function ApiBackedCustomFieldsProvider({
+export function EditableApiCustomFieldsProvider({
ownerType,
ownerId,
resourceType,
+ resourceLabel,
children,
-}: ApiBackedProviderProps) {
+}: EditableApiProviderProps) {
+ const { t } = useTranslation()
const { data: definitionsResponse, isLoading: defsLoading } =
useCustomFieldDefinitions(resourceType)
- const { data: valuesResponse, isLoading: valuesLoading } = useCustomFields(ownerType, ownerId)
+ const {
+ data: valuesResponse,
+ isLoading: valuesLoading,
+ refetch,
+ } = useCustomFields(ownerType, ownerId)
const create = useCreateCustomField(ownerType, ownerId)
const update = useUpdateCustomField(ownerType, ownerId)
- // Memoize against the fetched array's identity. Without this the `?? []`
- // fallback returns a fresh array on every render, the `useEffect` that
- // seeds `drafts` re-runs every render → setState → re-render loop →
- // "Maximum update depth exceeded".
+ // Memoize against the fetched array's identity so the seeding effect below
+ // doesn't re-run every render (→ setState loop → "Maximum update depth").
const definitions = useMemo(() => definitionsResponse?.data ?? [], [definitionsResponse?.data])
const savedValues = useMemo(() => valuesResponse?.data ?? [], [valuesResponse?.data])
- // Map definition id → existing CustomField record (for update by id) and to
- // the persisted value (the baseline against which `commit` decides whether
- // to call create or update).
+ // definition id → persisted CustomField record (for update-by-id + baseline).
const savedByDefinitionId = useMemo(() => {
const out = new Map<string, CustomField>()
- savedValues.forEach((cf) => {
- out.set(cf.custom_field_definition_id, cf)
- })
+ for (const cf of savedValues) out.set(cf.custom_field_definition_id, cf)
return out
}, [savedValues])
- // Local drafts let the user type freely without firing a request per
- // keystroke. Initialised from the persisted values; per-field commit flushes
- // back to the server. The card calls `commit` on blur for text inputs and
- // immediately for booleans.
- const [drafts, setDrafts] = useState<Record<string, unknown>>({})
- const [pending, setPending] = useState<Set<string>>(() => new Set())
-
- // Seed drafts whenever the saved values change (initial load + refetch).
- // Keys the user has actively edited (i.e. already in `drafts`) stay put.
- useEffect(() => {
- setDrafts((prev) => {
- const next: Record<string, unknown> = { ...prev }
- savedValues.forEach((cf) => {
- if (!(cf.custom_field_definition_id in next)) {
- next[cf.custom_field_definition_id] = cf.value
- }
- })
- return next
+ // The display value for every definition is the persisted value (drafts only
+ // exist while editing). Keyed by definition id so the card reads uniformly.
+ const savedDraft = useMemo(() => {
+ const out: Record<string, unknown> = {}
+ savedByDefinitionId.forEach((cf, defId) => {
+ out[defId] = cf.value
})
- }, [savedValues])
+ return out
+ }, [savedByDefinitionId])
+
+ const [isEditing, setIsEditing] = useState(false)
+ const [saving, setSaving] = useState(false)
+ // Drafts hold edits while in edit mode; null when not editing (display reads
+ // the persisted values directly, always fresh after a save's refetch).
+ const [drafts, setDrafts] = useState<Record<string, unknown> | null>(null)
+
+ const values = isEditing && drafts ? drafts : savedDraft
const setValue = useCallback((definitionId: string, value: unknown) => {
- setDrafts((prev) => ({ ...prev, [definitionId]: value }))
+ setDrafts((prev) => ({ ...(prev ?? {}), [definitionId]: value }))
}, [])
- const draftsRef = useRef(drafts)
- draftsRef.current = drafts
-
- // Local cache of records the merchant just created in this session. The
- // `useCustomFields` query needs a refetch round-trip before
- // `savedByDefinitionId` sees them, so a second blur on the same field
- // would otherwise re-enter the create branch and produce a duplicate.
- // Refilled on every save; the auth-backed mutation handles invalidation
- // so the cache merges cleanly when the refetch lands.
- const justSavedRef = useRef<Map<string, { id: string; value: unknown }>>(new Map())
-
- const commit = useCallback(
- async (definitionId: string, nextValue?: unknown) => {
- // Prefer the explicit `nextValue` (immediate-save widgets pass the
- // just-changed value directly because React hasn't flushed setDrafts
- // yet). Fall back to the current draft from state for commit-on-blur.
- const draft = nextValue === undefined ? draftsRef.current[definitionId] : nextValue
- const existing =
- savedByDefinitionId.get(definitionId) ?? justSavedRef.current.get(definitionId)
- const savedValue = existing?.value
- if (valuesEqual(draft, savedValue)) return // unchanged
-
- setPending((prev) => new Set(prev).add(definitionId))
- try {
- if (existing) {
- const updated = await update.mutateAsync({ id: existing.id, value: draft })
- justSavedRef.current.set(definitionId, { id: existing.id, value: updated.value })
- } else {
- const created = await create.mutateAsync({
- custom_field_definition_id: definitionId,
- value: draft,
- })
- justSavedRef.current.set(definitionId, { id: created.id, value: created.value })
- }
- } catch (err) {
- const message =
- err instanceof Error
- ? err.message
- : i18n.t('admin.components.custom_fields.errors.failed_to_save')
- toast.error(message)
- // Roll the draft back to the persisted value so the next render
- // matches the server's truth.
- setDrafts((prev) => ({ ...prev, [definitionId]: savedValue }))
- } finally {
- setPending((prev) => {
- const next = new Set(prev)
- next.delete(definitionId)
- return next
- })
+ const startEdit = useCallback(() => {
+ setDrafts({ ...savedDraft })
+ setIsEditing(true)
+ }, [savedDraft])
+
+ const cancel = useCallback(() => {
+ setDrafts(null)
+ setIsEditing(false)
+ }, [])
+
+ const save = useCallback(async () => {
+ const current = drafts ?? {}
+ // One task per definition whose draft differs from the persisted value,
+ // tagged with its definition so we can name failures back to the user.
+ const tasks: { def: CustomFieldDefinition; run: () => Promise<unknown> }[] = []
+ for (const def of definitions) {
+ const draft = current[def.id]
+ const existing = savedByDefinitionId.get(def.id)
+ if (valuesEqual(draft, existing?.value)) continue
+ tasks.push({
+ def,
+ run: existing
+ ? () => update.mutateAsync({ id: existing.id, value: draft })
+ : () => create.mutateAsync({ custom_field_definition_id: def.id, value: draft }),
+ })
+ }
+
+ if (tasks.length === 0) {
+ cancel()
+ return
+ }
+
+ setSaving(true)
+ try {
+ // allSettled (not all): a mid-batch failure must not orphan the fields
+ // that already persisted. Refetch unconditionally so the baseline matches
+ // the server, then report partial failures by field name.
+ const results = await Promise.allSettled(tasks.map((task) => task.run()))
+ await refetch()
+
+ const failed = tasks.filter((_, i) => results[i].status === 'rejected')
+ if (failed.length === 0) {
+ toast.success(t('admin.components.custom_fields.values_saved'))
+ setDrafts(null)
+ setIsEditing(false)
+ return
}
- },
- [create, update, savedByDefinitionId],
- )
+
+ // Some saved, some didn't. Keep edit mode with drafts intact so the user
+ // can retry — the refetched baseline means the succeeded fields now equal
+ // their persisted value, so a retry only re-sends the failures.
+ toast.error(
+ t('admin.components.custom_fields.values_save_partial_failed', {
+ fields: failed.map(({ def }) => def.label || def.key).join(', '),
+ }),
+ )
+ } catch (err) {
+ // refetch() itself failed (network) — the saves may still have landed.
+ const message =
+ err instanceof Error
+ ? err.message
+ : t('admin.components.custom_fields.errors.failed_to_save')
+ toast.error(message)
+ } finally {
+ setSaving(false)
+ }
+ }, [drafts, definitions, savedByDefinitionId, create, update, refetch, cancel, t])
const ctx = useMemo<CustomFieldsContextValue>(
() => ({
- state: { values: drafts, pending },
- actions: { setValue, commit },
- meta: { definitions, isLoading: defsLoading || valuesLoading },
+ state: { values },
+ actions: { setValue },
+ meta: {
+ definitions,
+ isLoading: defsLoading || valuesLoading,
+ resourceType,
+ resourceLabel,
+ },
+ mode: { kind: 'editable', isEditing, saving, startEdit, cancel, save },
}),
- [drafts, pending, setValue, commit, definitions, defsLoading, valuesLoading],
+ [
+ values,
+ setValue,
+ definitions,
+ defsLoading,
+ valuesLoading,
+ resourceType,
+ resourceLabel,
+ isEditing,
+ saving,
+ startEdit,
+ cancel,
+ save,
+ ],
)
return <CustomFieldsContext value={ctx}>{children}</CustomFieldsContext>
@@ -329,76 +406,335 @@ export function ApiBackedCustomFieldsProvider({
export function CustomFieldsInlineCard() {
const { t } = useTranslation()
- const { storeId } = useParams({ strict: false }) as { storeId: string }
+ const [createOpen, setCreateOpen] = useState(false)
const {
- state: { values, pending },
- actions: { setValue, commit },
- meta: { definitions, isLoading },
+ meta: { isLoading, definitions, resourceType, resourceLabel },
+ mode,
} = useCustomFieldsContext()
+ // Form mode always edits inline; editable mode edits only while `isEditing`.
+ const editing = mode.kind === 'form' || mode.isEditing
+ const hasDefinitions = definitions.length > 0
+ const openCreate = useCallback(() => setCreateOpen(true), [])
+
return (
<Card>
- <CardHeader>
- <CardTitle>{t('admin.pages.products.section_custom_fields')}</CardTitle>
+ <CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0">
+ <CardTitle>{t('admin.components.custom_fields.section_title')}</CardTitle>
+ {!isLoading && hasDefinitions && <EditableHeaderActions />}
</CardHeader>
<CardContent>
{isLoading ? (
- <div className="flex flex-col gap-2">
- <Skeleton className="h-4 w-3/4" />
- <Skeleton className="h-4 w-1/2" />
- </div>
- ) : definitions.length === 0 ? (
- <Empty className="border-0 p-0">
- <EmptyHeader>
- <EmptyMedia variant="icon">
- <TagIcon />
- </EmptyMedia>
- <EmptyTitle>{t('admin.products.custom_fields.empty_title')}</EmptyTitle>
- <EmptyDescription>
- {t('admin.products.custom_fields.empty_description')}
- </EmptyDescription>
- </EmptyHeader>
- <EmptyContent>
- <Button asChild type="button" variant="outline" size="sm">
- <Link to="/$storeId/settings/custom-field-definitions" params={{ storeId }}>
- {t('admin.products.custom_fields.empty_cta')}
- </Link>
- </Button>
- </EmptyContent>
- </Empty>
+ <LoadingRows />
+ ) : !hasDefinitions ? (
+ <CustomFieldsEmptyState onSetUp={openCreate} />
+ ) : editing ? (
+ <FieldsEditor onSetUp={openCreate} />
) : (
- <div className="flex flex-col gap-4">
- {definitions.map((def) => (
- <CustomFieldRow
- key={def.id}
- definition={def}
- value={values[def.id]}
- pending={pending.has(def.id)}
- onChange={(next) => setValue(def.id, next)}
- onCommit={(nextValue) => commit(def.id, nextValue)}
- />
- ))}
- </div>
+ <FieldsDisplay />
)}
</CardContent>
+
+ <CreateDefinitionSheet
+ open={createOpen}
+ onOpenChange={setCreateOpen}
+ resourceType={resourceType}
+ resourceLabel={resourceLabel}
+ />
</Card>
)
}
+// Edit / Cancel+Save buttons — only rendered in editable mode. Reads the mode
+// off context so the card body stays a thin selector.
+function EditableHeaderActions() {
+ const { t } = useTranslation()
+ const { mode } = useCustomFieldsContext()
+ if (mode.kind !== 'editable') return null
+
+ if (!mode.isEditing) {
+ return (
+ <Button type="button" variant="outline" size="sm" onClick={mode.startEdit}>
+ <PencilIcon className="size-4" />
+ {t('admin.actions.edit')}
+ </Button>
+ )
+ }
+
+ return (
+ <div className="flex items-center gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={mode.cancel}
+ disabled={mode.saving}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button type="button" size="sm" onClick={mode.save} disabled={mode.saving}>
+ {mode.saving && <Loader2Icon className="size-4 animate-spin" />}
+ {t('admin.actions.save')}
+ </Button>
+ </div>
+ )
+}
+
+function LoadingRows() {
+ return (
+ <div className="flex flex-col gap-2">
+ <Skeleton className="h-4 w-3/4" />
+ <Skeleton className="h-4 w-1/2" />
+ </div>
+ )
+}
+
+// No definitions yet: create one in place (sheet) or jump to the settings list.
+function CustomFieldsEmptyState({ onSetUp }: { onSetUp: () => void }) {
+ const { t } = useTranslation()
+ const { storeId } = useParams({ strict: false }) as { storeId: string }
+ return (
+ <Empty className="border-0 p-0">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <TagIcon />
+ </EmptyMedia>
+ <EmptyTitle>{t('admin.components.custom_fields.empty_title')}</EmptyTitle>
+ <EmptyDescription>{t('admin.components.custom_fields.empty_description')}</EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent className="gap-1">
+ <Button type="button" variant="outline" size="sm" onClick={onSetUp}>
+ <PlusIcon className="size-4" />
+ {t('admin.components.custom_fields.set_up')}
+ </Button>
+ <Button asChild type="button" variant="link" size="sm">
+ <Link to="/$storeId/settings/custom-field-definitions" params={{ storeId }}>
+ {t('admin.components.custom_fields.manage_in_settings')}
+ </Link>
+ </Button>
+ </EmptyContent>
+ </Empty>
+ )
+}
+
+// Editable rows. In editable mode a footer lets the user define another field
+// in place; form mode persists via the page's own Save, so no footer there.
+function FieldsEditor({ onSetUp }: { onSetUp: () => void }) {
+ const { t } = useTranslation()
+ const {
+ state: { values },
+ actions: { setValue },
+ meta: { definitions },
+ mode,
+ } = useCustomFieldsContext()
+
+ return (
+ <div className="flex flex-col gap-4">
+ {definitions.map((def) => (
+ <CustomFieldRow
+ key={def.id}
+ definition={def}
+ value={values[def.id]}
+ onChange={(next) => setValue(def.id, next)}
+ />
+ ))}
+ {mode.kind === 'editable' && (
+ <div className="border-t pt-3">
+ <Button type="button" variant="ghost" size="sm" onClick={onSetUp}>
+ <PlusIcon className="size-4" />
+ {t('admin.components.custom_fields.set_up')}
+ </Button>
+ </div>
+ )}
+ </div>
+ )
+}
+
+// Read-only value grid (editable mode, not editing).
+function FieldsDisplay() {
+ const {
+ state: { values },
+ meta: { definitions },
+ } = useCustomFieldsContext()
+ return (
+ <dl className="grid grid-cols-[minmax(140px,1fr)_2fr] gap-x-4 gap-y-2 text-sm">
+ {definitions.map((def) => (
+ <CustomFieldDisplayRow key={def.id} definition={def} value={values[def.id]} />
+ ))}
+ </dl>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Read-only display row (editable mode, not editing). Shows the formatted value
+// or an em-dash placeholder.
+// ---------------------------------------------------------------------------
+
+function CustomFieldDisplayRow({
+ definition,
+ value,
+}: {
+ definition: CustomFieldDefinition
+ value: unknown
+}) {
+ const { t } = useTranslation()
+ const friendlyLabel = definition.label || definition.key
+ const technicalKey = `${definition.namespace}.${definition.key}`
+
+ return (
+ <>
+ <dt className="font-medium text-muted-foreground" title={technicalKey}>
+ {friendlyLabel}
+ </dt>
+ <dd className="break-words text-foreground/90">
+ {formatDisplayValue(value, definition.field_type, t)}
+ </dd>
+ </>
+ )
+}
+
+// Compact, read-only rendering of a stored value for the display grid.
+function formatDisplayValue(value: unknown, fieldType: string, t: (key: string) => string): string {
+ const empty = t('admin.common.empty_value')
+ if (value === null || value === undefined || value === '') return empty
+ if (fieldType === 'boolean') return value ? t('admin.common.yes') : t('admin.common.no')
+ if (fieldType === 'rich_text' && typeof value === 'string') {
+ // Plain-text preview of HTML. DOMParser handles nested/malformed tags
+ // correctly — a single-pass regex strip can leak tags via patterns like
+ // `<scr<script>ipt>` (CodeQL js/incomplete-multi-character-sanitization).
+ const text = new DOMParser().parseFromString(value, 'text/html').body.textContent ?? ''
+ return text.trim() || empty
+ }
+ if (fieldType === 'json') return typeof value === 'string' ? value : JSON.stringify(value)
+ return String(value)
+}
+
+// ---------------------------------------------------------------------------
+// In-place create-definition sheet. Pre-fills (and hides) the resource type —
+// the card already knows its owner. On success it closes; the create mutation
+// invalidates the definitions query so the card re-renders with the new field
+// ready to edit. Lives inside the card's <Card> but renders into a portal, so
+// the parent product/category <form> never wraps it; the submit handler still
+// stops propagation defensively (React bubbles synthetic events through the
+// component tree even across the portal).
+// ---------------------------------------------------------------------------
+
+interface CreateDefinitionSheetProps {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ resourceType: string
+ resourceLabel?: string
+}
+
+function CreateDefinitionSheet({
+ open,
+ onOpenChange,
+ resourceType,
+ resourceLabel,
+}: CreateDefinitionSheetProps) {
+ const { t } = useTranslation()
+ const create = useCreateCustomFieldDefinition(resourceType)
+ const form = useForm<CustomFieldDefinitionFormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(customFieldDefinitionSchema) as any,
+ defaultValues: { ...CUSTOM_FIELD_DEFINITION_DEFAULTS, resource_type: resourceType },
+ })
+
+ const resetForm = useCallback(
+ () => form.reset({ ...CUSTOM_FIELD_DEFINITION_DEFAULTS, resource_type: resourceType }),
+ [form, resourceType],
+ )
+
+ async function onSubmit(values: CustomFieldDefinitionFormValues) {
+ try {
+ await create.mutateAsync(
+ customFieldDefinitionValuesToCreateParams({ ...values, resource_type: resourceType }),
+ )
+ resetForm()
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) {
+ form.setError('root', {
+ type: 'server',
+ message: err instanceof Error ? err.message : t('admin.errors.unexpected'),
+ })
+ }
+ }
+ }
+
+ return (
+ <Sheet
+ open={open}
+ onOpenChange={(next) => {
+ if (!next) resetForm()
+ onOpenChange(next)
+ }}
+ >
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>{t('admin.components.custom_fields.new_definition_title')}</SheetTitle>
+ <SheetDescription>
+ {t('admin.components.custom_fields.new_definition_description', {
+ resource: resourceLabel ?? t('admin.components.custom_fields.default_resource'),
+ })}
+ </SheetDescription>
+ </SheetHeader>
+ <form
+ // The sheet portals to document.body (outside the React root), but
+ // React still bubbles the synthetic submit up the fiber tree, so a
+ // parent product/category <form>'s onSubmit would also fire. Stop the
+ // synthetic bubble — but in the BUBBLE phase, AFTER handleSubmit runs.
+ // A capture-phase stopPropagation kills native propagation before it
+ // reaches React's root-delegated listener, so handleSubmit (and its
+ // preventDefault) never runs and the browser does a native page reload.
+ onSubmit={(e) => {
+ e.stopPropagation()
+ form.handleSubmit(onSubmit)(e)
+ }}
+ className="flex min-h-0 flex-1 flex-col"
+ >
+ <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
+ <DefinitionFormFields form={form} />
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ // Reset through the same path as the Sheet's onOpenChange wrapper
+ // so reopening doesn't show stale input or server errors.
+ onClick={() => {
+ resetForm()
+ onOpenChange(false)
+ }}
+ disabled={create.isPending}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button type="submit" size="sm" disabled={create.isPending}>
+ {create.isPending && <Loader2Icon className="size-4 animate-spin" />}
+ {t('admin.custom_field_definitions.create_label')}
+ </Button>
+ </SheetFooter>
+ </form>
+ </SheetContent>
+ </Sheet>
+ )
+}
+
// ---------------------------------------------------------------------------
-// Per-definition input. Picks the right widget by field_type and routes the
-// commit moment appropriately (immediate for boolean, on-blur for text/number).
+// Per-definition input row. Picks the widget by field_type. Edits flow to the
+// draft via onChange only — persistence is deferred to the page form's Save
+// (form mode) or the card's Save (editable mode). No on-blur/immediate commit.
// ---------------------------------------------------------------------------
interface CustomFieldRowProps {
definition: CustomFieldDefinition
value: unknown
- pending: boolean
onChange: (value: unknown) => void
- onCommit: (nextValue?: unknown) => void | Promise<void>
}
-function CustomFieldRow({ definition, value, pending, onChange, onCommit }: CustomFieldRowProps) {
+function CustomFieldRow({ definition, value, onChange }: CustomFieldRowProps) {
const inputId = `custom-field-${definition.id}`
const friendlyLabel = definition.label || definition.key
// The `namespace.key` identifier matters to developers / API consumers but
@@ -407,20 +743,39 @@ function CustomFieldRow({ definition, value, pending, onChange, onCommit }: Cust
// label, not rendered as inline copy.
const technicalKey = `${definition.namespace}.${definition.key}`
+ const widget = (
+ <CustomFieldWidget
+ id={inputId}
+ ariaLabel={friendlyLabel}
+ fieldType={definition.field_type}
+ value={value}
+ onChange={onChange}
+ />
+ )
+
+ // Booleans read as a horizontal label-left / switch-right row (matching the
+ // definition form and Shopify/Saleor). The vertical `Field` layout forces
+ // `*:w-full` on its children, which would stretch the compact switch across
+ // the row — so the toggle gets its own justified wrapper instead.
+ if (definition.field_type === 'boolean') {
+ return (
+ <Field>
+ <div className="flex items-center justify-between gap-4">
+ <FieldLabel htmlFor={inputId} title={technicalKey} className="cursor-pointer">
+ {friendlyLabel}
+ </FieldLabel>
+ {widget}
+ </div>
+ </Field>
+ )
+ }
+
return (
<Field>
- <FieldLabel htmlFor={inputId} title={technicalKey} className="flex items-baseline gap-2">
- <span>{friendlyLabel}</span>
- {pending && <span className="text-xs text-muted-foreground">…</span>}
+ <FieldLabel htmlFor={inputId} title={technicalKey}>
+ {friendlyLabel}
</FieldLabel>
- <CustomFieldWidget
- id={inputId}
- ariaLabel={friendlyLabel}
- fieldType={definition.field_type}
- value={value}
- onChange={onChange}
- onCommit={onCommit}
- />
+ {widget}
</Field>
)
}
@@ -431,37 +786,17 @@ interface CustomFieldWidgetProps {
fieldType: string
value: unknown
onChange: (value: unknown) => void
- /**
- * Persist the value. Accepts an optional `nextValue` for immediate-save
- * widgets (boolean, JSON-on-blur) where onChange + onCommit run back to
- * back — React hasn't flushed the draft state yet, so re-reading from
- * state would persist the previous value.
- */
- onCommit: (nextValue?: unknown) => void | Promise<void>
}
-function CustomFieldWidget({
- id,
- ariaLabel,
- fieldType,
- value,
- onChange,
- onCommit,
-}: CustomFieldWidgetProps) {
+function CustomFieldWidget({ id, ariaLabel, fieldType, value, onChange }: CustomFieldWidgetProps) {
switch (fieldType) {
case 'short_text':
return (
- // Pass the just-blurred value into commit explicitly. React 18's
- // auto-batching can keep `setDrafts` pending across a synchronous
- // onChange→onBlur sequence (Tab on the same JS tick as the final
- // keystroke), so `draftsRef.current` may be stale when commit
- // reads it. The DOM input is the source of truth — feed it through.
<Input
id={id}
aria-label={ariaLabel}
value={(value as string | null | undefined) ?? ''}
onChange={(e) => onChange(e.target.value)}
- onBlur={(e) => onCommit(e.target.value)}
/>
)
case 'long_text':
@@ -472,20 +807,15 @@ function CustomFieldWidget({
rows={4}
value={(value as string | null | undefined) ?? ''}
onChange={(e) => onChange(e.target.value)}
- onBlur={(e) => onCommit(e.target.value)}
/>
)
case 'rich_text':
- // RichTextEditor's onBlur doesn't surface the current HTML — track
- // the latest value through onChange and pass it on blur so commit
- // doesn't rely on a possibly-stale draftsRef.
return (
- <RichTextWidget
+ <RichTextEditor
id={id}
ariaLabel={ariaLabel}
value={(value as string | null | undefined) ?? ''}
- onChange={onChange}
- onCommit={onCommit}
+ onChange={(html: string) => onChange(html)}
/>
)
case 'number':
@@ -505,24 +835,13 @@ function CustomFieldWidget({
// `<input type="number">` sanitizes invalid input to "" in most
// browsers, but Safari and some locale-quirk paths can yield a
// non-empty unparseable string ("1,5" in de-DE). Coercing with
- // Number() in those cases produces NaN, which then flows into
- // form state and through the API. Hold the previous value
- // instead so a transient bad keystroke can't corrupt state;
- // when the user backspaces back to "" we fall through to null.
+ // Number() there produces NaN, which would flow into form state and
+ // the API. Hold the previous value instead so a transient bad
+ // keystroke can't corrupt state; backspacing to "" falls to null.
const parsed = Number(v)
if (Number.isNaN(parsed)) return
onChange(parsed)
}}
- onBlur={(e) => {
- const v = e.target.value
- if (v === '') {
- onCommit(null)
- return
- }
- const parsed = Number(v)
- if (Number.isNaN(parsed)) return // hold prior commit
- onCommit(parsed)
- }}
/>
)
case 'boolean':
@@ -531,12 +850,7 @@ function CustomFieldWidget({
id={id}
aria-label={ariaLabel}
checked={Boolean(value)}
- onCheckedChange={(checked) => {
- onChange(checked)
- // Booleans commit immediately — there's no "typing" phase.
- // Pass the next value so commit doesn't re-read stale draft state.
- void onCommit(checked)
- }}
+ onCheckedChange={(checked) => onChange(checked)}
/>
)
case 'json':
@@ -551,22 +865,19 @@ function CustomFieldWidget({
}
onChange={(e) => onChange(e.target.value)}
onBlur={(e) => {
+ // Normalize on blur (no persistence): parse JSON so the draft holds
+ // the canonical value the API expects. Leave an unparseable string
+ // as-is — Save will surface the server's validation error.
const raw = e.target.value.trim()
- // Pre-parse so we can pass the canonical value to commit(). React
- // hasn't flushed onChange's setDrafts yet, so re-reading from
- // state would persist the pre-parse string.
- let parsed: unknown
if (!raw) {
- parsed = null
- } else {
- try {
- parsed = JSON.parse(raw)
- } catch {
- parsed = raw // leave raw string; commit will surface server error
- }
+ onChange(null)
+ return
+ }
+ try {
+ onChange(JSON.parse(raw))
+ } catch {
+ onChange(raw)
}
- onChange(parsed)
- void onCommit(parsed)
}}
/>
)
@@ -574,34 +885,3 @@ function CustomFieldWidget({
return null
}
}
-
-// Tracks the latest HTML from onChange so the blur path can pass it
-// explicitly to commit, avoiding draftsRef staleness in synchronous
-// onChange→onBlur sequences.
-function RichTextWidget({
- id,
- ariaLabel,
- value,
- onChange,
- onCommit,
-}: {
- id?: string
- ariaLabel?: string
- value: string
- onChange: (value: unknown) => void
- onCommit: (nextValue?: unknown) => void | Promise<void>
-}) {
- const latestRef = useRef(value)
- return (
- <RichTextEditor
- id={id}
- ariaLabel={ariaLabel}
- value={value}
- onChange={(html) => {
- latestRef.current = html
- onChange(html)
- }}
- onBlur={() => onCommit(latestRef.current)}
- />
- )
-}
diff --git a/packages/dashboard/src/components/spree/custom-fields/definition-form.tsx b/packages/dashboard/src/components/spree/custom-fields/definition-form.tsx
index 05b72dd470..d4566e726e 100644
--- a/packages/dashboard/src/components/spree/custom-fields/definition-form.tsx
+++ b/packages/dashboard/src/components/spree/custom-fields/definition-form.tsx
@@ -1,7 +1,4 @@
-import { zodResolver } from '@hookform/resolvers/zod'
-import { mapSpreeErrorsToForm, useCreateCustomFieldDefinition } from '@spree/dashboard-core'
import {
- Button,
Field,
FieldError,
FieldLabel,
@@ -13,30 +10,23 @@ import {
SelectValue,
Switch,
} from '@spree/dashboard-ui'
-import { Loader2Icon } from 'lucide-react'
-import type { ReactNode } from 'react'
-import { Controller, type UseFormReturn, useForm } from 'react-hook-form'
+import { Controller, type UseFormReturn } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import {
- CUSTOM_FIELD_DEFINITION_DEFAULTS,
type CustomFieldDefinitionFormValues,
- customFieldDefinitionSchema,
- customFieldDefinitionValuesToCreateParams,
DEFAULT_RESOURCE_TYPES,
FIELD_TYPES,
fieldTypeLabel,
resourceTypeLabel,
} from '@/schemas/custom-field-definition'
-// Re-export so existing callers (drawer) don't have to chase paths.
-export type { CustomFieldDefinitionFormValues as DefinitionFormValues }
-
interface DefinitionFormFieldsProps {
form: UseFormReturn<CustomFieldDefinitionFormValues>
/**
* When true, the `resource_type` picker is rendered. Off by default — the
- * drawer creates definitions for a known owner and pre-fills the resource,
- * but the settings page (where the user picks from a list) opts in.
+ * inline create sheet (`CreateDefinitionSheet`) creates definitions for a
+ * known owner and pre-fills/hides the resource, but the settings page (where
+ * the user picks from a list) opts in.
*/
showResourceType?: boolean
/**
@@ -56,7 +46,8 @@ interface DefinitionFormFieldsProps {
* `<form>` element and submit handler — this just renders the controls.
*
* Used by:
- * - `<DefinitionForm>` below (drawer's inline create flow, owner pre-set).
+ * - `CreateDefinitionSheet` in custom-fields-inline.tsx (the inline card's
+ * empty-state create flow; resource type pre-set and hidden).
* - The Settings → Custom field definitions page (create + edit sheets).
*/
export function DefinitionFormFields({
@@ -223,79 +214,3 @@ export function DefinitionFormFields({
</div>
)
}
-
-interface DefinitionFormProps {
- resourceType: string
- /** Default namespace. */
- defaultNamespace?: string
- onSuccess: (definitionId: string) => void
- /**
- * Render-prop that builds the surrounding chrome (header/footer/etc) AROUND
- * the form fields and the submit button. The submit button must stay inside
- * the same `<form>` as the inputs, so the consumer composes layout, not the
- * form element itself.
- */
- renderShell: (parts: { fields: ReactNode; submitButton: ReactNode }) => ReactNode
-}
-
-/**
- * Drawer-style create form. Owns its own `useForm` + create mutation, and
- * pre-fills `resource_type` from the owning record (so the resource picker
- * is hidden — the drawer only ever creates fields for one specific owner).
- */
-export function DefinitionForm({
- resourceType,
- defaultNamespace = 'custom',
- onSuccess,
- renderShell,
-}: DefinitionFormProps) {
- const { t } = useTranslation()
- const create = useCreateCustomFieldDefinition(resourceType)
-
- const form = useForm<CustomFieldDefinitionFormValues>({
- resolver: zodResolver(customFieldDefinitionSchema),
- defaultValues: {
- ...CUSTOM_FIELD_DEFINITION_DEFAULTS,
- namespace: defaultNamespace,
- resource_type: resourceType,
- },
- })
-
- const onSubmit = async (values: CustomFieldDefinitionFormValues) => {
- try {
- const result = await create.mutateAsync(
- customFieldDefinitionValuesToCreateParams({ ...values, resource_type: resourceType }),
- )
- onSuccess(result.id)
- } catch (err) {
- // 422s map to inline field errors; anything else (network, 5xx) lands
- // on the form-level `root` so the user gets feedback inside the sheet.
- if (!mapSpreeErrorsToForm(err, form.setError)) {
- form.setError('root', {
- type: 'server',
- message: err instanceof Error ? err.message : t('admin.errors.unexpected'),
- })
- }
- }
- }
-
- const submitButton = (
- <Button type="submit" size="sm" disabled={create.isPending}>
- {create.isPending && <Loader2Icon className="size-4 animate-spin" />}
- {t('admin.custom_field_definitions.create_label')}
- </Button>
- )
-
- return (
- <form
- onSubmit={form.handleSubmit(onSubmit)}
- className="flex h-full flex-col"
- // The drawer is portaled out of the DOM but React bubbles synthetic
- // events through the React tree, so without this guard the outer
- // product form's onSubmit also fires. Hard-stop here.
- onSubmitCapture={(e) => e.stopPropagation()}
- >
- {renderShell({ fields: <DefinitionFormFields form={form} />, submitButton })}
- </form>
- )
-}
diff --git a/packages/dashboard/src/components/spree/custom-fields/value-input.tsx b/packages/dashboard/src/components/spree/custom-fields/value-input.tsx
deleted file mode 100644
index 8c4cf7a195..0000000000
--- a/packages/dashboard/src/components/spree/custom-fields/value-input.tsx
+++ /dev/null
@@ -1,101 +0,0 @@
-import { useTranslation } from '@spree/dashboard-core'
-import { Input, RichTextEditor, Switch, Textarea } from '@spree/dashboard-ui'
-import { type Control, Controller } from 'react-hook-form'
-
-type FieldType = 'short_text' | 'long_text' | 'rich_text' | 'number' | 'boolean' | 'json'
-
-interface ValueInputProps {
- control: Control<Record<string, unknown>>
- name: string
- fieldType: FieldType
- id?: string
-}
-
-export function ValueInput({ control, name, fieldType, id }: ValueInputProps) {
- const { t } = useTranslation()
- return (
- <Controller
- name={name}
- control={control}
- render={({ field }) => {
- switch (fieldType) {
- case 'short_text':
- return (
- <Input
- id={id}
- value={(field.value as string | null | undefined) ?? ''}
- onChange={field.onChange}
- onBlur={field.onBlur}
- />
- )
- case 'long_text':
- return (
- <Textarea
- id={id}
- rows={4}
- value={(field.value as string | null | undefined) ?? ''}
- onChange={field.onChange}
- onBlur={field.onBlur}
- />
- )
- case 'rich_text':
- return (
- <RichTextEditor
- value={(field.value as string | null | undefined) ?? ''}
- onChange={field.onChange}
- />
- )
- case 'number':
- return (
- <Input
- id={id}
- type="number"
- step="any"
- value={field.value === null || field.value === undefined ? '' : String(field.value)}
- onChange={(e) => {
- const v = e.target.value
- field.onChange(v === '' ? null : Number(v))
- }}
- onBlur={field.onBlur}
- />
- )
- case 'boolean':
- return (
- <Switch id={id} checked={Boolean(field.value)} onCheckedChange={field.onChange} />
- )
- case 'json':
- return (
- <Textarea
- id={id}
- rows={6}
- className="font-mono text-xs"
- placeholder={t('admin.components.custom_fields.json_placeholder')}
- value={
- field.value === null || field.value === undefined
- ? ''
- : typeof field.value === 'string'
- ? field.value
- : JSON.stringify(field.value, null, 2)
- }
- onChange={(e) => field.onChange(e.target.value)}
- onBlur={(e) => {
- field.onBlur()
- // Try to parse on blur so the form holds an object, not a string
- const v = e.target.value.trim()
- if (!v) {
- field.onChange(null)
- return
- }
- try {
- field.onChange(JSON.parse(v))
- } catch {
- // leave as raw string; submit will surface the server error
- }
- }}
- />
- )
- }
- }}
- />
- )
-}
diff --git a/packages/dashboard/src/components/spree/products/option-type-translations-dialog.tsx b/packages/dashboard/src/components/spree/products/option-type-translations-dialog.tsx
deleted file mode 100644
index 7fbf7e9a7a..0000000000
--- a/packages/dashboard/src/components/spree/products/option-type-translations-dialog.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import type { TranslatableField } from '@spree/admin-sdk'
-import { useTranslation } from 'react-i18next'
-import { ResourceTranslationsDialog } from '@/components/spree/translations/resource-translations-dialog'
-import { useOptionTypeTranslations } from '@/hooks/use-translations'
-
-interface OptionTypeTranslationsDialogProps {
- optionTypeId: string
- open: boolean
- onOpenChange: (open: boolean) => void
-}
-
-/**
- * Option type translations editor — a thin adapter over the generic
- * <ResourceTranslationsDialog>. Fetches the option type's translation matrix
- * with its option values nested under `children`, so the dialog renders the
- * type and all its values as rows and saves them in one batch.
- */
-export function OptionTypeTranslationsDialog({
- optionTypeId,
- open,
- onOpenChange,
-}: OptionTypeTranslationsDialogProps) {
- const { t } = useTranslation()
- const { data, isLoading, isError, refetch } = useOptionTypeTranslations(optionTypeId)
-
- const fieldLabel = (resourceType: string, field: TranslatableField) =>
- t([`admin.fields.${resourceType}.${field.key}.label`, `admin.fields.${field.key}.label`], {
- defaultValue: field.key,
- })
-
- return (
- <ResourceTranslationsDialog
- open={open}
- onOpenChange={onOpenChange}
- data={data}
- isLoading={isLoading}
- isError={isError}
- fieldLabel={fieldLabel}
- onSaved={() => refetch()}
- />
- )
-}
diff --git a/packages/dashboard/src/components/spree/products/product-translations-dialog.tsx b/packages/dashboard/src/components/spree/products/product-translations-dialog.tsx
deleted file mode 100644
index be79242709..0000000000
--- a/packages/dashboard/src/components/spree/products/product-translations-dialog.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import type { TranslatableField } from '@spree/admin-sdk'
-import { useTranslation } from 'react-i18next'
-import { ResourceTranslationsDialog } from '@/components/spree/translations/resource-translations-dialog'
-import { useProductTranslations } from '@/hooks/use-translations'
-
-interface ProductTranslationsDialogProps {
- productId: string
- open: boolean
- onOpenChange: (open: boolean) => void
-}
-
-/**
- * Product translations editor — a thin adapter over the generic
- * <ResourceTranslationsDialog>: supplies the product's translation matrix and a
- * product-scoped field-label resolver. The dialog handles the grid, locale
- * switching, and the batched save.
- */
-export function ProductTranslationsDialog({
- productId,
- open,
- onOpenChange,
-}: ProductTranslationsDialogProps) {
- const { t } = useTranslation()
- const { data, isLoading, isError, refetch } = useProductTranslations(productId)
-
- const fieldLabel = (_resourceType: string, field: TranslatableField) =>
- t([`admin.fields.product.${field.key}.label`, `admin.fields.${field.key}.label`], {
- defaultValue: field.key,
- })
-
- return (
- <ResourceTranslationsDialog
- open={open}
- onOpenChange={onOpenChange}
- data={data}
- isLoading={isLoading}
- isError={isError}
- fieldLabel={fieldLabel}
- onSaved={() => refetch()}
- />
- )
-}
diff --git a/packages/dashboard/src/components/spree/products/product-translations-card.tsx b/packages/dashboard/src/components/spree/translations/resource-translations-card.tsx
similarity index 56%
rename from packages/dashboard/src/components/spree/products/product-translations-card.tsx
rename to packages/dashboard/src/components/spree/translations/resource-translations-card.tsx
index d66013caa3..76816703db 100644
--- a/packages/dashboard/src/components/spree/products/product-translations-card.tsx
+++ b/packages/dashboard/src/components/spree/translations/resource-translations-card.tsx
@@ -2,18 +2,30 @@ import { Button, Card, CardContent, CardHeader, CardTitle } from '@spree/dashboa
import { LanguagesIcon } from 'lucide-react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { ProductTranslationsDialog } from '@/components/spree/products/product-translations-dialog'
-import { useProductTranslations } from '@/hooks/use-translations'
+import { ResourceTranslationsDialog } from '@/components/spree/translations/resource-translations-dialog'
+import { type TranslatableResourceType, useResourceTranslations } from '@/hooks/use-translations'
+
+interface ResourceTranslationsCardProps {
+ /** Public resource token, e.g. `product`, `category`, `option_type`. */
+ resourceType: TranslatableResourceType
+ /** Prefixed id of the resource being translated. */
+ resourceId: string
+}
/**
- * Launcher card for the full-page translations editor. Shows how many target
- * locales the product is translated into and opens the spreadsheet dialog. The
- * editing itself lives in <ProductTranslationsDialog>, not inline here.
+ * Launcher card for the full-page translations editor — works for any
+ * translatable resource. Shows how many target locales the resource is
+ * translated into and opens the editor dialog. Both the card and the dialog are
+ * resource-agnostic: pass a `resourceType` token and an id, no per-resource
+ * adapter needed.
*/
-export function ProductTranslationsCard({ productId }: { productId: string }) {
+export function ResourceTranslationsCard({
+ resourceType,
+ resourceId,
+}: ResourceTranslationsCardProps) {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
- const { data } = useProductTranslations(productId)
+ const { data } = useResourceTranslations(resourceType, resourceId)
const targetLocales = data ? data.supported_locales.filter((l) => l !== data.default_locale) : []
const translatedCount = targetLocales.filter(
@@ -43,7 +55,12 @@ export function ProductTranslationsCard({ productId }: { productId: string }) {
</p>
)}
</CardContent>
- <ProductTranslationsDialog productId={productId} open={open} onOpenChange={setOpen} />
+ <ResourceTranslationsDialog
+ open={open}
+ onOpenChange={setOpen}
+ resourceType={resourceType}
+ resourceId={resourceId}
+ />
</Card>
)
}
diff --git a/packages/dashboard/src/components/spree/translations/resource-translations-dialog.tsx b/packages/dashboard/src/components/spree/translations/resource-translations-dialog.tsx
index 014875947b..6885d5dfaa 100644
--- a/packages/dashboard/src/components/spree/translations/resource-translations-dialog.tsx
+++ b/packages/dashboard/src/components/spree/translations/resource-translations-dialog.tsx
@@ -28,7 +28,27 @@ import { XIcon } from 'lucide-react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
-import { useLocales } from '@/hooks/use-translations'
+import {
+ type TranslatableResourceType,
+ useLocales,
+ useResourceTranslations,
+} from '@/hooks/use-translations'
+
+/**
+ * Universal field-label resolver. The matrix carries each row's public
+ * `resource_type` (`product`, `category`, `option_type`, `option_value`), so a
+ * single dynamic lookup `admin.fields.<resourceType>.<field>.label` with a
+ * cross-resource fallback covers every resource — no per-resource resolver.
+ */
+function fieldLabel(
+ t: ReturnType<typeof useTranslation>['t'],
+ resourceType: string,
+ field: TranslatableField,
+): string {
+ return t([`admin.fields.${resourceType}.${field.key}.label`, `admin.fields.${field.key}.label`], {
+ defaultValue: field.key,
+ })
+}
/** One editable row in the grid: a translatable entity (the resource itself or
* a nested child like an option value). */
@@ -48,14 +68,10 @@ export interface TranslationRow {
interface ResourceTranslationsDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
- /** Translation matrix document (root, possibly with nested `children`). */
- data?: ResourceTranslations
- isLoading?: boolean
- isError?: boolean
- /** Resolves a field key to its display label (resource-specific i18n). */
- fieldLabel: (resourceType: string, field: TranslatableField) => string
- /** Called after a successful save so the parent can refetch. */
- onSaved?: () => void
+ /** Public resource token, e.g. `product`, `category`, `option_type`. */
+ resourceType: TranslatableResourceType
+ /** Prefixed id of the resource being translated. */
+ resourceId: string
}
/** Edits keyed by `${resourceId}::${locale}::${field}` → value. */
@@ -75,15 +91,13 @@ const cellKey = (resourceId: string, locale: string, field: string) =>
export function ResourceTranslationsDialog({
open,
onOpenChange,
- data,
- isLoading,
- isError,
- fieldLabel,
- onSaved,
+ resourceType,
+ resourceId,
}: ResourceTranslationsDialogProps) {
const { t } = useTranslation()
const confirm = useConfirm()
const { data: locales } = useLocales()
+ const { data, isLoading, isError, refetch } = useResourceTranslations(resourceType, resourceId)
const rows = useMemo(() => (data ? flattenTree(data) : []), [data])
const targetLocales = useMemo(
@@ -152,7 +166,7 @@ export function ResourceTranslationsDialog({
await adminClient.translations.batch(Array.from(byResource.values()))
toast.success(t('admin.translations.saved'))
setEdits(new Map())
- onSaved?.()
+ refetch()
} catch (err) {
// The grid has no form to render inline errors onto, so surface the
// server's validation message (if any) in the toast rather than the
@@ -249,7 +263,7 @@ export function ResourceTranslationsDialog({
rows={rows}
locale={locale}
localeName={localeName(locale)}
- fieldLabel={fieldLabel}
+ fieldLabel={(rt, field) => fieldLabel(t, rt, field)}
edits={edits}
setEdits={setEdits}
/>
diff --git a/packages/dashboard/src/hooks/use-categories.ts b/packages/dashboard/src/hooks/use-categories.ts
index 9963753cbf..bde4935be8 100644
--- a/packages/dashboard/src/hooks/use-categories.ts
+++ b/packages/dashboard/src/hooks/use-categories.ts
@@ -36,7 +36,7 @@ export function useCategorySearch(query: string) {
export function useCategory(id: string | undefined) {
return useQuery({
queryKey: useResourceKey('categories', id ?? 'noop'),
- queryFn: () => adminClient.categories.get(id as string),
+ queryFn: () => adminClient.categories.get(id as string, { expand: ['custom_fields'] }),
enabled: !!id,
})
}
diff --git a/packages/dashboard/src/hooks/use-product.ts b/packages/dashboard/src/hooks/use-product.ts
index ad996fd854..114c931a6c 100644
--- a/packages/dashboard/src/hooks/use-product.ts
+++ b/packages/dashboard/src/hooks/use-product.ts
@@ -26,6 +26,7 @@ export function useProduct(id: string) {
'tax_category',
'product_publications',
'channels',
+ 'custom_fields',
],
}),
enabled: !!id,
diff --git a/packages/dashboard/src/hooks/use-translations.ts b/packages/dashboard/src/hooks/use-translations.ts
index 9b89716396..63c809902d 100644
--- a/packages/dashboard/src/hooks/use-translations.ts
+++ b/packages/dashboard/src/hooks/use-translations.ts
@@ -1,4 +1,4 @@
-import type { Locale } from '@spree/admin-sdk'
+import type { Locale, ResourceTranslations } from '@spree/admin-sdk'
import { adminClient, useResourceKey } from '@spree/dashboard-core'
import { useQuery } from '@tanstack/react-query'
@@ -11,35 +11,33 @@ export function useLocales() {
}
/**
- * Full translation matrix for a product: source values + content type per
- * translatable field, plus the translated value for every supported locale.
- * Writes go through the batch endpoint (see ResourceTranslationsDialog).
+ * Public resource token → SDK translations accessor. The token is the
+ * `resource_type` the API uses in translation payloads (e.g. `category` for any
+ * Spree::Taxon — see Spree::Translations.public_resource_type). Mirrors the
+ * SDK's generic `customFields()` owner-path dispatch. A new translatable
+ * resource is one line here — no new hook or adapter component.
*/
-export function useProductTranslations(productId: string) {
- return useQuery({
- queryKey: useResourceKey('products', productId, 'translations'),
- queryFn: () => adminClient.products.translations.get(productId),
- enabled: !!productId,
- })
-}
+const TRANSLATIONS_ACCESSORS = {
+ product: adminClient.products.translations,
+ category: adminClient.categories.translations,
+ option_type: adminClient.optionTypes.translations,
+} as const
+
+export type TranslatableResourceType = keyof typeof TRANSLATIONS_ACCESSORS
/**
- * Translation matrix for an option type, with its option values nested under
- * `children` so the editor renders type + values together.
+ * Full translation matrix for any translatable resource: source values +
+ * content type per field, plus the translated value for every supported locale
+ * (with nested translatable children, e.g. an option type's values). Writes go
+ * through the batch endpoint (see ResourceTranslationsDialog).
*/
-export function useOptionTypeTranslations(optionTypeId: string) {
- return useQuery({
- queryKey: useResourceKey('option-types', optionTypeId, 'translations'),
- queryFn: () => adminClient.optionTypes.translations.get(optionTypeId),
- enabled: !!optionTypeId,
- })
-}
-
-/** Full translation matrix for a category. */
-export function useCategoryTranslations(categoryId: string) {
- return useQuery({
- queryKey: useResourceKey('categories', categoryId, 'translations'),
- queryFn: () => adminClient.categories.translations.get(categoryId),
- enabled: !!categoryId,
+export function useResourceTranslations(
+ resourceType: TranslatableResourceType,
+ resourceId: string,
+) {
+ return useQuery<ResourceTranslations>({
+ queryKey: useResourceKey(resourceType, resourceId, 'translations'),
+ queryFn: () => TRANSLATIONS_ACCESSORS[resourceType].get(resourceId),
+ enabled: !!resourceId,
})
}
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index cdc1118cc6..3ce3e4c4a6 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -222,7 +222,7 @@
"Spree::Variant": "المتغيرات",
"Spree::Order": "الطلبات",
"Spree::User": "العملاء",
- "Spree::Category": "الفئات",
+ "Spree::Taxon": "الفئات",
"Spree::OptionType": "أنواع الخيارات"
}
},
@@ -960,27 +960,17 @@
"search_placeholder": "بحث في الأسواق…",
"empty": "لا توجد أسواق تتطابق"
},
- "custom_fields_card": {
- "set_up": "يثبت",
- "empty_title": "لا توجد حقول custom حتى الآن",
- "empty_description": "تتبع التفاصيل المنظمة مثل المواد أو الملاءمة أو تعليمات العناية.",
- "not_yet_set": "{{count}} من {{total}} لم يتم ضبطه بعد"
- },
"custom_fields": {
- "title": "Custom الحقول",
- "new_definition_title": "حقل custom جديد",
- "definition_created_title": "تم إنشاء التعريف",
- "definition_created_toast": "تم إنشاء التعريف",
- "definition_created_hint": "يمكنك تعيين قيمته الآن أو تحديد حقل آخر أولاً.",
- "empty_title": "لم يتم تحديد حقول custom لـ {{resource}}",
- "empty_description": "حدد حقل custom لتخزين المعلومات المكتوبة والمنظمة بجانب سجلاتك.",
- "create_definition": "إنشاء تعريف",
- "values_saved": "تم حفظ الحقول Custom",
- "values_save_failed": "فشل حفظ الحقول custom",
- "admin_only": "Admin only",
- "add_another_field": "أضف حقلاً آخر",
- "create_another": "إنشاء آخر",
- "set_values": "تعيين القيم",
+ "section_title": "الحقول المخصصة",
+ "set_up": "إعداد الحقول المخصصة",
+ "manage_in_settings": "الإدارة في الإعدادات",
+ "empty_title": "لا توجد حقول مخصصة بعد",
+ "empty_description": "تتبّع تفاصيل منظمة مثل الخامة أو المقاس أو تعليمات العناية.",
+ "values_saved": "تم حفظ الحقول المخصصة",
+ "values_save_partial_failed": "تعذّر حفظ بعض الحقول المخصصة: {{fields}}",
+ "new_definition_title": "حقل مخصص جديد",
+ "new_definition_description": "حدّد حقلاً مخصصاً لتخزين معلومات مكتوبة ومنظمة في {{resource}} الخاصة بك.",
+ "default_resource": "السجلات",
"errors": {
"failed_to_save": "فشل حفظ الحقل المخصص"
}
@@ -1149,7 +1139,7 @@
"add_cta": "أضف المنتج",
"new": {
"title": "منتج جديد",
- "description": "قم بإعداد منتجك — أضف المتغيرات والأسعار والمخزون والوسائط وحقول custom، ثم احفظه مرة واحدة.",
+ "description": "قم بإعداد منتجك — أضف المتغيرات والأسعار والمخزون والوسائط والحقول المخصصة",
"save_label": "إنشاء المنتج",
"create_succeeded": "تم إنشاء المنتج",
"create_failed": "فشل في إنشاء المنتج",
@@ -1168,7 +1158,6 @@
"section_categorization": "التصنيف",
"section_organization": "منظمة",
"section_variants": "المتغيرات",
- "section_custom_fields": "Custom الحقول",
"publishing": {
"title": "نشر",
"manage_cta": "يدير",
@@ -2126,11 +2115,6 @@
"empty_no_variants": "تتم إدارة مستويات المخزون لكل موقع المخزون. أضف متغيرًا لبدء تتبع المخزون.",
"unknown_location": "موقع غير معروف"
},
- "custom_fields": {
- "empty_title": "لا توجد حقول custom حتى الآن",
- "empty_description": "حدد حقول custom في الإعدادات لبدء تتبع التفاصيل المنظمة للمنتجات.",
- "empty_cta": "قم بإعداد حقول custom"
- },
"columns": {
"sku": "SKU",
"price": "سعر",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 5b6fc4ac86..2f5f0aaee7 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -174,7 +174,7 @@
"Spree::Variant": "Varianten",
"Spree::Order": "Bestellungen",
"Spree::User": "Kunden",
- "Spree::Category": "Kategorien",
+ "Spree::Taxon": "Kategorien",
"Spree::OptionType": "Optionstypen"
}
},
@@ -912,27 +912,17 @@
"search_placeholder": "Märkte suchen…",
"empty": "Keine passenden Märkte"
},
- "custom_fields_card": {
- "set_up": "Einrichten",
+ "custom_fields": {
+ "section_title": "Benutzerdefinierte Felder",
+ "set_up": "Benutzerdefinierte Felder einrichten",
+ "manage_in_settings": "In den Einstellungen verwalten",
"empty_title": "Noch keine benutzerdefinierten Felder",
"empty_description": "Erfassen Sie strukturierte Details wie Material, Passform oder Pflegehinweise.",
- "not_yet_set": "{{count}} von {{total}} noch nicht festgelegt"
- },
- "custom_fields": {
- "title": "Benutzerdefinierte Felder",
- "new_definition_title": "Neues benutzerdefiniertes Feld",
- "definition_created_title": "Definition erstellt",
- "definition_created_toast": "Definition erstellt",
- "definition_created_hint": "Sie können den Wert jetzt festlegen oder zunächst ein weiteres Feld definieren.",
- "empty_title": "Keine benutzerdefinierten Felder für {{resource}} definiert",
- "empty_description": "Definieren Sie ein benutzerdefiniertes Feld, um typisierte, strukturierte Informationen zusammen mit Ihren Datensätzen zu speichern.",
- "create_definition": "Definition erstellen",
"values_saved": "Benutzerdefinierte Felder gespeichert",
- "values_save_failed": "Benutzerdefinierte Felder konnten nicht gespeichert werden",
- "admin_only": "Nur für Administratoren",
- "add_another_field": "Weiteres Feld hinzufügen",
- "create_another": "Weiteres erstellen",
- "set_values": "Werte festlegen",
+ "values_save_partial_failed": "Einige benutzerdefinierte Felder konnten nicht gespeichert werden: {{fields}}",
+ "new_definition_title": "Neues benutzerdefiniertes Feld",
+ "new_definition_description": "Definieren Sie ein benutzerdefiniertes Feld, um typisierte, strukturierte Informationen zu Ihren {{resource}} zu speichern.",
+ "default_resource": "Datensätzen",
"errors": {
"failed_to_save": "Benutzerdefiniertes Feld konnte nicht gespeichert werden"
}
@@ -1101,7 +1091,7 @@
"add_cta": "Produkt hinzufügen",
"new": {
"title": "Neues Produkt",
- "description": "Richten Sie Ihr Produkt ein — fügen Sie Varianten, Preise, Bestand, Medien und benutzerdefinierte Felder hinzu und speichern Sie einmalig.",
+ "description": "Richten Sie Ihr Produkt ein — fügen Sie Varianten, Preise, Bestand, Medien und benutzerdefinierte Felder hinzu",
"save_label": "Produkt erstellen",
"create_succeeded": "Produkt erstellt",
"create_failed": "Produkt konnte nicht erstellt werden",
@@ -1120,7 +1110,6 @@
"section_categorization": "Kategorisierung",
"section_organization": "Organisation",
"section_variants": "Varianten",
- "section_custom_fields": "Benutzerdefinierte Felder",
"publishing": {
"title": "Veröffentlichung",
"manage_cta": "Verwalten",
@@ -2078,11 +2067,6 @@
"empty_no_variants": "Lagerbestände werden pro Lagerstandort verwaltet. Fügen Sie eine Variante hinzu, um mit der Bestandsverfolgung zu beginnen.",
"unknown_location": "Unbekannter Standort"
},
- "custom_fields": {
- "empty_title": "Noch keine benutzerdefinierten Felder",
- "empty_description": "Definieren Sie in den Einstellungen benutzerdefinierte Felder, um strukturierte Details zu Produkten zu erfassen.",
- "empty_cta": "Benutzerdefinierte Felder einrichten"
- },
"columns": {
"sku": "SKU",
"price": "Preis",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index c932f03061..f4706af5f8 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -225,7 +225,7 @@
"Spree::Variant": "Variants",
"Spree::Order": "Orders",
"Spree::User": "Customers",
- "Spree::Category": "Categories",
+ "Spree::Taxon": "Categories",
"Spree::OptionType": "Option types"
}
},
@@ -960,27 +960,17 @@
"search_placeholder": "Search markets…",
"empty": "No markets match"
},
- "custom_fields_card": {
- "set_up": "Set up",
+ "custom_fields": {
+ "section_title": "Custom fields",
+ "set_up": "Set up custom fields",
+ "manage_in_settings": "Manage in settings",
"empty_title": "No custom fields yet",
"empty_description": "Track structured details like material, fit, or care instructions.",
- "not_yet_set": "{{count}} of {{total}} not yet set"
- },
- "custom_fields": {
- "title": "Custom fields",
- "new_definition_title": "New custom field",
- "definition_created_title": "Definition created",
- "definition_created_toast": "Definition created",
- "definition_created_hint": "You can set its value now or define another field first.",
- "empty_title": "No custom fields defined for {{resource}}",
- "empty_description": "Define a custom field to store typed, structured information alongside your records.",
- "create_definition": "Create definition",
"values_saved": "Custom fields saved",
- "values_save_failed": "Failed to save custom fields",
- "admin_only": "Admin only",
- "add_another_field": "Add another field",
- "create_another": "Create another",
- "set_values": "Set values",
+ "values_save_partial_failed": "Some custom fields could not be saved: {{fields}}",
+ "new_definition_title": "New custom field",
+ "new_definition_description": "Define a custom field to store typed, structured information on your {{resource}}.",
+ "default_resource": "records",
"errors": {
"failed_to_save": "Failed to save custom field"
}
@@ -1149,7 +1139,7 @@
"add_cta": "Add product",
"new": {
"title": "New product",
- "description": "Set up your product — add variants, prices, inventory, media, and custom fields, then save once.",
+ "description": "Set up your product — add variants, prices, inventory, media, and custom fields",
"save_label": "Create product",
"create_succeeded": "Product created",
"create_failed": "Failed to create product",
@@ -1168,7 +1158,6 @@
"section_categorization": "Categorization",
"section_organization": "Organization",
"section_variants": "Variants",
- "section_custom_fields": "Custom fields",
"publishing": {
"title": "Publishing",
"manage_cta": "Manage",
@@ -2126,11 +2115,6 @@
"empty_no_variants": "Stock levels are managed per stock location. Add a variant to start tracking inventory.",
"unknown_location": "Unknown location"
},
- "custom_fields": {
- "empty_title": "No custom fields yet",
- "empty_description": "Define custom fields in Settings to start tracking structured details on products.",
- "empty_cta": "Set up custom fields"
- },
"columns": {
"sku": "SKU",
"price": "Price",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index f55ec134eb..e13e490ec1 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -174,7 +174,7 @@
"Spree::Variant": "Variantes",
"Spree::Order": "Commandes",
"Spree::User": "Clients",
- "Spree::Category": "Catégories",
+ "Spree::Taxon": "Catégories",
"Spree::OptionType": "Types d'options"
}
},
@@ -912,27 +912,17 @@
"search_placeholder": "Rechercher des marchés…",
"empty": "Aucun marché ne correspond"
},
- "custom_fields_card": {
- "set_up": "Configurer",
- "empty_title": "Aucun champ personnalisé pour le moment",
- "empty_description": "Suivez des informations structurées telles que la matière, la coupe ou les instructions d'entretien.",
- "not_yet_set": "{{count}} sur {{total}} pas encore renseignés"
- },
"custom_fields": {
- "title": "Champs personnalisés",
- "new_definition_title": "Nouveau champ personnalisé",
- "definition_created_title": "Définition créée",
- "definition_created_toast": "Définition créée",
- "definition_created_hint": "Vous pouvez définir sa valeur maintenant ou d'abord définir un autre champ.",
- "empty_title": "Aucun champ personnalisé défini pour {{resource}}",
- "empty_description": "Définissez un champ personnalisé pour stocker des informations typées et structurées avec vos enregistrements.",
- "create_definition": "Créer une définition",
+ "section_title": "Champs personnalisés",
+ "set_up": "Configurer les champs personnalisés",
+ "manage_in_settings": "Gérer dans les paramètres",
+ "empty_title": "Aucun champ personnalisé pour le moment",
+ "empty_description": "Suivez des détails structurés comme la matière, la coupe ou les instructions d’entretien.",
"values_saved": "Champs personnalisés enregistrés",
- "values_save_failed": "Échec de l'enregistrement des champs personnalisés",
- "admin_only": "Administrateurs uniquement",
- "add_another_field": "Ajouter un autre champ",
- "create_another": "En créer un autre",
- "set_values": "Définir les valeurs",
+ "values_save_partial_failed": "Certains champs personnalisés n’ont pas pu être enregistrés : {{fields}}",
+ "new_definition_title": "Nouveau champ personnalisé",
+ "new_definition_description": "Définissez un champ personnalisé pour stocker des informations typées et structurées sur vos {{resource}}.",
+ "default_resource": "enregistrements",
"errors": {
"failed_to_save": "Impossible d’enregistrer le champ personnalisé"
}
@@ -1101,7 +1091,7 @@
"add_cta": "Ajouter un produit",
"new": {
"title": "Nouveau produit",
- "description": "Configurez votre produit — ajoutez des variantes, des prix, des stocks, des médias et des champs personnalisés, puis enregistrez en une seule fois.",
+ "description": "Configurez votre produit — ajoutez des variantes, des prix, des stocks, des médias et des champs personnalisés",
"save_label": "Créer le produit",
"create_succeeded": "Produit créé",
"create_failed": "Échec de la création du produit",
@@ -1120,7 +1110,6 @@
"section_categorization": "Catégorisation",
"section_organization": "Organisation",
"section_variants": "Variantes",
- "section_custom_fields": "Champs personnalisés",
"publishing": {
"title": "Publication",
"manage_cta": "Gérer",
@@ -2078,11 +2067,6 @@
"empty_no_variants": "Les niveaux de stock sont gérés par emplacement de stock. Ajoutez une variante pour commencer à suivre l'inventaire.",
"unknown_location": "Emplacement inconnu"
},
- "custom_fields": {
- "empty_title": "Aucun champ personnalisé pour le moment",
- "empty_description": "Définissez des champs personnalisés dans les Paramètres pour commencer à suivre des informations structurées sur les produits.",
- "empty_cta": "Configurer les champs personnalisés"
- },
"columns": {
"sku": "SKU",
"price": "Prix",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index ca1ec6a4c4..8e68c9da10 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -174,7 +174,7 @@
"Spree::Variant": "Warianty",
"Spree::Order": "Zamówienia",
"Spree::User": "Klienci",
- "Spree::Category": "Kategorie",
+ "Spree::Taxon": "Kategorie",
"Spree::OptionType": "Typy opcji"
}
},
@@ -912,27 +912,17 @@
"search_placeholder": "Szukaj rynków…",
"empty": "Brak pasujących rynków"
},
- "custom_fields_card": {
- "set_up": "Skonfiguruj",
- "empty_title": "Brak pól niestandardowych",
- "empty_description": "Śledź uporządkowane szczegóły, takie jak materiał, krój czy instrukcje pielęgnacji.",
- "not_yet_set": "{{count}} z {{total}} jeszcze nie ustawiono"
- },
"custom_fields": {
- "title": "Pola niestandardowe",
- "new_definition_title": "Nowe pole niestandardowe",
- "definition_created_title": "Definicja utworzona",
- "definition_created_toast": "Definicja utworzona",
- "definition_created_hint": "Możesz teraz ustawić jej wartość lub najpierw zdefiniować kolejne pole.",
- "empty_title": "Brak zdefiniowanych pól niestandardowych dla {{resource}}",
- "empty_description": "Zdefiniuj pole niestandardowe, aby przechowywać typowane, ustrukturyzowane informacje wraz z rekordami.",
- "create_definition": "Utwórz definicję",
+ "section_title": "Pola niestandardowe",
+ "set_up": "Skonfiguruj pola niestandardowe",
+ "manage_in_settings": "Zarządzaj w ustawieniach",
+ "empty_title": "Brak pól niestandardowych",
+ "empty_description": "Śledź ustrukturyzowane szczegóły, takie jak materiał, krój czy instrukcje pielęgnacji.",
"values_saved": "Pola niestandardowe zapisane",
- "values_save_failed": "Nie udało się zapisać pól niestandardowych",
- "admin_only": "Tylko dla administratorów",
- "add_another_field": "Dodaj kolejne pole",
- "create_another": "Utwórz kolejne",
- "set_values": "Ustaw wartości",
+ "values_save_partial_failed": "Niektórych pól niestandardowych nie udało się zapisać: {{fields}}",
+ "new_definition_title": "Nowe pole niestandardowe",
+ "new_definition_description": "Zdefiniuj pole niestandardowe, aby przechowywać typowane, ustrukturyzowane informacje dla: {{resource}}.",
+ "default_resource": "rekordy",
"errors": {
"failed_to_save": "Nie udało się zapisać pola niestandardowego"
}
@@ -1101,7 +1091,7 @@
"add_cta": "Dodaj produkt",
"new": {
"title": "Nowy produkt",
- "description": "Skonfiguruj swój produkt — dodaj warianty, ceny, stan magazynowy, multimedia i pola niestandardowe, a następnie zapisz wszystko za jednym razem.",
+ "description": "Skonfiguruj swój produkt — dodaj warianty, ceny, stan magazynowy, multimedia i pola niestandardowe",
"save_label": "Utwórz produkt",
"create_succeeded": "Produkt utworzony",
"create_failed": "Nie udało się utworzyć produktu",
@@ -1120,7 +1110,6 @@
"section_categorization": "Kategoryzacja",
"section_organization": "Organizacja",
"section_variants": "Warianty",
- "section_custom_fields": "Pola niestandardowe",
"publishing": {
"title": "Publikacja",
"manage_cta": "Zarządzaj",
@@ -2108,11 +2097,6 @@
"empty_no_variants": "Stany magazynowe są zarządzane osobno dla każdej lokalizacji magazynowej. Dodaj wariant, aby rozpocząć śledzenie stanów magazynowych.",
"unknown_location": "Nieznana lokalizacja"
},
- "custom_fields": {
- "empty_title": "Brak pól niestandardowych",
- "empty_description": "Zdefiniuj pola niestandardowe w Ustawieniach, aby rozpocząć śledzenie ustrukturyzowanych szczegółów produktów.",
- "empty_cta": "Skonfiguruj pola niestandardowe"
- },
"columns": {
"sku": "SKU",
"price": "Cena",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 0d6ead614c..73b69a223a 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -222,7 +222,7 @@
"Spree::Variant": "变体",
"Spree::Order": "订单",
"Spree::User": "客户",
- "Spree::Category": "分类",
+ "Spree::Taxon": "分类",
"Spree::OptionType": "选项类型"
}
},
@@ -960,27 +960,17 @@
"search_placeholder": "搜索市场…",
"empty": "没有匹配的市场"
},
- "custom_fields_card": {
- "set_up": "设置",
- "empty_title": "暂无自定义字段",
- "empty_description": "记录结构化信息,例如材质、版型或保养说明。",
- "not_yet_set": "{{total}} 项中有 {{count}} 项尚未设置"
- },
"custom_fields": {
- "title": "自定义字段",
- "new_definition_title": "新建自定义字段",
- "definition_created_title": "定义已创建",
- "definition_created_toast": "定义已创建",
- "definition_created_hint": "您现在可以设置其值,或先定义另一个字段。",
- "empty_title": "尚未为 {{resource}} 定义自定义字段",
- "empty_description": "定义自定义字段,以便在记录中存储有类型的结构化信息。",
- "create_definition": "创建定义",
+ "section_title": "自定义字段",
+ "set_up": "设置自定义字段",
+ "manage_in_settings": "在设置中管理",
+ "empty_title": "尚无自定义字段",
+ "empty_description": "记录结构化的详细信息,例如材质、版型或保养说明。",
"values_saved": "自定义字段已保存",
- "values_save_failed": "保存自定义字段失败",
- "admin_only": "仅管理员可见",
- "add_another_field": "添加另一个字段",
- "create_another": "再创建一个",
- "set_values": "设置值",
+ "values_save_partial_failed": "部分自定义字段无法保存:{{fields}}",
+ "new_definition_title": "新建自定义字段",
+ "new_definition_description": "定义自定义字段,以在您的{{resource}}上存储有类型的结构化信息。",
+ "default_resource": "记录",
"errors": {
"failed_to_save": "保存自定义字段失败"
}
@@ -1149,7 +1139,7 @@
"add_cta": "添加商品",
"new": {
"title": "新建商品",
- "description": "设置您的商品 — 添加变体、价格、库存、媒体和自定义字段,然后一次性保存。",
+ "description": "设置您的商品 — 添加变体、价格、库存、媒体和自定义字段",
"save_label": "创建商品",
"create_succeeded": "商品已创建",
"create_failed": "创建商品失败",
@@ -1168,7 +1158,6 @@
"section_categorization": "分类",
"section_organization": "组织",
"section_variants": "变体",
- "section_custom_fields": "自定义字段",
"publishing": {
"title": "发布",
"manage_cta": "管理",
@@ -2126,11 +2115,6 @@
"empty_no_variants": "库存水平按库存地点管理。添加一个变体以开始跟踪库存。",
"unknown_location": "未知位置"
},
- "custom_fields": {
- "empty_title": "暂无自定义字段",
- "empty_description": "在设置中定义自定义字段,即可开始为商品记录结构化信息。",
- "empty_cta": "配置自定义字段"
- },
"columns": {
"sku": "SKU",
"price": "价格",
diff --git a/packages/dashboard/src/nav/default.ts b/packages/dashboard/src/nav/default.ts
index fce4315820..57ee4beae3 100644
--- a/packages/dashboard/src/nav/default.ts
+++ b/packages/dashboard/src/nav/default.ts
@@ -54,7 +54,7 @@ nav.add({
key: 'products.categories',
label: i18n.t('admin.nav.categories'),
path: '/products/categories',
- subject: Subject.Taxon,
+ subject: Subject.Category,
position: 300,
},
{
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/customers/$customerId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/customers/$customerId.tsx
index 6df9a72d98..5bb97e28c9 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/customers/$customerId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/customers/$customerId.tsx
@@ -7,6 +7,7 @@ import {
mapSpreeErrorsToForm,
PageHeader,
ResourceMultiAutocomplete,
+ Subject,
TagCombobox,
useCountries,
useStore,
@@ -71,7 +72,10 @@ import { Controller, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { currencyParts } from '@/components/spree/bulk-price-editor/currency-parts'
import { normalizeMoneyInput } from '@/components/spree/bulk-price-editor/normalize-money'
-import { CustomFieldsCard } from '@/components/spree/custom-fields/custom-fields-card'
+import {
+ CustomFieldsInlineCard,
+ EditableApiCustomFieldsProvider,
+} from '@/components/spree/custom-fields/custom-fields-inline'
import { useCurrencyLocale } from '@/hooks/use-currency-locale'
import { customerGroupAutocompleteProps, useCustomerGroups } from '@/hooks/use-customer-groups'
import {
@@ -182,11 +186,14 @@ function CustomerBody({ customer }: { customer: Customer }) {
isLoading={isLoading}
/>
<StoreCreditsCard customer={customer} />
- <CustomFieldsCard
- ownerType="Spree::User"
+ <EditableApiCustomFieldsProvider
+ ownerType={Subject.Customer}
ownerId={customer.id}
- resourceLabel="customers"
- />
+ resourceType={Subject.Customer}
+ resourceLabel={t('admin.nav.customers').toLowerCase()}
+ >
+ <CustomFieldsInlineCard />
+ </EditableApiCustomFieldsProvider>
<MetadataCard
metadata={customer.metadata}
title={t('admin.components.metadata_card.title')}
@@ -374,7 +381,7 @@ function EditProfileSheet({
control={form.control}
render={({ field }) => (
<TagCombobox
- taggableType="Spree::User"
+ taggableType={Subject.Customer}
value={field.value}
onChange={field.onChange}
/>
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/customers/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/customers/index.tsx
index 7342d28bb5..4cb249c2f0 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/customers/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/customers/index.tsx
@@ -331,7 +331,7 @@ function TagPickerDialog({
>
<Field>
<FieldLabel>{t('admin.fields.customer.tags.label')}</FieldLabel>
- <TagCombobox taggableType="Spree::User" value={tags} onChange={setTags} />
+ <TagCombobox taggableType={Subject.Customer} value={tags} onChange={setTags} />
</Field>
</BulkDialog>
)
@@ -451,7 +451,7 @@ function NewCustomerSheet({
control={form.control}
render={({ field }) => (
<TagCombobox
- taggableType="Spree::User"
+ taggableType={Subject.Customer}
value={field.value}
onChange={field.onChange}
/>
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsx
index 20c6ba2e64..7817a3561b 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsx
@@ -82,7 +82,10 @@ import {
} from 'lucide-react'
import { type FormEvent, type ReactNode, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { CustomFieldsCard } from '@/components/spree/custom-fields/custom-fields-card'
+import {
+ CustomFieldsInlineCard,
+ EditableApiCustomFieldsProvider,
+} from '@/components/spree/custom-fields/custom-fields-inline'
import { orderQueryKey, useOrder, useOrderMutation } from '@/hooks/use-order'
import { spreeJsonLinkResolver } from '@/lib/json-link-resolver'
@@ -135,7 +138,14 @@ function OrderDetailPage() {
<ShipmentsCard order={order} />
<PaymentsCard order={order} />
<OrderSummaryCard order={order} />
- <CustomFieldsCard ownerType="Spree::Order" ownerId={order.id} resourceLabel="orders" />
+ <EditableApiCustomFieldsProvider
+ ownerType="Spree::Order"
+ ownerId={order.id}
+ resourceType="Spree::Order"
+ resourceLabel={t('admin.nav.orders').toLowerCase()}
+ >
+ <CustomFieldsInlineCard />
+ </EditableApiCustomFieldsProvider>
<MetadataCard
metadata={order.metadata}
title={t('admin.components.metadata_card.title')}
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx
index b545e79056..3c83637edd 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx
@@ -18,8 +18,8 @@ import { useForm, useWatch } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import {
- ApiBackedCustomFieldsProvider,
CustomFieldsInlineCard,
+ FormBackedCustomFieldsProvider,
} from '@/components/spree/custom-fields/custom-fields-inline'
import {
CategorizationCard,
@@ -32,8 +32,8 @@ import {
TaxCard,
VariantsCard,
} from '@/components/spree/products/product-form-cards'
-import { ProductTranslationsCard } from '@/components/spree/products/product-translations-card'
import { PublishingCard } from '@/components/spree/products/publishing-card'
+import { ResourceTranslationsCard } from '@/components/spree/translations/resource-translations-card'
import { useDeleteProduct, useProduct, useUpdateProduct } from '@/hooks/use-product'
import { useProductMedia } from '@/hooks/use-product-media'
import { spreeJsonLinkResolver } from '@/lib/json-link-resolver'
@@ -131,6 +131,12 @@ function productToFormValues(
meta_description: product.meta_description ?? '',
slug: product.slug ?? '',
variants: variantSource.map((v, i) => variantToFormValues(v, i)),
+ custom_fields:
+ product.custom_fields?.map((cf) => ({
+ id: cf.id,
+ custom_field_definition_id: cf.custom_field_definition_id,
+ value: cf.value,
+ })) ?? [],
media:
media?.map((m, i) => ({
id: m.id,
@@ -394,14 +400,10 @@ function ProductForm({ product }: { product: Product }) {
<MediaCard productId={productId} variants={assignableVariants} form={form} />
<PricesCard form={form} productName={product.name} />
<InventoryCard form={form} storeId={storeId} />
- <ApiBackedCustomFieldsProvider
- ownerType="Spree::Product"
- ownerId={productId}
- resourceType="Spree::Product"
- >
+ <FormBackedCustomFieldsProvider form={form} resourceType="Spree::Product">
<CustomFieldsInlineCard />
- </ApiBackedCustomFieldsProvider>
- <ProductTranslationsCard productId={productId} />
+ </FormBackedCustomFieldsProvider>
+ <ResourceTranslationsCard resourceType="product" resourceId={productId} />
<MetadataCard
metadata={product.metadata}
title={t('admin.components.metadata_card.title')}
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/index.tsx
index c082ee9e09..f16c67cd9e 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/index.tsx
@@ -14,8 +14,8 @@ import { PlusIcon, SearchIcon } from 'lucide-react'
import { useDeferredValue, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { CategoryList } from '@/components/spree/categories/category-list'
-import { CategoryTranslationsDialog } from '@/components/spree/categories/category-translations-dialog'
import { CategoryTree } from '@/components/spree/categories/category-tree'
+import { ResourceTranslationsDialog } from '@/components/spree/translations/resource-translations-dialog'
import {
useCategories,
useCategorySearch,
@@ -86,7 +86,7 @@ function CategoriesPage() {
placeholder={t('admin.categories.search_placeholder')}
/>
</InputGroup>
- <Can I="create" a={Subject.Taxon}>
+ <Can I="create" a={Subject.Category}>
<Button
size="sm"
className="h-[2.125rem]"
@@ -124,8 +124,9 @@ function CategoriesPage() {
</Card>
{translateId && (
- <CategoryTranslationsDialog
- categoryId={translateId}
+ <ResourceTranslationsDialog
+ resourceType="category"
+ resourceId={translateId}
open
onOpenChange={(o) => !o && setTranslateId(null)}
/>
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/options.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/options.tsx
index 067e723120..b2b3a06432 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/options.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/options.tsx
@@ -84,7 +84,7 @@ import {
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { z } from 'zod/v4'
-import { OptionTypeTranslationsDialog } from '@/components/spree/products/option-type-translations-dialog'
+import { ResourceTranslationsDialog } from '@/components/spree/translations/resource-translations-dialog'
import {
useCreateOptionType,
useDeleteOptionType,
@@ -348,8 +348,9 @@ function EditOptionTypeSheet({
{/* Mounted only when opened so its translation fetch doesn't fire on
every option-type edit. */}
{translationsOpen && (
- <OptionTypeTranslationsDialog
- optionTypeId={id}
+ <ResourceTranslationsDialog
+ resourceType="option_type"
+ resourceId={id}
open={translationsOpen}
onOpenChange={setTranslationsOpen}
/>
diff --git a/packages/dashboard/src/schemas/category.ts b/packages/dashboard/src/schemas/category.ts
index e01965881f..150bc489c8 100644
--- a/packages/dashboard/src/schemas/category.ts
+++ b/packages/dashboard/src/schemas/category.ts
@@ -1,6 +1,7 @@
import type { Category } from '@spree/admin-sdk'
import { requiredMessage } from '@spree/dashboard-ui'
import { z } from 'zod/v4'
+import { customFieldFormSchema } from '@/schemas/product'
// Each image field is a small state machine: untouched (omit on save),
// uploaded (send signed_id), or cleared (send null to purge). `*_signed_id`
@@ -24,6 +25,10 @@ export const categoryFormSchema = z.object({
permalink: z.string(),
meta_title: z.string(),
meta_description: z.string(),
+ // Inline custom field values keyed by definition id, upserted server-side via
+ // Spree::Metafields#custom_fields= (the categories controller permits them).
+ // Persisted with the rest of the category on the page's Save button.
+ custom_fields: z.array(customFieldFormSchema).optional(),
...imageFields,
})
@@ -45,6 +50,7 @@ export const CATEGORY_DEFAULTS: CategoryFormValues = {
permalink: '',
meta_title: '',
meta_description: '',
+ custom_fields: [],
...IMAGE_DEFAULTS,
}
@@ -57,6 +63,12 @@ export function categoryToForm(category: Category): CategoryFormValues {
permalink: category.permalink ?? '',
meta_title: category.meta_title ?? '',
meta_description: category.meta_description ?? '',
+ custom_fields:
+ category.custom_fields?.map((cf) => ({
+ id: cf.id,
+ custom_field_definition_id: cf.custom_field_definition_id,
+ value: cf.value,
+ })) ?? [],
...IMAGE_DEFAULTS,
}
}
@@ -72,6 +84,11 @@ export function categoryToParams(values: CategoryFormValues) {
permalink: values.permalink,
meta_title: values.meta_title,
meta_description: values.meta_description,
+ // Only ship when present — the model setter no-ops on blank, and an empty
+ // array is noise. Upsert semantics mean untouched definitions stay as-is.
+ ...(values.custom_fields && values.custom_fields.length > 0
+ ? { custom_fields: values.custom_fields }
+ : {}),
...imageParam('image', values.image_signed_id, values.image_cleared),
...imageParam('square_image', values.square_image_signed_id, values.square_image_cleared),
}
diff --git a/packages/dashboard/src/schemas/custom-field-definition.ts b/packages/dashboard/src/schemas/custom-field-definition.ts
index b196a9524e..c0ea5e496e 100644
--- a/packages/dashboard/src/schemas/custom-field-definition.ts
+++ b/packages/dashboard/src/schemas/custom-field-definition.ts
@@ -35,7 +35,11 @@ export const DEFAULT_RESOURCE_TYPES = [
'Spree::Variant',
'Spree::Order',
'Spree::User',
- 'Spree::Category',
+ // Category custom-field definitions are stored under Spree::Taxon (the API
+ // exposes taxons as categories — the custom_fields controller maps the
+ // category route segment to the Spree::Taxon class). Listing Spree::Category
+ // here would orphan definitions: the inline category card reads under Taxon.
+ 'Spree::Taxon',
'Spree::OptionType',
] as const
diff --git a/packages/dashboard/src/schemas/product.ts b/packages/dashboard/src/schemas/product.ts
index 42d08581c8..473dfa73ad 100644
--- a/packages/dashboard/src/schemas/product.ts
+++ b/packages/dashboard/src/schemas/product.ts
@@ -54,6 +54,9 @@ export const variantFormSchema = z.object({
export type VariantFormValues = z.infer<typeof variantFormSchema>
export const customFieldFormSchema = z.object({
+ // Prefixed id of an existing custom-field value. Present when hydrating a
+ // persisted record so edits patch the existing row rather than insert.
+ id: z.string().optional(),
custom_field_definition_id: z.string(),
value: z.unknown(),
})
diff --git a/packages/dashboard/src/search/default.tsx b/packages/dashboard/src/search/default.tsx
index ea862757a3..a4fea3d820 100644
--- a/packages/dashboard/src/search/default.tsx
+++ b/packages/dashboard/src/search/default.tsx
@@ -1,7 +1,13 @@
-import type { Customer, Order, Product, Promotion } from '@spree/admin-sdk'
+import type { Category, Customer, Order, Product, Promotion } from '@spree/admin-sdk'
import { adminClient, defineSearchEntry, Subject, searchRegistry } from '@spree/dashboard-core'
import { StatusBadge } from '@spree/dashboard-ui'
-import { ShoppingCartIcon, TagIcon, TicketPercentIcon, UsersIcon } from 'lucide-react'
+import {
+ FolderTreeIcon,
+ ShoppingCartIcon,
+ TagIcon,
+ TicketPercentIcon,
+ UsersIcon,
+} from 'lucide-react'
// Each entry teaches the command palette how to search one resource: how to
// fetch matches, render a result row, and where a row navigates. Resources are
@@ -28,6 +34,30 @@ searchRegistry.add(
}),
)
+searchRegistry.add(
+ defineSearchEntry<Category>({
+ key: 'categories',
+ headingKey: 'admin.nav.categories',
+ subject: Subject.Category,
+ position: 150,
+ // No backend `search` scope on Taxon — match the name via a Ransack `cont`
+ // predicate (whitelisted on Spree::Taxon), sorted by the full hierarchy path
+ // so nested categories read top-down. Mirrors the categories page search.
+ fetch: (search, limit) =>
+ adminClient.categories
+ .list({ name_cont: search, limit, sort: 'pretty_name' })
+ .then((r) => r.data),
+ getKey: (c) => c.id,
+ getRoute: (c, storeId) => ({ to: `/${storeId}/products/categories/${c.id}` }),
+ renderRow: (c) => (
+ <>
+ <CategoryIconOrThumbnail thumbnailUrl={c.square_image_url ?? c.image_url ?? null} />
+ <span className="flex-1 truncate">{c.pretty_name}</span>
+ </>
+ ),
+ }),
+)
+
searchRegistry.add(
defineSearchEntry<Order>({
key: 'orders',
@@ -106,3 +136,15 @@ function ProductIconOrThumbnail({ thumbnailUrl }: { thumbnailUrl: string | null
/>
)
}
+
+function CategoryIconOrThumbnail({ thumbnailUrl }: { thumbnailUrl: string | null }) {
+ if (!thumbnailUrl) return <FolderTreeIcon />
+ return (
+ <img
+ src={thumbnailUrl}
+ alt=""
+ className="size-5 shrink-0 rounded object-cover"
+ loading="lazy"
+ />
+ )
+}
diff --git a/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb
index 8c5f682e00..66e7b30d17 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb
@@ -62,7 +62,14 @@ module Spree
permitted = params.permit(
:name, :description, :permalink,
:meta_title, :meta_description, :meta_keywords,
- :hide_from_nav, :image, :square_image
+ :hide_from_nav, :image, :square_image,
+ # Inline custom field values keyed by definition id. The model
+ # setter (Spree::Metafields#custom_fields=) validates each entry
+ # against its definition. `value` is permitted as a scalar AND as
+ # `value: []` / `value: {}` so JSON metafields round-trip whether
+ # the parsed payload is an array or an object, while
+ # text/number/boolean ship scalars.
+ custom_fields: [:id, :custom_field_definition_id, :value, { value: [] }, { value: {} }]
)
permitted[:parent] = scope.find_by_prefix_id!(params[:parent_id]) if params[:parent_id].present?
permitted
diff --git a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
index 308ba94887..dca02db57c 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
@@ -171,11 +171,11 @@ module Spree
prices: [:amount, :compare_at_amount, :currency],
# Inline custom field values keyed by definition id. The model
# setter (`Spree::Metafields#custom_fields=`) validates each
- # entry against its definition. We permit `value` as both a
- # scalar AND `value: {}` (any-shape Hash/Array) — Strong
- # Parameters merges them so JSON metafields can ship parsed
- # objects while text/number/boolean ship scalars.
- custom_fields: [:id, :custom_field_definition_id, :value, value: {}],
+ # entry against its definition. We permit `value` as a scalar AND
+ # as `value: []` / `value: {}` so JSON metafields round-trip
+ # whether the parsed payload is an array or an object, while
+ # text/number/boolean ship scalars.
+ custom_fields: [:id, :custom_field_definition_id, :value, { value: [] }, { value: {} }],
# Inline media. Entries with `id` patch an existing asset
# (alt, position, variant_ids). Entries with `signed_id` create
# + attach a fresh upload. Lets the dashboard ship media changes
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/categories_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/categories_controller_spec.rb
index e5dc2c5c1e..d321ce3a4a 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/categories_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/categories_controller_spec.rb
@@ -119,6 +119,75 @@ RSpec.describe Spree::Api::V3::Admin::CategoriesController, type: :controller do
expect(response).to have_http_status(:ok)
expect(imaged.reload.image).not_to be_attached
end
+
+ # Category custom-field definitions are stored under Spree::Taxon (the
+ # category route maps to the Taxon class). The dashboard ships values inline
+ # with the category form, persisted via Spree::Metafields#custom_fields=.
+ context 'with inline custom fields' do
+ let!(:fabric_definition) do
+ create(:metafield_definition,
+ resource_type: 'Spree::Taxon',
+ namespace: 'category',
+ key: 'fabric',
+ metafield_type: 'Spree::Metafields::ShortText')
+ end
+ let!(:specs_definition) do
+ create(:metafield_definition,
+ resource_type: 'Spree::Taxon',
+ namespace: 'category',
+ key: 'specs',
+ metafield_type: 'Spree::Metafields::Json')
+ end
+
+ it 'round-trips an array-shaped JSON custom field value' do
+ patch :update, params: {
+ id: category.prefixed_id,
+ custom_fields: [
+ { custom_field_definition_id: specs_definition.prefixed_id, value: %w[a b c] }
+ ]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ stored = category.reload.metafields.find_by(metafield_definition: specs_definition)
+ expect(stored.serialize_value).to eq(%w[a b c])
+ end
+
+ it 'round-trips an object-shaped JSON custom field value' do
+ patch :update, params: {
+ id: category.prefixed_id,
+ custom_fields: [
+ { custom_field_definition_id: specs_definition.prefixed_id, value: { 'color' => 'red' } }
+ ]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ stored = category.reload.metafields.find_by(metafield_definition: specs_definition)
+ expect(stored.serialize_value).to eq('color' => 'red')
+ end
+
+ it 'persists custom_fields inline on update' do
+ expect {
+ patch :update, params: {
+ id: category.prefixed_id,
+ custom_fields: [
+ { custom_field_definition_id: fabric_definition.prefixed_id, value: 'Linen' }
+ ]
+ }, as: :json
+ }.to change(Spree::Metafield, :count).by(1)
+
+ expect(response).to have_http_status(:ok)
+ expect(category.reload.metafields.find_by(metafield_definition: fabric_definition).value).to eq('Linen')
+ end
+
+ it 'leaves existing values untouched when custom_fields is omitted' do
+ category.metafields.create!(metafield_definition: fabric_definition, value: 'Wool')
+
+ patch :update, params: { id: category.prefixed_id, name: 'Apparel' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(category.reload.metafields.find_by(metafield_definition: fabric_definition).value).to eq('Wool')
+ end
+ end
end
describe 'DELETE #destroy' do