import { DashboardSkeleton } from "@/components/ui/dashboard-skeleton"; import { useEffect, useRef, useState, type ReactNode } from "react"; import { ArrowDown, ArrowLeft, ArrowUp, Loader2, Plus, Trash2, X, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { Switch } from "@/components/ui/switch"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover"; import { toast, settingsSaved } from "@/components/ui/toast"; type Option = { id: string; label: string; price: number | string; pricingType: string; color?: string; }; type Rule = { field: string; operator: string; value: string }; type Field = { id: string; type: string; title: string; description?: string; required: boolean; price?: number | string; pricingType?: string; options?: Option[]; fileAllowedTypes?: string; fileMaxSize?: number; fileMaxFiles?: number; minDate?: string; maxDate?: string; addonQuantityEnabled?: boolean; minSelections?: number; maxSelections?: number; conditionalLogic?: { enabled: boolean; action: string; relation: string; rules: Rule[]; }; }; type Group = { archived?: boolean; id?: number; revision?: number; name: string; enabled: boolean; allProducts: boolean; priority: number; productIds: number[]; categoryIds: number[]; excludedProductIds: number[]; excludedCategoryIds: number[]; fields: Field[]; }; type CatalogItem = { id: number; name: string }; type Preview = { items: (CatalogItem & { mode: string; url: string })[]; total: number; pages: number; enabled: boolean; }; const fieldTypes = { text: "Short text", textarea: "Long text", checkbox: "Checkboxes", radio: "Radio buttons", select: "Dropdown", heading: "Heading", file: "File upload", date_time: "Date and time", color_swatch: "Color swatches", }; const pricingTypes = { flat_fee: "Flat fee", quantity_based: "Per product quantity", percentage: "Percentage", }; const uid = () => `field_${Array.from(crypto.getRandomValues(new Uint32Array(4)), (value) => value.toString(16).padStart(8, "0")).join("")}`; const emptyGroup = (): Group => ({ name: "", enabled: true, allProducts: false, priority: 10, productIds: [], categoryIds: [], excludedProductIds: [], excludedCategoryIds: [], fields: [], }); async function api( path = "", data?: unknown, method = data === undefined ? "GET" : "POST", signal?: AbortSignal, ): Promise { const response = await fetch( `${window.swiftCommerceData?.apiUrl || "/wp-json/swift-commerce/v1"}/product-addons/groups${path}`, { method, signal, headers: { "Content-Type": "application/json", "X-WP-Nonce": window.swiftCommerceData?.restNonce || "", }, ...(data === undefined ? {} : { body: JSON.stringify(data) }), }, ); const result = await response.json(); if (!response.ok) throw new Error(result.message || "The request failed. Please try again."); return result; } function Choice({ value, onChange, choices, label, }: { value: string; onChange: (value: string) => void; choices: Record; label: string; }) { return ( ); } function FieldSection({ title, children, }: { title: string; children: ReactNode; }) { const [open, setOpen] = useState(!title); return (
setOpen(event.currentTarget.open)} className="rounded-md border p-4" > {children}
); } function AssignmentPicker({ label, kind, value, onChange, }: { label: string; kind: "products" | "categories"; value: number[]; onChange: (ids: number[]) => void; }) { const [open, setOpen] = useState(false); const [search, setSearch] = useState(""); const [items, setItems] = useState([]); const [names, setNames] = useState>({}); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); const selectedIds = value.join(","); useEffect(() => { if (!selectedIds) return; const controller = new AbortController(); api<{ items: CatalogItem[] }>( `/catalog?kind=${kind}&ids=${selectedIds}`, undefined, "GET", controller.signal, ) .then((result) => setNames((previous) => ({ ...previous, ...Object.fromEntries( result.items.map((item) => [item.id, item.name]), ), })), ) .catch((error) => { if (!controller.signal.aborted) setError(error.message); }); return () => controller.abort(); }, [kind, selectedIds]); useEffect(() => { if (!open) return; const controller = new AbortController(); const timer = window.setTimeout(async () => { setLoading(true); setError(""); try { const result = await api<{ items: CatalogItem[] }>( `/catalog?kind=${kind}&search=${encodeURIComponent(search)}`, undefined, "GET", controller.signal, ); setItems(result.items); setNames((previous) => ({ ...previous, ...Object.fromEntries( result.items.map((item) => [item.id, item.name]), ), })); } catch (error) { if (!controller.signal.aborted) setError((error as Error).message); } finally { if (!controller.signal.aborted) setLoading(false); } }, 200); return () => { controller.abort(); window.clearTimeout(timer); }; }, [kind, open, search]); return (
{value.map((id) => ( {names[id] || `#${id}`} ))}
setSearch(event.target.value)} />
{loading && (

Searching…

)} {error && (

{error}

)} {!loading && !error && items.length === 0 && (

No matches.

)} {items.map((item) => ( ))}
); } export function FieldEditor({ field, fields, update, }: { field: Field; fields: Field[]; update: (value: Field) => void; }) { const patch = (value: Partial) => update({ ...field, ...value }); const choice = ["checkbox", "radio", "select", "color_swatch"].includes( field.type, ); const logic = field.conditionalLogic || { enabled: false, action: "show", relation: "all", rules: [], }; const changeLogic = (value: Partial) => patch({ conditionalLogic: { ...logic, ...value } }); return (
patch({ title: event.target.value })} />
patch({ type, options: [ "checkbox", "radio", "select", "color_swatch", ].includes(type) ? field.options || [ { id: uid(), label: "", price: 0, pricingType: "flat_fee", }, ] : undefined, }) } />