| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815 |
- "use client";
- import { Children, useEffect, useState } from "react";
- import {
- defineRegistry,
- useBoundProp,
- useStateBinding,
- useFieldValidation,
- } from "@json-render/react";
- import { toast } from "sonner";
- import { playgroundCatalog } from "./catalog";
- // shadcn components
- 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 { Checkbox } from "@/components/ui/checkbox";
- import { Switch } from "@/components/ui/switch";
- import { Progress } from "@/components/ui/progress";
- import { Separator } from "@/components/ui/separator";
- import { Alert, AlertTitle, AlertDescription } from "@/components/ui/alert";
- import {
- Dialog as DialogPrimitive,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
- } from "@/components/ui/dialog";
- import {
- Accordion as AccordionPrimitive,
- AccordionContent,
- AccordionItem,
- AccordionTrigger,
- } from "@/components/ui/accordion";
- import { Badge } from "@/components/ui/badge";
- import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
- import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
- } from "@/components/ui/select";
- import {
- Carousel as CarouselPrimitive,
- CarouselContent,
- CarouselItem,
- CarouselNext,
- CarouselPrevious,
- } from "@/components/ui/carousel";
- import {
- Collapsible,
- CollapsibleContent,
- CollapsibleTrigger,
- } from "@/components/ui/collapsible";
- import {
- Table as TablePrimitive,
- TableBody,
- TableCaption,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
- } from "@/components/ui/table";
- import {
- Drawer as DrawerPrimitive,
- DrawerContent,
- DrawerDescription,
- DrawerHeader,
- DrawerTitle,
- } from "@/components/ui/drawer";
- import {
- DropdownMenu as DropdownMenuPrimitive,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
- } from "@/components/ui/dropdown-menu";
- import {
- Pagination as PaginationPrimitive,
- PaginationContent,
- PaginationItem,
- PaginationLink,
- PaginationNext,
- PaginationPrevious,
- } from "@/components/ui/pagination";
- import {
- Popover as PopoverPrimitive,
- PopoverContent,
- PopoverTrigger,
- } from "@/components/ui/popover";
- import { Skeleton } from "@/components/ui/skeleton";
- import { Slider } from "@/components/ui/slider";
- import {
- Tabs as TabsPrimitive,
- TabsList,
- TabsTrigger,
- TabsContent,
- } from "@/components/ui/tabs";
- import { Toggle } from "@/components/ui/toggle";
- import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
- import {
- Tooltip as TooltipPrimitive,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
- } from "@/components/ui/tooltip";
- import { icons as lucideIcons } from "lucide-react";
- // =============================================================================
- // Registry — components + actions, types inferred from catalog
- // =============================================================================
- export const { registry, executeAction } = defineRegistry(playgroundCatalog, {
- components: {
- // ── Layout ────────────────────────────────────────────────────────
- Card: ({ props, children }) => {
- const maxWidthClass =
- props.maxWidth === "sm"
- ? "max-w-xs sm:min-w-[280px]"
- : props.maxWidth === "md"
- ? "max-w-sm sm:min-w-[320px]"
- : props.maxWidth === "lg"
- ? "max-w-md sm:min-w-[360px]"
- : "w-full";
- const centeredClass = props.centered ? "mx-auto" : "";
- return (
- <div
- className={`border border-border rounded-xl p-5 bg-card text-card-foreground shadow-sm overflow-hidden h-full flex flex-col ${maxWidthClass} ${centeredClass}`}
- >
- {(props.title || props.description) && (
- <div className="mb-4">
- {props.title && (
- <h3 className="font-semibold text-lg tracking-tight">
- {props.title}
- </h3>
- )}
- {props.description && (
- <p className="text-sm text-muted-foreground mt-1">
- {props.description}
- </p>
- )}
- </div>
- )}
- <div className="flex-1 flex flex-col gap-4 [&>:last-child]:mt-auto">
- {children}
- </div>
- </div>
- );
- },
- Stack: ({ props, children }) => {
- const isHorizontal = props.direction === "horizontal";
- const gapClass =
- props.gap === "lg"
- ? "gap-4"
- : props.gap === "md"
- ? "gap-3"
- : props.gap === "sm"
- ? "gap-2"
- : props.gap === "none"
- ? "gap-0"
- : "gap-3";
- let alignClass: string;
- if (isHorizontal) {
- alignClass =
- props.align === "center"
- ? "items-center"
- : props.align === "end"
- ? "items-end"
- : props.align === "stretch"
- ? "items-stretch"
- : "items-start";
- } else {
- // Vertical: items-center/end lets inline elements (Avatar, Badge, Button)
- // center/align naturally. Block containers (Grid, Accordion, Table) add
- // their own w-full to stretch regardless.
- alignClass =
- props.align === "center"
- ? "items-center"
- : props.align === "end"
- ? "items-end"
- : props.align === "start"
- ? "items-start"
- : "items-stretch";
- }
- const justifyClass =
- props.justify === "center"
- ? "justify-center"
- : props.justify === "end"
- ? "justify-end"
- : props.justify === "between"
- ? "justify-between"
- : props.justify === "around"
- ? "justify-around"
- : "";
- // Horizontal stacks wrap by default; wrap:false keeps a single scrolling
- // row (Kanban boards / column layouts that must sit side by side).
- const horizontalFlow =
- props.wrap === false
- ? "flex-row flex-nowrap overflow-x-auto w-full [&>*]:shrink-0"
- : "flex-row flex-wrap";
- return (
- <div
- className={`flex ${isHorizontal ? horizontalFlow : "flex-col w-full"} ${gapClass} ${alignClass} ${justifyClass}`}
- >
- {children}
- </div>
- );
- },
- Grid: ({ props, children }) => {
- const childCount = Array.isArray(children)
- ? children.length
- : children
- ? 1
- : 0;
- const n = Math.min(props.columns ?? 1, childCount || 1);
- const cols =
- n >= 7
- ? "grid-cols-7"
- : n >= 6
- ? "grid-cols-6"
- : n >= 5
- ? "grid-cols-5"
- : n >= 4
- ? "grid-cols-4"
- : n >= 3
- ? "grid-cols-3"
- : n >= 2
- ? "grid-cols-2"
- : "grid-cols-1";
- const gridGap =
- props.gap === "lg" ? "gap-4" : props.gap === "sm" ? "gap-2" : "gap-3";
- return <div className={`grid w-full ${cols} ${gridGap}`}>{children}</div>;
- },
- Separator: ({ props }) => (
- <Separator
- orientation={props.orientation ?? "horizontal"}
- className={
- props.orientation === "vertical" ? "h-full mx-3" : "my-4 opacity-50"
- }
- />
- ),
- Tabs: ({ props, bindings, emit, children }) => {
- const tabs = props.tabs ?? [];
- const [boundValue, setBoundValue] = useBoundProp<string>(
- props.value as string | undefined,
- bindings?.value,
- );
- const [localValue, setLocalValue] = useState(
- props.defaultValue ?? tabs[0]?.value ?? "",
- );
- const isBound = !!bindings?.value;
- const value = isBound ? (boundValue ?? tabs[0]?.value ?? "") : localValue;
- const setValue = isBound ? setBoundValue : setLocalValue;
- // Children map positionally to tabs: children[i] is the panel for tabs[i].
- const panels = Children.toArray(children);
- return (
- <TabsPrimitive
- value={value}
- onValueChange={(v) => {
- setValue(v);
- emit("change");
- }}
- >
- <TabsList>
- {tabs.map((tab) => (
- <TabsTrigger key={tab.value} value={tab.value}>
- {tab.label}
- </TabsTrigger>
- ))}
- </TabsList>
- {tabs.map((tab, i) => (
- <TabsContent key={tab.value} value={tab.value} className="pt-4">
- {panels[i] ?? null}
- </TabsContent>
- ))}
- </TabsPrimitive>
- );
- },
- Accordion: ({ props }) => {
- const items = props.items ?? [];
- const accordionType = props.type ?? "single";
- if (accordionType === "multiple") {
- return (
- <AccordionPrimitive type="multiple" className="w-full">
- {items.map((item, i) => (
- <AccordionItem key={i} value={`item-${i}`}>
- <AccordionTrigger>{item.title}</AccordionTrigger>
- <AccordionContent>{item.content}</AccordionContent>
- </AccordionItem>
- ))}
- </AccordionPrimitive>
- );
- }
- return (
- <AccordionPrimitive type="single" collapsible className="w-full">
- {items.map((item, i) => (
- <AccordionItem key={i} value={`item-${i}`}>
- <AccordionTrigger>{item.title}</AccordionTrigger>
- <AccordionContent>{item.content}</AccordionContent>
- </AccordionItem>
- ))}
- </AccordionPrimitive>
- );
- },
- Collapsible: ({ props, children }) => {
- const [open, setOpen] = useState(props.defaultOpen ?? false);
- return (
- <Collapsible open={open} onOpenChange={setOpen} className="w-full">
- <CollapsibleTrigger asChild>
- <button className="flex w-full items-center justify-between rounded-md border border-border px-4 py-2 text-sm font-medium hover:bg-muted transition-colors">
- {props.title}
- <svg
- className={`h-4 w-4 transition-transform ${open ? "rotate-180" : ""}`}
- fill="none"
- viewBox="0 0 24 24"
- stroke="currentColor"
- strokeWidth={2}
- >
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- d="M19 9l-7 7-7-7"
- />
- </svg>
- </button>
- </CollapsibleTrigger>
- <CollapsibleContent className="pt-2">{children}</CollapsibleContent>
- </Collapsible>
- );
- },
- Dialog: ({ props, children }) => {
- const [open, setOpen] = useStateBinding<boolean>(props.openPath);
- return (
- <DialogPrimitive open={open ?? false} onOpenChange={(v) => setOpen(v)}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>{props.title}</DialogTitle>
- {props.description && (
- <DialogDescription>{props.description}</DialogDescription>
- )}
- </DialogHeader>
- {children}
- </DialogContent>
- </DialogPrimitive>
- );
- },
- Drawer: ({ props, children }) => {
- const [open, setOpen] = useStateBinding<boolean>(props.openPath);
- return (
- <DrawerPrimitive open={open ?? false} onOpenChange={(v) => setOpen(v)}>
- <DrawerContent>
- <DrawerHeader>
- <DrawerTitle>{props.title}</DrawerTitle>
- {props.description && (
- <DrawerDescription>{props.description}</DrawerDescription>
- )}
- </DrawerHeader>
- <div className="p-4">{children}</div>
- </DrawerContent>
- </DrawerPrimitive>
- );
- },
- Carousel: ({ props }) => {
- const items = props.items ?? [];
- return (
- <CarouselPrimitive className="w-full">
- <CarouselContent>
- {items.map((item, i) => (
- <CarouselItem
- key={i}
- className="basis-3/4 md:basis-1/2 lg:basis-1/3"
- >
- <div className="border border-border rounded-lg p-4 bg-card h-full">
- {item.title && (
- <h4 className="font-semibold text-sm mb-1">{item.title}</h4>
- )}
- {item.description && (
- <p className="text-sm text-muted-foreground">
- {item.description}
- </p>
- )}
- </div>
- </CarouselItem>
- ))}
- </CarouselContent>
- <CarouselPrevious />
- <CarouselNext />
- </CarouselPrimitive>
- );
- },
- // ── Data Display ──────────────────────────────────────────────────
- Table: ({ props }) => {
- const columns = props.columns ?? [];
- const rawRows: unknown[] = Array.isArray(props.rows) ? props.rows : [];
- const rows = rawRows.map((row) => {
- if (Array.isArray(row)) return row.map(String);
- if (row && typeof row === "object") {
- const obj = row as Record<string, unknown>;
- return columns.map((col) =>
- String(obj[col] ?? obj[col.toLowerCase()] ?? ""),
- );
- }
- return columns.map(() => "");
- });
- return (
- <div className="w-full rounded-md border border-border overflow-hidden">
- <TablePrimitive>
- {props.caption && <TableCaption>{props.caption}</TableCaption>}
- <TableHeader>
- <TableRow>
- {columns.map((col) => (
- <TableHead key={col}>{col}</TableHead>
- ))}
- </TableRow>
- </TableHeader>
- <TableBody>
- {rows.map((row, i) => (
- <TableRow key={i}>
- {row.map((cell, j) => (
- <TableCell key={j}>{cell}</TableCell>
- ))}
- </TableRow>
- ))}
- </TableBody>
- </TablePrimitive>
- </div>
- );
- },
- Heading: ({ props }) => {
- const level = props.level ?? "h2";
- const headingClass =
- level === "h1"
- ? "text-2xl font-bold tracking-tight"
- : level === "h3"
- ? "text-base font-semibold tracking-tight"
- : level === "h4"
- ? "text-sm font-medium uppercase tracking-wider text-muted-foreground"
- : "text-xl font-semibold tracking-tight";
- if (level === "h1") return <h1 className={headingClass}>{props.text}</h1>;
- if (level === "h3") return <h3 className={headingClass}>{props.text}</h3>;
- if (level === "h4") return <h4 className={headingClass}>{props.text}</h4>;
- return <h2 className={headingClass}>{props.text}</h2>;
- },
- Text: ({ props }) => {
- const textClass =
- props.variant === "caption"
- ? "text-xs"
- : props.variant === "muted"
- ? "text-sm text-muted-foreground"
- : props.variant === "lead"
- ? "text-xl text-muted-foreground"
- : props.variant === "code"
- ? "font-mono text-sm bg-muted px-1.5 py-0.5 rounded"
- : "text-sm";
- if (props.variant === "code") {
- return <code className={textClass}>{props.text}</code>;
- }
- return <p className={textClass}>{props.text}</p>;
- },
- Image: ({ props }) => {
- const src = typeof props.src === "string" ? props.src.trim() : "";
- if (src) {
- return (
- // eslint-disable-next-line @next/next/no-img-element
- <img
- src={src}
- alt={props.alt ?? ""}
- loading="lazy"
- className="w-full rounded-lg object-cover bg-muted"
- style={{
- maxWidth: props.width ?? undefined,
- height: props.height ?? undefined,
- aspectRatio:
- props.height == null && props.width == null
- ? "16 / 9"
- : undefined,
- }}
- />
- );
- }
- return (
- <div
- className="w-full bg-muted/50 border border-dashed border-border rounded-lg flex flex-col items-center justify-center gap-2 text-muted-foreground/60 px-4"
- style={{
- maxWidth: props.width ?? undefined,
- height: props.height ?? 120,
- minHeight: 80,
- }}
- >
- <svg
- width="32"
- height="32"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="1.5"
- strokeLinecap="round"
- strokeLinejoin="round"
- className="opacity-50"
- >
- <rect width="18" height="18" x="3" y="3" rx="2" ry="2" />
- <circle cx="9" cy="9" r="2" />
- <path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" />
- </svg>
- {props.alt && <span className="text-xs">{props.alt}</span>}
- </div>
- );
- },
- Map: ({ props }) => {
- const query = String(props.query ?? "");
- const zoom = typeof props.zoom === "number" ? props.zoom : 14;
- const height = typeof props.height === "number" ? props.height : 320;
- const src = `https://maps.google.com/maps?q=${encodeURIComponent(
- query,
- )}&z=${zoom}&output=embed`;
- return (
- <iframe
- title={query ? `Map: ${query}` : "Map"}
- src={src}
- className="w-full rounded-lg border border-border"
- style={{ height, minHeight: 200 }}
- loading="lazy"
- referrerPolicy="no-referrer-when-downgrade"
- />
- );
- },
- Pressable: ({ children, emit }) => (
- <button
- type="button"
- onClick={() => emit("press")}
- className="block w-full text-left cursor-pointer rounded-lg transition-transform hover:scale-[1.02] focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- >
- {children}
- </button>
- ),
- // Self-contained photo gallery + lightbox. Manages its own open/index state
- // with React useState — does NOT depend on the json-render setState action.
- Lightbox: ({ props }) => {
- const images = (
- Array.isArray(props.images) ? props.images : []
- ) as Array<{ src: string; caption?: string | null }>;
- const cols =
- props.columns === 2
- ? "grid-cols-2"
- : props.columns === 4
- ? "grid-cols-4"
- : props.columns === 5
- ? "grid-cols-5"
- : props.columns === 6
- ? "grid-cols-6"
- : "grid-cols-3";
- const [openIndex, setOpenIndex] = useState<number | null>(null);
- const current = openIndex !== null ? images[openIndex] : undefined;
- useEffect(() => {
- if (openIndex === null) return;
- const onKey = (e: KeyboardEvent) => {
- if (e.key === "Escape") setOpenIndex(null);
- if (e.key === "ArrowLeft")
- setOpenIndex((i) =>
- i === null ? i : (i - 1 + images.length) % images.length,
- );
- if (e.key === "ArrowRight")
- setOpenIndex((i) => (i === null ? i : (i + 1) % images.length));
- };
- window.addEventListener("keydown", onKey);
- return () => window.removeEventListener("keydown", onKey);
- }, [openIndex, images.length]);
- return (
- <>
- <div className={`grid w-full gap-3 ${cols}`}>
- {images.map((img, i) => (
- <button
- key={i}
- type="button"
- onClick={() => setOpenIndex(i)}
- className="group relative aspect-square overflow-hidden rounded-lg bg-muted focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- >
- {/* eslint-disable-next-line @next/next/no-img-element */}
- <img
- src={img.src}
- alt={img.caption ?? ""}
- loading="lazy"
- className="h-full w-full object-cover transition-transform duration-200 group-hover:scale-105"
- />
- </button>
- ))}
- </div>
- {current && (
- <div
- className="fixed inset-0 z-50 flex items-center justify-center bg-black/85 p-4 backdrop-blur-sm"
- onClick={() => setOpenIndex(null)}
- >
- <button
- type="button"
- aria-label="Close"
- onClick={() => setOpenIndex(null)}
- className="absolute right-4 top-4 flex h-10 w-10 items-center justify-center rounded-full bg-white/10 text-white hover:bg-white/20"
- >
- ✕
- </button>
- {images.length > 1 && (
- <button
- type="button"
- aria-label="Previous"
- onClick={(e) => {
- e.stopPropagation();
- setOpenIndex((i) =>
- i === null ? i : (i - 1 + images.length) % images.length,
- );
- }}
- className="absolute left-4 flex h-12 w-12 items-center justify-center rounded-full bg-white/10 text-2xl text-white hover:bg-white/20"
- >
- ‹
- </button>
- )}
- <figure
- className="flex max-h-[90vh] max-w-[92vw] flex-col items-center gap-3"
- onClick={(e) => e.stopPropagation()}
- >
- {/* eslint-disable-next-line @next/next/no-img-element */}
- <img
- src={current.src}
- alt={current.caption ?? ""}
- className="max-h-[82vh] max-w-full rounded-lg object-contain shadow-2xl"
- />
- {current.caption && (
- <figcaption className="text-sm text-white/80">
- {current.caption}
- <span className="ml-2 text-white/50">
- {(openIndex ?? 0) + 1} / {images.length}
- </span>
- </figcaption>
- )}
- </figure>
- {images.length > 1 && (
- <button
- type="button"
- aria-label="Next"
- onClick={(e) => {
- e.stopPropagation();
- setOpenIndex((i) =>
- i === null ? i : (i + 1) % images.length,
- );
- }}
- className="absolute right-4 flex h-12 w-12 items-center justify-center rounded-full bg-white/10 text-2xl text-white hover:bg-white/20"
- >
- ›
- </button>
- )}
- </div>
- )}
- </>
- );
- },
- // Self-contained modal: renders its own trigger button and manages open
- // state with React useState — no setState / openPath / Dialog needed.
- Modal: ({ props, children }) => {
- const [open, setOpen] = useState(false);
- const variant =
- props.triggerVariant === "outline"
- ? "outline"
- : props.triggerVariant === "secondary"
- ? "secondary"
- : props.triggerVariant === "danger"
- ? "destructive"
- : "default";
- const sizeClass =
- props.size === "lg"
- ? "max-w-2xl"
- : props.size === "sm"
- ? "max-w-sm"
- : "max-w-lg";
- useEffect(() => {
- if (!open) return;
- const onKey = (e: KeyboardEvent) => {
- if (e.key === "Escape") setOpen(false);
- };
- window.addEventListener("keydown", onKey);
- return () => window.removeEventListener("keydown", onKey);
- }, [open]);
- return (
- <>
- <Button variant={variant} onClick={() => setOpen(true)}>
- {props.triggerLabel ?? "Open"}
- </Button>
- {open && (
- <div
- className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm"
- onClick={() => setOpen(false)}
- >
- <div
- role="dialog"
- aria-modal="true"
- className={`w-full ${sizeClass} rounded-xl border border-border bg-background p-6 shadow-2xl`}
- onClick={(e) => e.stopPropagation()}
- >
- <div className="flex items-start justify-between gap-4">
- <div className="min-w-0">
- {props.title && (
- <h2 className="text-lg font-semibold leading-tight">
- {props.title}
- </h2>
- )}
- {props.description && (
- <p className="mt-1 text-sm text-muted-foreground">
- {props.description}
- </p>
- )}
- </div>
- <button
- type="button"
- aria-label="Close"
- onClick={() => setOpen(false)}
- className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground"
- >
- ✕
- </button>
- </div>
- {children && <div className="mt-4">{children}</div>}
- </div>
- </div>
- )}
- </>
- );
- },
- Icon: ({ props }) => {
- const IconComponent = lucideIcons[props.name as keyof typeof lucideIcons];
- if (!IconComponent) return null;
- const sizeMap = {
- sm: 16,
- md: 20,
- lg: 24,
- xl: 32,
- "2xl": 48,
- "3xl": 64,
- } as const;
- const px = sizeMap[props.size ?? "md"] ?? 20;
- const colorClass =
- props.color === "muted"
- ? "text-muted-foreground"
- : props.color === "primary"
- ? "text-primary"
- : props.color === "success"
- ? "text-green-600 dark:text-green-400"
- : props.color === "warning"
- ? "text-yellow-600 dark:text-yellow-400"
- : props.color === "danger"
- ? "text-red-600 dark:text-red-400"
- : "";
- return <IconComponent size={px} className={`shrink-0 ${colorClass}`} />;
- },
- Avatar: ({ props }) => {
- const name = props.name || "?";
- const initials = name
- .split(" ")
- .map((n) => n[0])
- .join("")
- .slice(0, 2)
- .toUpperCase();
- const sizeStyles =
- props.size === "lg"
- ? { outer: "w-[72px] h-[72px]", text: "text-xl", ring: "ring-[3px]" }
- : props.size === "sm"
- ? { outer: "w-8 h-8", text: "text-xs", ring: "ring-2" }
- : { outer: "w-10 h-10", text: "text-sm", ring: "ring-2" };
- return (
- <div
- className={`${sizeStyles.outer} ${sizeStyles.text} rounded-full bg-gradient-to-br from-muted-foreground/20 to-muted flex items-center justify-center font-semibold tracking-wide ${sizeStyles.ring} ring-background shadow-sm`}
- >
- {initials}
- </div>
- );
- },
- Badge: ({ props }) => {
- const variant =
- props.variant === "success" || props.variant === "warning"
- ? "secondary"
- : props.variant === "danger"
- ? "destructive"
- : "default";
- const customClass =
- props.variant === "success"
- ? "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-100"
- : props.variant === "warning"
- ? "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-100"
- : "";
- const dotColor =
- props.variant === "success"
- ? "bg-green-500"
- : props.variant === "warning"
- ? "bg-yellow-500"
- : props.variant === "danger"
- ? "bg-red-500"
- : "";
- return (
- <Badge variant={variant} className={`${customClass} gap-1.5`}>
- {dotColor && (
- <span className={`w-1.5 h-1.5 rounded-full ${dotColor} shrink-0`} />
- )}
- {props.text}
- </Badge>
- );
- },
- Alert: ({ props }) => {
- const variant = props.type === "error" ? "destructive" : "default";
- const customClass =
- props.type === "success"
- ? "border-green-200 bg-green-50 text-green-900 dark:border-green-800 dark:bg-green-950 dark:text-green-100"
- : props.type === "warning"
- ? "border-yellow-200 bg-yellow-50 text-yellow-900 dark:border-yellow-800 dark:bg-yellow-950 dark:text-yellow-100"
- : props.type === "info"
- ? "border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"
- : "";
- const iconProps = {
- width: 16,
- height: 16,
- viewBox: "0 0 24 24",
- fill: "none",
- stroke: "currentColor",
- strokeWidth: 2,
- strokeLinecap: "round" as const,
- strokeLinejoin: "round" as const,
- className: "shrink-0",
- };
- const icon =
- props.type === "success" ? (
- <svg {...iconProps}>
- <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
- <polyline points="22 4 12 14.01 9 11.01" />
- </svg>
- ) : props.type === "warning" ? (
- <svg {...iconProps}>
- <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z" />
- <line x1="12" y1="9" x2="12" y2="13" />
- <line x1="12" y1="17" x2="12.01" y2="17" />
- </svg>
- ) : props.type === "error" ? (
- <svg {...iconProps}>
- <circle cx="12" cy="12" r="10" />
- <line x1="15" y1="9" x2="9" y2="15" />
- <line x1="9" y1="9" x2="15" y2="15" />
- </svg>
- ) : (
- <svg {...iconProps}>
- <circle cx="12" cy="12" r="10" />
- <line x1="12" y1="16" x2="12" y2="12" />
- <line x1="12" y1="8" x2="12.01" y2="8" />
- </svg>
- );
- return (
- <Alert variant={variant} className={customClass}>
- {icon}
- <AlertTitle>{props.title}</AlertTitle>
- {props.message && (
- <AlertDescription>{props.message}</AlertDescription>
- )}
- </Alert>
- );
- },
- Progress: ({ props }) => {
- const value = Math.min(100, Math.max(0, props.value || 0));
- return (
- <div className="w-full space-y-2">
- {props.label && (
- <Label className="text-sm text-muted-foreground">
- {props.label}
- </Label>
- )}
- <Progress value={value} />
- </div>
- );
- },
- Skeleton: ({ props }) => (
- <Skeleton
- className={props.rounded ? "rounded-full" : "rounded-md"}
- style={{
- width: props.width ?? "100%",
- height: props.height ?? "1.25rem",
- }}
- />
- ),
- Spinner: ({ props }) => {
- const sizeClass =
- props.size === "lg"
- ? "h-8 w-8"
- : props.size === "sm"
- ? "h-4 w-4"
- : "h-6 w-6";
- return (
- <div className="flex items-center gap-2">
- <svg
- className={`${sizeClass} animate-spin text-muted-foreground`}
- viewBox="0 0 24 24"
- fill="none"
- >
- <circle
- className="opacity-25"
- cx="12"
- cy="12"
- r="10"
- stroke="currentColor"
- strokeWidth="4"
- />
- <path
- className="opacity-75"
- fill="currentColor"
- d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
- />
- </svg>
- {props.label && (
- <span className="text-sm text-muted-foreground">{props.label}</span>
- )}
- </div>
- );
- },
- Tooltip: ({ props }) => (
- <TooltipProvider>
- <TooltipPrimitive>
- <TooltipTrigger asChild>
- <span className="text-sm underline decoration-dotted cursor-help">
- {props.text}
- </span>
- </TooltipTrigger>
- <TooltipContent>
- <p>{props.content}</p>
- </TooltipContent>
- </TooltipPrimitive>
- </TooltipProvider>
- ),
- Popover: ({ props }) => (
- <PopoverPrimitive>
- <PopoverTrigger asChild>
- <Button variant="outline" className="text-sm">
- {props.trigger}
- </Button>
- </PopoverTrigger>
- <PopoverContent className="w-64">
- <p className="text-sm">{props.content}</p>
- </PopoverContent>
- </PopoverPrimitive>
- ),
- Rating: ({ props, bindings, emit }) => {
- const [boundValue, setBoundValue] = useBoundProp<number>(
- props.value as number | undefined,
- bindings?.value,
- );
- const [localValue, setLocalValue] = useState(props.value || 0);
- const isBound = !!bindings?.value;
- const ratingValue = isBound ? (boundValue ?? 0) : localValue;
- const setValue = isBound ? setBoundValue : setLocalValue;
- const maxRating = props.max ?? 5;
- const interactive = props.interactive !== false;
- const [hoverIndex, setHoverIndex] = useState(-1);
- return (
- <div className="space-y-2">
- {props.label && (
- <Label className="text-sm text-muted-foreground">
- {props.label}
- </Label>
- )}
- <div
- className="flex gap-0.5"
- onMouseLeave={() => interactive && setHoverIndex(-1)}
- >
- {Array.from({ length: maxRating }).map((_, i) => {
- const filled =
- hoverIndex >= 0 ? i <= hoverIndex : i < ratingValue;
- return (
- <button
- key={i}
- type="button"
- className={`p-0.5 transition-colors ${interactive ? "cursor-pointer hover:scale-110" : "cursor-default"}`}
- onMouseEnter={() => interactive && setHoverIndex(i)}
- onClick={() => {
- if (!interactive) return;
- const newVal = i + 1 === ratingValue ? 0 : i + 1;
- setValue(newVal);
- emit("change");
- }}
- >
- <svg
- width="20"
- height="20"
- viewBox="0 0 24 24"
- fill={filled ? "currentColor" : "none"}
- stroke="currentColor"
- strokeWidth="1.5"
- strokeLinecap="round"
- strokeLinejoin="round"
- className={
- filled ? "text-yellow-400" : "text-muted-foreground/40"
- }
- >
- <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
- </svg>
- </button>
- );
- })}
- </div>
- </div>
- );
- },
- Timeline: ({ props }) => (
- <div className="relative pl-8">
- <div className="absolute left-[5.5px] top-3 bottom-3 w-px bg-border" />
- <div className="flex flex-col gap-6">
- {(props.items ?? []).map((item, i) => {
- const dotColor =
- item.status === "completed"
- ? "bg-emerald-500"
- : item.status === "current"
- ? "bg-blue-500"
- : "bg-muted-foreground/30";
- return (
- <div key={i} className="relative">
- <div
- className={`absolute -left-8 top-0.5 h-3 w-3 rounded-full ${dotColor} ring-2 ring-background`}
- />
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2 flex-wrap">
- <p className="font-medium text-sm">{item.title}</p>
- {item.date && (
- <span className="text-xs text-muted-foreground bg-muted px-1.5 py-0.5 rounded">
- {item.date}
- </span>
- )}
- </div>
- {item.description && (
- <p className="text-sm text-muted-foreground mt-1">
- {item.description}
- </p>
- )}
- </div>
- </div>
- );
- })}
- </div>
- </div>
- ),
- Metric: ({ props }) => {
- const changeColor =
- props.changeType === "positive"
- ? "text-green-600 dark:text-green-400"
- : props.changeType === "negative"
- ? "text-red-600 dark:text-red-400"
- : "text-muted-foreground";
- const changeIcon =
- props.changeType === "positive"
- ? "\u2191"
- : props.changeType === "negative"
- ? "\u2193"
- : "";
- return (
- <div className="space-y-1">
- <div className="text-sm text-muted-foreground">{props.label}</div>
- <div className="flex items-baseline gap-1.5">
- <span className="text-2xl font-semibold tracking-tight tabular-nums">
- {props.prefix}
- {props.value}
- {props.suffix}
- </span>
- {props.change && (
- <span className={`text-sm font-medium ${changeColor}`}>
- {changeIcon}
- {props.change}
- </span>
- )}
- </div>
- </div>
- );
- },
- // ── Charts ────────────────────────────────────────────────────────
- BarGraph: ({ props }) => {
- const data = props.data || [];
- const maxValue = Math.max(...data.map((d) => d.value), 1);
- const barColors = [
- "bg-primary",
- "bg-primary/80",
- "bg-primary/60",
- "bg-primary/70",
- "bg-primary/90",
- "bg-primary/50",
- ];
- return (
- <div className="space-y-3">
- {props.title && (
- <div className="text-sm font-medium">{props.title}</div>
- )}
- <div className="flex items-end gap-2" style={{ height: 160 }}>
- {data.map((d, i) => (
- <div
- key={i}
- className="flex-1 flex flex-col items-center gap-1.5 h-full justify-end group"
- >
- <div className="text-[11px] font-medium text-muted-foreground tabular-nums">
- {d.value}
- </div>
- <div className="w-full flex-1 flex items-end">
- <div
- className={`w-full ${barColors[i % barColors.length]} rounded-t-md transition-all group-hover:opacity-80`}
- style={{
- height: `${(d.value / maxValue) * 100}%`,
- minHeight: 4,
- }}
- />
- </div>
- <div className="text-[11px] text-muted-foreground truncate w-full text-center">
- {d.label}
- </div>
- </div>
- ))}
- </div>
- </div>
- );
- },
- LineGraph: ({ props }) => {
- const data = props.data || [];
- const maxValue = Math.max(...data.map((d) => d.value));
- const minValue = Math.min(...data.map((d) => d.value));
- const range = maxValue - minValue || 1;
- const width = 300;
- const height = 140;
- const padding = { top: 12, right: 12, bottom: 12, left: 12 };
- const chartWidth = width - padding.left - padding.right;
- const chartHeight = height - padding.top - padding.bottom;
- const points = data.map((d, i) => {
- const x =
- padding.left +
- (data.length > 1
- ? (i / (data.length - 1)) * chartWidth
- : chartWidth / 2);
- const y =
- padding.top +
- chartHeight -
- ((d.value - minValue) / range) * chartHeight;
- return { x, y, ...d };
- });
- // Build smooth cubic bezier curve through points
- let smoothPath = "";
- let areaPath = "";
- if (points.length > 1) {
- const first = points[0]!;
- const last = points[points.length - 1]!;
- smoothPath = `M ${first.x} ${first.y}`;
- for (let i = 0; i < points.length - 1; i++) {
- const curr = points[i]!;
- const next = points[i + 1]!;
- const cpx = (curr.x + next.x) / 2;
- smoothPath += ` C ${cpx} ${curr.y}, ${cpx} ${next.y}, ${next.x} ${next.y}`;
- }
- const bottomY = height - padding.bottom;
- areaPath = `${smoothPath} L ${last.x} ${bottomY} L ${first.x} ${bottomY} Z`;
- } else if (points.length === 1) {
- const only = points[0]!;
- smoothPath = `M ${only.x} ${only.y}`;
- }
- const gradientId = `line-gradient-${Math.random().toString(36).slice(2, 8)}`;
- return (
- <div className="space-y-3">
- {props.title && (
- <div className="text-sm font-medium">{props.title}</div>
- )}
- <div className="relative" style={{ height: 160 }}>
- <svg
- viewBox={`0 0 ${width} ${height}`}
- className="w-full h-full"
- preserveAspectRatio="none"
- >
- <defs>
- <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
- <stop
- offset="0%"
- stopColor="currentColor"
- stopOpacity="0.15"
- />
- <stop
- offset="100%"
- stopColor="currentColor"
- stopOpacity="0"
- />
- </linearGradient>
- </defs>
- {[0, 0.25, 0.5, 0.75, 1].map((frac) => (
- <line
- key={frac}
- x1={padding.left}
- y1={padding.top + chartHeight * frac}
- x2={width - padding.right}
- y2={padding.top + chartHeight * frac}
- stroke="currentColor"
- strokeOpacity="0.07"
- vectorEffect="non-scaling-stroke"
- strokeWidth="1"
- />
- ))}
- {areaPath && (
- <path
- d={areaPath}
- fill={`url(#${gradientId})`}
- className="text-primary"
- />
- )}
- {smoothPath && (
- <path
- d={smoothPath}
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- strokeLinejoin="round"
- vectorEffect="non-scaling-stroke"
- className="text-primary"
- />
- )}
- </svg>
- {points.map((p, i) => (
- <div
- key={i}
- className="absolute w-[7px] h-[7px] rounded-full bg-primary -translate-x-1/2 -translate-y-1/2"
- style={{
- left: `${(p.x / width) * 100}%`,
- top: `${(p.y / height) * 100}%`,
- }}
- />
- ))}
- </div>
- {points.length > 0 && (
- <div className="relative h-4">
- {points.map((p, i) => (
- <span
- key={i}
- className="absolute text-[11px] text-muted-foreground -translate-x-1/2"
- style={{ left: `${(p.x / width) * 100}%` }}
- >
- {data[i]?.label}
- </span>
- ))}
- </div>
- )}
- </div>
- );
- },
- // ── Form Inputs ───────────────────────────────────────────────────
- Input: ({ props, bindings, emit }) => {
- const [boundValue, setBoundValue] = useBoundProp<string>(
- props.value as string | undefined,
- bindings?.value,
- );
- const [localValue, setLocalValue] = useState("");
- const isBound = !!bindings?.value;
- const value = isBound ? (boundValue ?? "") : localValue;
- const setValue = isBound ? setBoundValue : setLocalValue;
- const hasValidation = !!(bindings?.value && props.checks?.length);
- const { errors, validate } = useFieldValidation(
- bindings?.value ?? "",
- hasValidation ? { checks: props.checks ?? [] } : undefined,
- );
- return (
- <div className="w-full space-y-2">
- {props.label && <Label htmlFor={props.name}>{props.label}</Label>}
- <Input
- id={props.name}
- name={props.name}
- type={props.type ?? "text"}
- placeholder={props.placeholder ?? ""}
- value={value}
- onChange={(e) => setValue(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter") emit("submit");
- }}
- onFocus={() => emit("focus")}
- onBlur={() => {
- if (hasValidation) validate();
- emit("blur");
- }}
- />
- {errors.length > 0 && (
- <p className="text-sm text-destructive">{errors[0]}</p>
- )}
- </div>
- );
- },
- Textarea: ({ props, bindings }) => {
- const [boundValue, setBoundValue] = useBoundProp<string>(
- props.value as string | undefined,
- bindings?.value,
- );
- const [localValue, setLocalValue] = useState("");
- const isBound = !!bindings?.value;
- const value = isBound ? (boundValue ?? "") : localValue;
- const setValue = isBound ? setBoundValue : setLocalValue;
- const hasValidation = !!(bindings?.value && props.checks?.length);
- const { errors, validate } = useFieldValidation(
- bindings?.value ?? "",
- hasValidation ? { checks: props.checks ?? [] } : undefined,
- );
- return (
- <div className="w-full space-y-2">
- {props.label && <Label htmlFor={props.name}>{props.label}</Label>}
- <Textarea
- id={props.name}
- name={props.name}
- placeholder={props.placeholder ?? ""}
- rows={props.rows ?? 3}
- value={value}
- onChange={(e) => setValue(e.target.value)}
- onBlur={() => {
- if (hasValidation) validate();
- }}
- />
- {errors.length > 0 && (
- <p className="text-sm text-destructive">{errors[0]}</p>
- )}
- </div>
- );
- },
- Select: ({ props, bindings, emit }) => {
- const [boundValue, setBoundValue] = useBoundProp<string>(
- props.value as string | undefined,
- bindings?.value,
- );
- const [localValue, setLocalValue] = useState<string>("");
- const isBound = !!bindings?.value;
- const value = isBound ? (boundValue ?? "") : localValue;
- const setValue = isBound ? setBoundValue : setLocalValue;
- const rawOptions = props.options ?? [];
- // Coerce options to strings – AI may produce objects/numbers instead of
- // plain strings which would cause duplicate `[object Object]` keys.
- const options = rawOptions.map((opt) =>
- typeof opt === "string" ? opt : String(opt ?? ""),
- );
- const hasValidation = !!(bindings?.value && props.checks?.length);
- const { errors, validate } = useFieldValidation(
- bindings?.value ?? "",
- hasValidation ? { checks: props.checks ?? [] } : undefined,
- );
- return (
- <div className="w-full space-y-2">
- <Label>{props.label}</Label>
- <Select
- value={value}
- onValueChange={(v) => {
- setValue(v);
- if (hasValidation) validate();
- emit("change");
- }}
- >
- <SelectTrigger className="w-full">
- <SelectValue placeholder={props.placeholder ?? "Select..."} />
- </SelectTrigger>
- <SelectContent>
- {options.map((opt, idx) => (
- <SelectItem
- key={`${idx}-${opt}`}
- value={opt || `option-${idx}`}
- >
- {opt}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- {errors.length > 0 && (
- <p className="text-sm text-destructive">{errors[0]}</p>
- )}
- </div>
- );
- },
- Checkbox: ({ props, bindings, emit }) => {
- const [boundChecked, setBoundChecked] = useBoundProp<boolean>(
- props.checked as boolean | undefined,
- bindings?.checked,
- );
- const [localChecked, setLocalChecked] = useState(!!props.checked);
- const isBound = !!bindings?.checked;
- const checked = isBound ? (boundChecked ?? false) : localChecked;
- const setChecked = isBound ? setBoundChecked : setLocalChecked;
- return (
- <div className="flex items-center space-x-2">
- <Checkbox
- id={props.name}
- checked={checked}
- onCheckedChange={(c) => {
- setChecked(c === true);
- emit("change");
- }}
- />
- <Label htmlFor={props.name} className="cursor-pointer">
- {props.label}
- </Label>
- </div>
- );
- },
- Radio: ({ props, bindings, emit }) => {
- const rawOptions = props.options ?? [];
- const options = rawOptions.map((opt) =>
- typeof opt === "string" ? opt : String(opt ?? ""),
- );
- const [boundValue, setBoundValue] = useBoundProp<string>(
- props.value as string | undefined,
- bindings?.value,
- );
- const [localValue, setLocalValue] = useState(options[0] ?? "");
- const isBound = !!bindings?.value;
- const value = isBound ? (boundValue ?? "") : localValue;
- const setValue = isBound ? setBoundValue : setLocalValue;
- return (
- <div className="w-full space-y-2">
- {props.label && <Label>{props.label}</Label>}
- <RadioGroup
- value={value}
- onValueChange={(v) => {
- setValue(v);
- emit("change");
- }}
- >
- {options.map((opt, idx) => (
- <div
- key={`${idx}-${opt}`}
- className="flex items-center space-x-2"
- >
- <RadioGroupItem
- value={opt || `option-${idx}`}
- id={`${props.name}-${idx}-${opt}`}
- />
- <Label
- htmlFor={`${props.name}-${idx}-${opt}`}
- className="cursor-pointer"
- >
- {opt}
- </Label>
- </div>
- ))}
- </RadioGroup>
- </div>
- );
- },
- Switch: ({ props, bindings, emit }) => {
- const [boundChecked, setBoundChecked] = useBoundProp<boolean>(
- props.checked as boolean | undefined,
- bindings?.checked,
- );
- const [localChecked, setLocalChecked] = useState(!!props.checked);
- const isBound = !!bindings?.checked;
- const checked = isBound ? (boundChecked ?? false) : localChecked;
- const setChecked = isBound ? setBoundChecked : setLocalChecked;
- return (
- <div className="w-full flex items-center justify-between space-x-2">
- <Label htmlFor={props.name} className="cursor-pointer">
- {props.label}
- </Label>
- <Switch
- id={props.name}
- checked={checked}
- onCheckedChange={(c) => {
- setChecked(c);
- emit("change");
- }}
- />
- </div>
- );
- },
- Slider: ({ props, bindings, emit }) => {
- const [boundValue, setBoundValue] = useBoundProp<number>(
- props.value as number | undefined,
- bindings?.value,
- );
- const [localValue, setLocalValue] = useState(props.min ?? 0);
- const isBound = !!bindings?.value;
- const value = isBound ? (boundValue ?? props.min ?? 0) : localValue;
- const setValue = isBound ? setBoundValue : setLocalValue;
- return (
- <div className="w-full space-y-2">
- {props.label && (
- <div className="flex justify-between">
- <Label className="text-sm">{props.label}</Label>
- <span className="text-sm text-muted-foreground">{value}</span>
- </div>
- )}
- <Slider
- value={[value]}
- min={props.min ?? 0}
- max={props.max ?? 100}
- step={props.step ?? 1}
- onValueChange={(v) => {
- setValue(v[0] ?? 0);
- emit("change");
- }}
- />
- </div>
- );
- },
- // ── Actions ───────────────────────────────────────────────────────
- Button: ({ props, emit }) => {
- const variant =
- props.variant === "danger"
- ? "destructive"
- : props.variant === "outline"
- ? "outline"
- : props.variant === "secondary"
- ? "secondary"
- : "default";
- return (
- <Button
- variant={variant}
- disabled={props.disabled ?? false}
- onClick={() => emit("press")}
- >
- {props.label}
- </Button>
- );
- },
- Link: ({ props, emit }) => (
- <Button
- variant="link"
- className="h-auto p-0"
- onClick={() => emit("press")}
- >
- {props.label}
- </Button>
- ),
- DropdownMenu: ({ props, emit }) => {
- const items = props.items ?? [];
- return (
- <DropdownMenuPrimitive>
- <DropdownMenuTrigger asChild>
- <Button variant="outline">{props.label}</Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- {items.map((item) => (
- <DropdownMenuItem key={item.value} onClick={() => emit("select")}>
- {item.label}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenuPrimitive>
- );
- },
- Toggle: ({ props, bindings, emit }) => {
- const [boundPressed, setBoundPressed] = useBoundProp<boolean>(
- props.pressed as boolean | undefined,
- bindings?.pressed,
- );
- const [localPressed, setLocalPressed] = useState(props.pressed ?? false);
- const isBound = !!bindings?.pressed;
- const pressed = isBound ? (boundPressed ?? false) : localPressed;
- const setPressed = isBound ? setBoundPressed : setLocalPressed;
- return (
- <Toggle
- variant={props.variant ?? "default"}
- pressed={pressed}
- onPressedChange={(v) => {
- setPressed(v);
- emit("change");
- }}
- >
- {props.label}
- </Toggle>
- );
- },
- ToggleGroup: ({ props, bindings, emit }) => {
- const type = props.type ?? "single";
- const items = props.items ?? [];
- const [boundValue, setBoundValue] = useBoundProp<string>(
- props.value as string | undefined,
- bindings?.value,
- );
- const [localValue, setLocalValue] = useState(items[0]?.value ?? "");
- const isBound = !!bindings?.value;
- const value = isBound ? (boundValue ?? "") : localValue;
- const setValue = isBound ? setBoundValue : setLocalValue;
- if (type === "multiple") {
- return (
- <ToggleGroup type="multiple">
- {items.map((item) => (
- <ToggleGroupItem key={item.value} value={item.value}>
- {item.label}
- </ToggleGroupItem>
- ))}
- </ToggleGroup>
- );
- }
- return (
- <ToggleGroup
- type="single"
- value={value}
- onValueChange={(v) => {
- if (v) {
- setValue(v);
- emit("change");
- }
- }}
- >
- {items.map((item) => (
- <ToggleGroupItem key={item.value} value={item.value}>
- {item.label}
- </ToggleGroupItem>
- ))}
- </ToggleGroup>
- );
- },
- ButtonGroup: ({ props, bindings, emit }) => {
- const buttons = props.buttons ?? [];
- const [boundSelected, setBoundSelected] = useBoundProp<string>(
- props.selected as string | undefined,
- bindings?.selected,
- );
- const [localValue, setLocalValue] = useState(buttons[0]?.value ?? "");
- const isBound = !!bindings?.selected;
- const value = isBound ? (boundSelected ?? "") : localValue;
- const setValue = isBound ? setBoundSelected : setLocalValue;
- return (
- <div className="inline-flex rounded-md border border-border">
- {buttons.map((btn, i) => (
- <button
- key={btn.value}
- className={`px-3 py-1.5 text-sm transition-colors ${
- value === btn.value
- ? "bg-primary text-primary-foreground"
- : "bg-background hover:bg-muted"
- } ${i > 0 ? "border-l border-border" : ""} ${
- i === 0 ? "rounded-l-md" : ""
- } ${i === buttons.length - 1 ? "rounded-r-md" : ""}`}
- onClick={() => {
- setValue(btn.value);
- emit("change");
- }}
- >
- {btn.label}
- </button>
- ))}
- </div>
- );
- },
- Pagination: ({ props, bindings, emit }) => {
- const [boundPage, setBoundPage] = useBoundProp<number>(
- props.page as number | undefined,
- bindings?.page,
- );
- const currentPage = boundPage ?? 1;
- const pages = Array.from({ length: props.totalPages }, (_, i) => i + 1);
- return (
- <PaginationPrimitive>
- <PaginationContent>
- <PaginationItem>
- <PaginationPrevious
- href="#"
- onClick={(e) => {
- e.preventDefault();
- if (currentPage > 1) {
- setBoundPage(currentPage - 1);
- emit("change");
- }
- }}
- />
- </PaginationItem>
- {pages.map((page) => (
- <PaginationItem key={page}>
- <PaginationLink
- href="#"
- isActive={page === currentPage}
- onClick={(e) => {
- e.preventDefault();
- setBoundPage(page);
- emit("change");
- }}
- >
- {page}
- </PaginationLink>
- </PaginationItem>
- ))}
- <PaginationItem>
- <PaginationNext
- href="#"
- onClick={(e) => {
- e.preventDefault();
- if (currentPage < props.totalPages) {
- setBoundPage(currentPage + 1);
- emit("change");
- }
- }}
- />
- </PaginationItem>
- </PaginationContent>
- </PaginationPrimitive>
- );
- },
- },
- actions: {
- // Built-in state actions — handled by ActionProvider, stubs needed for types
- setState: async () => {},
- pushState: async () => {},
- removeState: async () => {},
- // Demo actions — show toasts
- buttonClick: async (params) => {
- const message = (params?.message as string) || "Button clicked!";
- toast.success(message);
- },
- formSubmit: async (params) => {
- const formName = (params?.formName as string) || "Form";
- toast.success(`${formName} submitted successfully!`);
- },
- linkClick: async (params) => {
- const href = (params?.href as string) || "#";
- toast.info(`Navigating to: ${href}`);
- },
- },
- });
- // Fallback component for unknown types
- export function Fallback({ type }: { type: string }) {
- return <div className="text-xs text-muted-foreground">[{type}]</div>;
- }
|