import { getNestedError } from '@components/common/form/utils/getNestedError.js'; import { Button } from '@components/common/ui/Button.js'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@components/common/ui/Card.js'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@components/common/ui/Dialog.js'; import { Skeleton } from '@components/common/ui/Skeleton.js'; import { toast } from '@components/common/ui/Sonner.js'; import { _ } from '@evershop/evershop/lib/locale/translate/_'; import axios from 'axios'; import { Code, Cog, Pencil, Plus, Tags } from 'lucide-react'; import React, { useCallback, useEffect, useState } from 'react'; import { useFormContext, useFormState } from 'react-hook-form'; import { DefinitionEditor } from './DefinitionEditor.js'; import { MetafieldValueInput, type FieldDescriptor } from './MetafieldValueInput.js'; interface Definition extends FieldDescriptor { uuid: string; namespace: string; visibleToCustomer: boolean; } interface Props { /** The owner type these definitions belong to (e.g. "product"). */ ownerType: string; /** Current values (the entity's meta_data) to prefill the form for editing. */ values?: Record; } /** Human-readable preview of a single scalar value, or null when not set. */ function formatScalar(type: string, value: unknown): string | null { if (value === '' || value === undefined || value === null) return null; if (type === 'boolean') return value ? _('Yes') : _('No'); return String(value); } /** Plain-text snippet of block-editor content for the collapsed preview row. */ function richTextPreview(value: unknown): string | null { if (!Array.isArray(value)) return null; const parts: string[] = []; for (const row of value as any[]) { for (const col of row?.columns ?? []) { for (const block of col?.data?.blocks ?? []) { if (typeof block?.data?.text === 'string') { parts.push(block.data.text.replace(/<[^>]*>/g, '')); } else if (Array.isArray(block?.data?.items)) { parts.push(block.data.items.map(String).join(', ')); } } } } const text = parts.join(' ').replace(/\s+/g, ' ').trim(); return text || null; } /** Preview text for a field's current value (lists joined with • ), or null. */ function formatPreview(def: Definition, value: unknown): string | null { if (def.type === 'rich_text') return richTextPreview(value); if (def.type === 'group') { if (def.isList) { const n = Array.isArray(value) ? value.filter( (it) => it && typeof it === 'object' && Object.values(it).some((x) => x !== '' && x != null) ).length : 0; return n ? `${n} ${n === 1 ? _('item') : _('items')}` : null; } if (value && typeof value === 'object') { const parts = (def.subFields || []) .map((sf) => (value as Record)[sf.key]) .filter((x) => x !== '' && x != null) .map(String); return parts.length ? parts.join(' · ') : null; } return null; } if (def.isList) { if (!Array.isArray(value)) return null; const items = value .map((v) => formatScalar(def.type, v)) .filter((s): s is string => s !== null); return items.length ? items.join(' • ') : null; } return formatScalar(def.type, value); } /** * One field: collapsed it shows the current value as text (or "Not set"); click * the row to expand the editor. The input stays mounted (just hidden) while * collapsed so its value is always part of the form submission. */ function MetafieldRow({ def, initialValue, onEditDefinition }: { def: Definition; initialValue?: unknown; onEditDefinition: () => void; }) { const [open, setOpen] = useState(false); const { watch, trigger } = useFormContext(); const name = `metafields.${def.namespace}.${def.key}`; const preview = formatPreview(def, watch(name)); // Auto-expand when this field has a validation error (e.g. a required field // left empty when the parent form is submitted) so the error is never hidden // inside a collapsed row. const { errors } = useFormState({ name }); const hasError = !!getNestedError(name, errors); useEffect(() => { if (hasError) setOpen(true); }, [hasError]); // Validate the field(s) being edited; collapse to the preview only when valid // so an inline error stays visible (the input is hidden once collapsed). const handleDone = async () => { const valid = await trigger(name); if (valid) setOpen(false); }; return (
{def.description ? (

{def.description}

) : null} {!def.visibleToCustomer ? (

{_('Not visible to customers')}

) : null}
{def.type === 'rich_text' ? ( // Block editor: render inline (always visible). It must not mount inside // a hidden container, and a one-line preview can't represent it. ) : ( <> {!open ? ( ) : null}
)}
); } /** * The "Custom fields" section, mounted inside an entity's edit `
`. It loads * the owner type's definitions over REST, renders a per-field row (value shown as * text, expand to edit) that contributes a `metafields` object to the parent form * payload, and offers an "Add field" popup plus a read-only "View JSON". */ export function MetafieldSection({ ownerType, values }: Props) { const [definitions, setDefinitions] = useState([]); const [loading, setLoading] = useState(true); const [addOpen, setAddOpen] = useState(false); const [jsonOpen, setJsonOpen] = useState(false); const [editDef, setEditDef] = useState(null); const { watch, setValue } = useFormContext(); // Seed the parent form's `metafields` once with the entity's current values so // the inputs prefill when editing an existing entity. useEffect(() => { if (values && Object.keys(values).length > 0) { setValue('metafields', values); } }, []); const load = useCallback(async () => { setLoading(true); try { const res = await axios.get( `/api/metafield-definitions?ownerType=${encodeURIComponent(ownerType)}` ); setDefinitions(res.data?.data ?? []); } catch (e) { toast.error(_('Failed to load custom fields')); } finally { setLoading(false); } }, [ownerType]); useEffect(() => { load(); }, [load]); const metaValues = watch('metafields'); return (
{_('Custom fields')}
{_( 'Fields applicable to this entity type. Adding a field applies it to all entities of this type.' )}
{loading ? (
{[0, 1, 2, 3, 4].map((i) => (
))}
) : definitions.length === 0 ? (

{_('No custom fields yet.')}

) : (
{definitions.map((def) => ( > | undefined)?.[ def.namespace ]?.[def.key] } onEditDefinition={() => setEditDef(def)} /> ))}
)}
{_('Add custom field')} { setAddOpen(false); load(); }} /> { if (!o) setEditDef(null); }} > {_('Edit custom field')} {editDef ? ( { setEditDef(null); load(); }} /> ) : null} {_('Custom fields (JSON)')}
            {JSON.stringify(metaValues ?? {}, null, 2)}
          
); }