registry.tsx 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  1. "use client";
  2. import { useState } from "react";
  3. import { defineRegistry, useStateBinding } from "@json-render/react";
  4. import { toast } from "sonner";
  5. import { playgroundCatalog } from "./catalog";
  6. // shadcn components
  7. import { Button } from "@/components/ui/button";
  8. import { Input } from "@/components/ui/input";
  9. import { Label } from "@/components/ui/label";
  10. import { Textarea } from "@/components/ui/textarea";
  11. import { Checkbox } from "@/components/ui/checkbox";
  12. import { Switch } from "@/components/ui/switch";
  13. import { Progress } from "@/components/ui/progress";
  14. import { Separator } from "@/components/ui/separator";
  15. import { Alert, AlertTitle, AlertDescription } from "@/components/ui/alert";
  16. import {
  17. Dialog as DialogPrimitive,
  18. DialogContent,
  19. DialogDescription,
  20. DialogHeader,
  21. DialogTitle,
  22. } from "@/components/ui/dialog";
  23. import {
  24. Accordion as AccordionPrimitive,
  25. AccordionContent,
  26. AccordionItem,
  27. AccordionTrigger,
  28. } from "@/components/ui/accordion";
  29. import { Badge } from "@/components/ui/badge";
  30. import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
  31. import {
  32. Select,
  33. SelectContent,
  34. SelectItem,
  35. SelectTrigger,
  36. SelectValue,
  37. } from "@/components/ui/select";
  38. import {
  39. Carousel as CarouselPrimitive,
  40. CarouselContent,
  41. CarouselItem,
  42. CarouselNext,
  43. CarouselPrevious,
  44. } from "@/components/ui/carousel";
  45. import {
  46. Collapsible,
  47. CollapsibleContent,
  48. CollapsibleTrigger,
  49. } from "@/components/ui/collapsible";
  50. import {
  51. Table as TablePrimitive,
  52. TableBody,
  53. TableCaption,
  54. TableCell,
  55. TableHead,
  56. TableHeader,
  57. TableRow,
  58. } from "@/components/ui/table";
  59. import {
  60. Drawer as DrawerPrimitive,
  61. DrawerContent,
  62. DrawerDescription,
  63. DrawerHeader,
  64. DrawerTitle,
  65. } from "@/components/ui/drawer";
  66. import {
  67. DropdownMenu as DropdownMenuPrimitive,
  68. DropdownMenuContent,
  69. DropdownMenuItem,
  70. DropdownMenuTrigger,
  71. } from "@/components/ui/dropdown-menu";
  72. import {
  73. Pagination as PaginationPrimitive,
  74. PaginationContent,
  75. PaginationItem,
  76. PaginationLink,
  77. PaginationNext,
  78. PaginationPrevious,
  79. } from "@/components/ui/pagination";
  80. import {
  81. Popover as PopoverPrimitive,
  82. PopoverContent,
  83. PopoverTrigger,
  84. } from "@/components/ui/popover";
  85. import { Skeleton } from "@/components/ui/skeleton";
  86. import { Slider } from "@/components/ui/slider";
  87. import {
  88. Tabs as TabsPrimitive,
  89. TabsList,
  90. TabsTrigger,
  91. } from "@/components/ui/tabs";
  92. import { Toggle } from "@/components/ui/toggle";
  93. import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
  94. import {
  95. Tooltip as TooltipPrimitive,
  96. TooltipContent,
  97. TooltipProvider,
  98. TooltipTrigger,
  99. } from "@/components/ui/tooltip";
  100. // =============================================================================
  101. // Registry — components + actions, types inferred from catalog
  102. // =============================================================================
  103. export const { registry, executeAction } = defineRegistry(playgroundCatalog, {
  104. components: {
  105. // ── Layout ────────────────────────────────────────────────────────
  106. Card: ({ props, children }) => {
  107. const maxWidthClass =
  108. props.maxWidth === "sm"
  109. ? "max-w-xs sm:min-w-[280px]"
  110. : props.maxWidth === "md"
  111. ? "max-w-sm sm:min-w-[320px]"
  112. : props.maxWidth === "lg"
  113. ? "max-w-md sm:min-w-[360px]"
  114. : "w-full";
  115. const centeredClass = props.centered ? "mx-auto" : "";
  116. return (
  117. <div
  118. className={`border border-border rounded-lg p-4 bg-card text-card-foreground overflow-hidden ${maxWidthClass} ${centeredClass}`}
  119. >
  120. {(props.title || props.description) && (
  121. <div className="mb-4">
  122. {props.title && (
  123. <h3 className="font-semibold text-lg text-left">
  124. {props.title}
  125. </h3>
  126. )}
  127. {props.description && (
  128. <p className="text-sm text-muted-foreground mt-1 text-left">
  129. {props.description}
  130. </p>
  131. )}
  132. </div>
  133. )}
  134. <div className="space-y-3">{children}</div>
  135. </div>
  136. );
  137. },
  138. Stack: ({ props, children }) => {
  139. const isHorizontal = props.direction === "horizontal";
  140. const gapClass =
  141. props.gap === "lg"
  142. ? "gap-4"
  143. : props.gap === "md"
  144. ? "gap-3"
  145. : props.gap === "sm"
  146. ? "gap-2"
  147. : props.gap === "none"
  148. ? "gap-0"
  149. : "gap-3";
  150. const alignClass =
  151. props.align === "center"
  152. ? "items-center"
  153. : props.align === "end"
  154. ? "items-end"
  155. : props.align === "stretch"
  156. ? "items-stretch"
  157. : "items-start";
  158. const justifyClass =
  159. props.justify === "center"
  160. ? "justify-center"
  161. : props.justify === "end"
  162. ? "justify-end"
  163. : props.justify === "between"
  164. ? "justify-between"
  165. : props.justify === "around"
  166. ? "justify-around"
  167. : "";
  168. return (
  169. <div
  170. className={`flex ${isHorizontal ? "flex-row flex-wrap" : "flex-col"} ${gapClass} ${alignClass} ${justifyClass}`}
  171. >
  172. {children}
  173. </div>
  174. );
  175. },
  176. Grid: ({ props, children }) => {
  177. const n = props.columns ?? 1;
  178. const cols =
  179. n >= 6
  180. ? "grid-cols-6"
  181. : n >= 5
  182. ? "grid-cols-5"
  183. : n >= 4
  184. ? "grid-cols-4"
  185. : n >= 3
  186. ? "grid-cols-3"
  187. : n >= 2
  188. ? "grid-cols-2"
  189. : "grid-cols-1";
  190. const gridGap =
  191. props.gap === "lg" ? "gap-4" : props.gap === "sm" ? "gap-2" : "gap-3";
  192. return <div className={`grid ${cols} ${gridGap}`}>{children}</div>;
  193. },
  194. Separator: ({ props }) => (
  195. <Separator
  196. orientation={props.orientation ?? "horizontal"}
  197. className={props.orientation === "vertical" ? "h-full mx-2" : "my-3"}
  198. />
  199. ),
  200. Tabs: ({ props, emit }) => {
  201. const tabs = props.tabs ?? [];
  202. const [boundValue, setBoundValue] = props.statePath
  203. ? useStateBinding<string>(props.statePath) // eslint-disable-line react-hooks/rules-of-hooks
  204. : [undefined, undefined];
  205. const [localValue, setLocalValue] = useState(
  206. props.defaultValue ?? tabs[0]?.value ?? "",
  207. );
  208. const value = props.statePath
  209. ? (boundValue ?? tabs[0]?.value ?? "")
  210. : localValue;
  211. const setValue = props.statePath ? setBoundValue! : setLocalValue;
  212. return (
  213. <TabsPrimitive
  214. value={value}
  215. onValueChange={(v) => {
  216. setValue(v);
  217. emit?.("change");
  218. }}
  219. >
  220. <TabsList>
  221. {tabs.map((tab) => (
  222. <TabsTrigger key={tab.value} value={tab.value}>
  223. {tab.label}
  224. </TabsTrigger>
  225. ))}
  226. </TabsList>
  227. </TabsPrimitive>
  228. );
  229. },
  230. Accordion: ({ props }) => {
  231. const items = props.items ?? [];
  232. const accordionType = props.type ?? "single";
  233. if (accordionType === "multiple") {
  234. return (
  235. <AccordionPrimitive type="multiple" className="w-full">
  236. {items.map((item, i) => (
  237. <AccordionItem key={i} value={`item-${i}`}>
  238. <AccordionTrigger>{item.title}</AccordionTrigger>
  239. <AccordionContent>{item.content}</AccordionContent>
  240. </AccordionItem>
  241. ))}
  242. </AccordionPrimitive>
  243. );
  244. }
  245. return (
  246. <AccordionPrimitive type="single" collapsible className="w-full">
  247. {items.map((item, i) => (
  248. <AccordionItem key={i} value={`item-${i}`}>
  249. <AccordionTrigger>{item.title}</AccordionTrigger>
  250. <AccordionContent>{item.content}</AccordionContent>
  251. </AccordionItem>
  252. ))}
  253. </AccordionPrimitive>
  254. );
  255. },
  256. Collapsible: ({ props, children }) => {
  257. const [open, setOpen] = useState(props.defaultOpen ?? false);
  258. return (
  259. <Collapsible open={open} onOpenChange={setOpen} className="w-full">
  260. <CollapsibleTrigger asChild>
  261. <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">
  262. {props.title}
  263. <svg
  264. className={`h-4 w-4 transition-transform ${open ? "rotate-180" : ""}`}
  265. fill="none"
  266. viewBox="0 0 24 24"
  267. stroke="currentColor"
  268. strokeWidth={2}
  269. >
  270. <path
  271. strokeLinecap="round"
  272. strokeLinejoin="round"
  273. d="M19 9l-7 7-7-7"
  274. />
  275. </svg>
  276. </button>
  277. </CollapsibleTrigger>
  278. <CollapsibleContent className="pt-2">{children}</CollapsibleContent>
  279. </Collapsible>
  280. );
  281. },
  282. Dialog: ({ props, children }) => {
  283. const [open, setOpen] = useStateBinding<boolean>(props.openPath);
  284. return (
  285. <DialogPrimitive open={open ?? false} onOpenChange={(v) => setOpen(v)}>
  286. <DialogContent>
  287. <DialogHeader>
  288. <DialogTitle>{props.title}</DialogTitle>
  289. {props.description && (
  290. <DialogDescription>{props.description}</DialogDescription>
  291. )}
  292. </DialogHeader>
  293. {children}
  294. </DialogContent>
  295. </DialogPrimitive>
  296. );
  297. },
  298. Drawer: ({ props, children }) => {
  299. const [open, setOpen] = useStateBinding<boolean>(props.openPath);
  300. return (
  301. <DrawerPrimitive open={open ?? false} onOpenChange={(v) => setOpen(v)}>
  302. <DrawerContent>
  303. <DrawerHeader>
  304. <DrawerTitle>{props.title}</DrawerTitle>
  305. {props.description && (
  306. <DrawerDescription>{props.description}</DrawerDescription>
  307. )}
  308. </DrawerHeader>
  309. <div className="p-4">{children}</div>
  310. </DrawerContent>
  311. </DrawerPrimitive>
  312. );
  313. },
  314. Carousel: ({ props }) => {
  315. const items = props.items ?? [];
  316. return (
  317. <CarouselPrimitive className="w-full">
  318. <CarouselContent>
  319. {items.map((item, i) => (
  320. <CarouselItem
  321. key={i}
  322. className="basis-3/4 md:basis-1/2 lg:basis-1/3"
  323. >
  324. <div className="border border-border rounded-lg p-4 bg-card h-full">
  325. {item.title && (
  326. <h4 className="font-semibold text-sm mb-1">{item.title}</h4>
  327. )}
  328. {item.description && (
  329. <p className="text-sm text-muted-foreground">
  330. {item.description}
  331. </p>
  332. )}
  333. </div>
  334. </CarouselItem>
  335. ))}
  336. </CarouselContent>
  337. <CarouselPrevious />
  338. <CarouselNext />
  339. </CarouselPrimitive>
  340. );
  341. },
  342. // ── Data Display ──────────────────────────────────────────────────
  343. Table: ({ props }) => {
  344. const columns = props.columns ?? [];
  345. const rawRows: unknown[] = Array.isArray(props.rows) ? props.rows : [];
  346. const rows = rawRows.map((row) => {
  347. if (Array.isArray(row)) return row.map(String);
  348. if (row && typeof row === "object") {
  349. const obj = row as Record<string, unknown>;
  350. return columns.map((col) =>
  351. String(obj[col] ?? obj[col.toLowerCase()] ?? ""),
  352. );
  353. }
  354. return columns.map(() => "");
  355. });
  356. return (
  357. <div className="rounded-md border border-border overflow-hidden">
  358. <TablePrimitive>
  359. {props.caption && <TableCaption>{props.caption}</TableCaption>}
  360. <TableHeader>
  361. <TableRow>
  362. {columns.map((col) => (
  363. <TableHead key={col}>{col}</TableHead>
  364. ))}
  365. </TableRow>
  366. </TableHeader>
  367. <TableBody>
  368. {rows.map((row, i) => (
  369. <TableRow key={i}>
  370. {row.map((cell, j) => (
  371. <TableCell key={j}>{cell}</TableCell>
  372. ))}
  373. </TableRow>
  374. ))}
  375. </TableBody>
  376. </TablePrimitive>
  377. </div>
  378. );
  379. },
  380. Heading: ({ props }) => {
  381. const level = props.level ?? "h2";
  382. const headingClass =
  383. level === "h1"
  384. ? "text-2xl font-bold"
  385. : level === "h3"
  386. ? "text-base font-semibold"
  387. : level === "h4"
  388. ? "text-sm font-semibold"
  389. : "text-lg font-semibold";
  390. if (level === "h1")
  391. return <h1 className={`${headingClass} text-left`}>{props.text}</h1>;
  392. if (level === "h3")
  393. return <h3 className={`${headingClass} text-left`}>{props.text}</h3>;
  394. if (level === "h4")
  395. return <h4 className={`${headingClass} text-left`}>{props.text}</h4>;
  396. return <h2 className={`${headingClass} text-left`}>{props.text}</h2>;
  397. },
  398. Text: ({ props }) => {
  399. const textClass =
  400. props.variant === "caption"
  401. ? "text-xs"
  402. : props.variant === "muted"
  403. ? "text-sm text-muted-foreground"
  404. : props.variant === "lead"
  405. ? "text-xl text-muted-foreground"
  406. : props.variant === "code"
  407. ? "font-mono text-sm bg-muted px-1.5 py-0.5 rounded"
  408. : "text-sm";
  409. if (props.variant === "code") {
  410. return <code className={`${textClass} text-left`}>{props.text}</code>;
  411. }
  412. return <p className={`${textClass} text-left`}>{props.text}</p>;
  413. },
  414. Image: ({ props }) => (
  415. <div
  416. className="bg-muted border border-border rounded flex items-center justify-center text-xs text-muted-foreground aspect-video"
  417. style={{ width: props.width ?? 80, height: props.height ?? 60 }}
  418. >
  419. {props.alt || "img"}
  420. </div>
  421. ),
  422. Avatar: ({ props }) => {
  423. const name = props.name || "?";
  424. const initials = name
  425. .split(" ")
  426. .map((n) => n[0])
  427. .join("")
  428. .slice(0, 2)
  429. .toUpperCase();
  430. const avatarSize =
  431. props.size === "lg"
  432. ? "w-12 h-12 text-base"
  433. : props.size === "sm"
  434. ? "w-8 h-8 text-xs"
  435. : "w-10 h-10 text-sm";
  436. return (
  437. <div
  438. className={`${avatarSize} rounded-full bg-muted flex items-center justify-center font-medium`}
  439. >
  440. {initials}
  441. </div>
  442. );
  443. },
  444. Badge: ({ props }) => {
  445. const variant =
  446. props.variant === "success" || props.variant === "warning"
  447. ? "secondary"
  448. : props.variant === "danger"
  449. ? "destructive"
  450. : "default";
  451. const customClass =
  452. props.variant === "success"
  453. ? "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-100"
  454. : props.variant === "warning"
  455. ? "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-100"
  456. : "";
  457. return (
  458. <Badge variant={variant} className={customClass}>
  459. {props.text}
  460. </Badge>
  461. );
  462. },
  463. Alert: ({ props }) => {
  464. const variant = props.type === "error" ? "destructive" : "default";
  465. const customClass =
  466. props.type === "success"
  467. ? "border-green-200 bg-green-50 text-green-900 dark:border-green-800 dark:bg-green-950 dark:text-green-100"
  468. : props.type === "warning"
  469. ? "border-yellow-200 bg-yellow-50 text-yellow-900 dark:border-yellow-800 dark:bg-yellow-950 dark:text-yellow-100"
  470. : props.type === "info"
  471. ? "border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"
  472. : "";
  473. return (
  474. <Alert variant={variant} className={customClass}>
  475. <AlertTitle>{props.title}</AlertTitle>
  476. {props.message && (
  477. <AlertDescription>{props.message}</AlertDescription>
  478. )}
  479. </Alert>
  480. );
  481. },
  482. Progress: ({ props }) => {
  483. const value = Math.min(100, Math.max(0, props.value || 0));
  484. return (
  485. <div className="space-y-2">
  486. {props.label && (
  487. <Label className="text-sm text-muted-foreground">
  488. {props.label}
  489. </Label>
  490. )}
  491. <Progress value={value} />
  492. </div>
  493. );
  494. },
  495. Skeleton: ({ props }) => (
  496. <Skeleton
  497. className={props.rounded ? "rounded-full" : "rounded-md"}
  498. style={{
  499. width: props.width ?? "100%",
  500. height: props.height ?? "1.25rem",
  501. }}
  502. />
  503. ),
  504. Spinner: ({ props }) => {
  505. const sizeClass =
  506. props.size === "lg"
  507. ? "h-8 w-8"
  508. : props.size === "sm"
  509. ? "h-4 w-4"
  510. : "h-6 w-6";
  511. return (
  512. <div className="flex items-center gap-2">
  513. <svg
  514. className={`${sizeClass} animate-spin text-muted-foreground`}
  515. viewBox="0 0 24 24"
  516. fill="none"
  517. >
  518. <circle
  519. className="opacity-25"
  520. cx="12"
  521. cy="12"
  522. r="10"
  523. stroke="currentColor"
  524. strokeWidth="4"
  525. />
  526. <path
  527. className="opacity-75"
  528. fill="currentColor"
  529. d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
  530. />
  531. </svg>
  532. {props.label && (
  533. <span className="text-sm text-muted-foreground">{props.label}</span>
  534. )}
  535. </div>
  536. );
  537. },
  538. Tooltip: ({ props }) => (
  539. <TooltipProvider>
  540. <TooltipPrimitive>
  541. <TooltipTrigger asChild>
  542. <span className="text-sm underline decoration-dotted cursor-help">
  543. {props.text}
  544. </span>
  545. </TooltipTrigger>
  546. <TooltipContent>
  547. <p>{props.content}</p>
  548. </TooltipContent>
  549. </TooltipPrimitive>
  550. </TooltipProvider>
  551. ),
  552. Popover: ({ props }) => (
  553. <PopoverPrimitive>
  554. <PopoverTrigger asChild>
  555. <Button variant="outline" className="text-sm">
  556. {props.trigger}
  557. </Button>
  558. </PopoverTrigger>
  559. <PopoverContent className="w-64">
  560. <p className="text-sm">{props.content}</p>
  561. </PopoverContent>
  562. </PopoverPrimitive>
  563. ),
  564. Rating: ({ props }) => {
  565. const ratingValue = props.value || 0;
  566. const maxRating = props.max ?? 5;
  567. return (
  568. <div className="space-y-2">
  569. {props.label && (
  570. <Label className="text-sm text-muted-foreground">
  571. {props.label}
  572. </Label>
  573. )}
  574. <div className="flex gap-1">
  575. {Array.from({ length: maxRating }).map((_, i) => (
  576. <span
  577. key={i}
  578. className={`text-lg ${i < ratingValue ? "text-yellow-400" : "text-muted"}`}
  579. >
  580. *
  581. </span>
  582. ))}
  583. </div>
  584. </div>
  585. );
  586. },
  587. // ── Charts ────────────────────────────────────────────────────────
  588. BarGraph: ({ props }) => {
  589. const data = props.data || [];
  590. const maxValue = Math.max(...data.map((d) => d.value), 1);
  591. return (
  592. <div className="space-y-2">
  593. {props.title && (
  594. <div className="text-sm font-medium text-left">{props.title}</div>
  595. )}
  596. <div className="flex gap-2">
  597. {data.map((d, i) => (
  598. <div key={i} className="flex-1 flex flex-col items-center gap-1">
  599. <div className="text-xs text-muted-foreground">{d.value}</div>
  600. <div className="w-full h-24 flex items-end">
  601. <div
  602. className="w-full bg-primary rounded-t transition-all"
  603. style={{
  604. height: `${(d.value / maxValue) * 100}%`,
  605. minHeight: 2,
  606. }}
  607. />
  608. </div>
  609. <div className="text-xs text-muted-foreground truncate w-full text-center">
  610. {d.label}
  611. </div>
  612. </div>
  613. ))}
  614. </div>
  615. </div>
  616. );
  617. },
  618. LineGraph: ({ props }) => {
  619. const data = props.data || [];
  620. const maxValue = Math.max(...data.map((d) => d.value));
  621. const minValue = Math.min(...data.map((d) => d.value));
  622. const range = maxValue - minValue || 1;
  623. const width = 300;
  624. const height = 100;
  625. const padding = { top: 10, right: 10, bottom: 10, left: 10 };
  626. const chartWidth = width - padding.left - padding.right;
  627. const chartHeight = height - padding.top - padding.bottom;
  628. const points = data.map((d, i) => {
  629. const x =
  630. padding.left +
  631. (data.length > 1
  632. ? (i / (data.length - 1)) * chartWidth
  633. : chartWidth / 2);
  634. const y =
  635. padding.top +
  636. chartHeight -
  637. ((d.value - minValue) / range) * chartHeight;
  638. return { x, y, ...d };
  639. });
  640. const pathD =
  641. points.length > 0
  642. ? `M ${points.map((p) => `${p.x} ${p.y}`).join(" L ")}`
  643. : "";
  644. return (
  645. <div className="space-y-2">
  646. {props.title && (
  647. <div className="text-sm font-medium text-left">{props.title}</div>
  648. )}
  649. <div className="relative h-28">
  650. <svg viewBox={`0 0 ${width} ${height}`} className="w-full h-full">
  651. <line
  652. x1={padding.left}
  653. y1={padding.top + chartHeight / 2}
  654. x2={width - padding.right}
  655. y2={padding.top + chartHeight / 2}
  656. stroke="currentColor"
  657. strokeOpacity="0.1"
  658. strokeWidth="1"
  659. />
  660. <line
  661. x1={padding.left}
  662. y1={padding.top}
  663. x2={width - padding.right}
  664. y2={padding.top}
  665. stroke="currentColor"
  666. strokeOpacity="0.1"
  667. strokeWidth="1"
  668. />
  669. <line
  670. x1={padding.left}
  671. y1={height - padding.bottom}
  672. x2={width - padding.right}
  673. y2={height - padding.bottom}
  674. stroke="currentColor"
  675. strokeOpacity="0.1"
  676. strokeWidth="1"
  677. />
  678. {pathD && (
  679. <path
  680. d={pathD}
  681. fill="none"
  682. stroke="currentColor"
  683. strokeWidth="2"
  684. strokeLinecap="round"
  685. strokeLinejoin="round"
  686. className="text-primary"
  687. />
  688. )}
  689. {points.map((p, i) => (
  690. <circle
  691. key={i}
  692. cx={p.x}
  693. cy={p.y}
  694. r="4"
  695. className="fill-primary"
  696. />
  697. ))}
  698. </svg>
  699. </div>
  700. {data.length > 0 && (
  701. <div className="flex justify-between">
  702. {data.map((d, i) => (
  703. <div
  704. key={i}
  705. className="text-xs text-muted-foreground text-center"
  706. style={{ width: `${100 / data.length}%` }}
  707. >
  708. {d.label}
  709. </div>
  710. ))}
  711. </div>
  712. )}
  713. </div>
  714. );
  715. },
  716. // ── Form Inputs ───────────────────────────────────────────────────
  717. Input: ({ props, emit }) => {
  718. const [boundValue, setBoundValue] = props.statePath
  719. ? useStateBinding<string>(props.statePath) // eslint-disable-line react-hooks/rules-of-hooks
  720. : [undefined, undefined];
  721. const [localValue, setLocalValue] = useState("");
  722. const value = props.statePath ? (boundValue ?? "") : localValue;
  723. const setValue = props.statePath ? setBoundValue! : setLocalValue;
  724. return (
  725. <div className="space-y-2">
  726. {props.label && <Label htmlFor={props.name}>{props.label}</Label>}
  727. <Input
  728. id={props.name}
  729. name={props.name}
  730. type={props.type ?? "text"}
  731. placeholder={props.placeholder ?? ""}
  732. value={value}
  733. onChange={(e) => setValue(e.target.value)}
  734. onKeyDown={(e) => {
  735. if (e.key === "Enter") emit?.("submit");
  736. }}
  737. onFocus={() => emit?.("focus")}
  738. onBlur={() => emit?.("blur")}
  739. />
  740. </div>
  741. );
  742. },
  743. Textarea: ({ props }) => {
  744. const [boundValue, setBoundValue] = props.statePath
  745. ? useStateBinding<string>(props.statePath) // eslint-disable-line react-hooks/rules-of-hooks
  746. : [undefined, undefined];
  747. const [localValue, setLocalValue] = useState("");
  748. const value = props.statePath ? (boundValue ?? "") : localValue;
  749. const setValue = props.statePath ? setBoundValue! : setLocalValue;
  750. return (
  751. <div className="space-y-2">
  752. {props.label && <Label htmlFor={props.name}>{props.label}</Label>}
  753. <Textarea
  754. id={props.name}
  755. name={props.name}
  756. placeholder={props.placeholder ?? ""}
  757. rows={props.rows ?? 3}
  758. value={value}
  759. onChange={(e) => setValue(e.target.value)}
  760. />
  761. </div>
  762. );
  763. },
  764. Select: ({ props, emit }) => {
  765. const [boundValue, setBoundValue] = props.statePath
  766. ? useStateBinding<string>(props.statePath) // eslint-disable-line react-hooks/rules-of-hooks
  767. : [undefined, undefined];
  768. const [localValue, setLocalValue] = useState<string>("");
  769. const value = props.statePath ? (boundValue ?? "") : localValue;
  770. const setValue = props.statePath ? setBoundValue! : setLocalValue;
  771. const rawOptions = props.options ?? [];
  772. // Coerce options to strings – AI may produce objects/numbers instead of
  773. // plain strings which would cause duplicate `[object Object]` keys.
  774. const options = rawOptions.map((opt) =>
  775. typeof opt === "string" ? opt : String(opt ?? ""),
  776. );
  777. return (
  778. <div className="space-y-2">
  779. <Label>{props.label}</Label>
  780. <Select
  781. value={value}
  782. onValueChange={(v) => {
  783. setValue(v);
  784. emit?.("change");
  785. }}
  786. >
  787. <SelectTrigger className="w-full">
  788. <SelectValue placeholder={props.placeholder ?? "Select..."} />
  789. </SelectTrigger>
  790. <SelectContent>
  791. {options.map((opt, idx) => (
  792. <SelectItem
  793. key={`${idx}-${opt}`}
  794. value={opt || `option-${idx}`}
  795. >
  796. {opt}
  797. </SelectItem>
  798. ))}
  799. </SelectContent>
  800. </Select>
  801. </div>
  802. );
  803. },
  804. Checkbox: ({ props, emit }) => {
  805. const [boundValue, setBoundValue] = props.statePath
  806. ? useStateBinding<boolean>(props.statePath) // eslint-disable-line react-hooks/rules-of-hooks
  807. : [undefined, undefined];
  808. const [localChecked, setLocalChecked] = useState(!!props.checked);
  809. const checked = props.statePath ? (boundValue ?? false) : localChecked;
  810. const setChecked = props.statePath ? setBoundValue! : setLocalChecked;
  811. return (
  812. <div className="flex items-center space-x-2">
  813. <Checkbox
  814. id={props.name}
  815. checked={checked}
  816. onCheckedChange={(c) => {
  817. setChecked(c === true);
  818. emit?.("change");
  819. }}
  820. />
  821. <Label htmlFor={props.name} className="cursor-pointer">
  822. {props.label}
  823. </Label>
  824. </div>
  825. );
  826. },
  827. Radio: ({ props, emit }) => {
  828. const rawOptions = props.options ?? [];
  829. const options = rawOptions.map((opt) =>
  830. typeof opt === "string" ? opt : String(opt ?? ""),
  831. );
  832. const [boundValue, setBoundValue] = props.statePath
  833. ? useStateBinding<string>(props.statePath) // eslint-disable-line react-hooks/rules-of-hooks
  834. : [undefined, undefined];
  835. const [localValue, setLocalValue] = useState(options[0] ?? "");
  836. const value = props.statePath ? (boundValue ?? "") : localValue;
  837. const setValue = props.statePath ? setBoundValue! : setLocalValue;
  838. return (
  839. <div className="space-y-2">
  840. {props.label && <Label>{props.label}</Label>}
  841. <RadioGroup
  842. value={value}
  843. onValueChange={(v) => {
  844. setValue(v);
  845. emit?.("change");
  846. }}
  847. >
  848. {options.map((opt, idx) => (
  849. <div
  850. key={`${idx}-${opt}`}
  851. className="flex items-center space-x-2"
  852. >
  853. <RadioGroupItem
  854. value={opt || `option-${idx}`}
  855. id={`${props.name}-${idx}-${opt}`}
  856. />
  857. <Label
  858. htmlFor={`${props.name}-${idx}-${opt}`}
  859. className="cursor-pointer"
  860. >
  861. {opt}
  862. </Label>
  863. </div>
  864. ))}
  865. </RadioGroup>
  866. </div>
  867. );
  868. },
  869. Switch: ({ props, emit }) => {
  870. const [boundValue, setBoundValue] = props.statePath
  871. ? useStateBinding<boolean>(props.statePath) // eslint-disable-line react-hooks/rules-of-hooks
  872. : [undefined, undefined];
  873. const [localChecked, setLocalChecked] = useState(!!props.checked);
  874. const checked = props.statePath ? (boundValue ?? false) : localChecked;
  875. const setChecked = props.statePath ? setBoundValue! : setLocalChecked;
  876. return (
  877. <div className="flex items-center justify-between space-x-2">
  878. <Label htmlFor={props.name} className="cursor-pointer">
  879. {props.label}
  880. </Label>
  881. <Switch
  882. id={props.name}
  883. checked={checked}
  884. onCheckedChange={(c) => {
  885. setChecked(c);
  886. emit?.("change");
  887. }}
  888. />
  889. </div>
  890. );
  891. },
  892. Slider: ({ props, emit }) => {
  893. const [boundValue, setBoundValue] = props.statePath
  894. ? useStateBinding<number>(props.statePath) // eslint-disable-line react-hooks/rules-of-hooks
  895. : [undefined, undefined];
  896. const [localValue, setLocalValue] = useState(props.min ?? 0);
  897. const value = props.statePath
  898. ? (boundValue ?? props.min ?? 0)
  899. : localValue;
  900. const setValue = props.statePath ? setBoundValue! : setLocalValue;
  901. return (
  902. <div className="space-y-2">
  903. {props.label && (
  904. <div className="flex justify-between">
  905. <Label className="text-sm">{props.label}</Label>
  906. <span className="text-sm text-muted-foreground">{value}</span>
  907. </div>
  908. )}
  909. <Slider
  910. value={[value]}
  911. min={props.min ?? 0}
  912. max={props.max ?? 100}
  913. step={props.step ?? 1}
  914. onValueChange={(v) => {
  915. setValue(v[0] ?? 0);
  916. emit?.("change");
  917. }}
  918. />
  919. </div>
  920. );
  921. },
  922. // ── Actions ───────────────────────────────────────────────────────
  923. Button: ({ props, emit }) => {
  924. const variant =
  925. props.variant === "danger"
  926. ? "destructive"
  927. : props.variant === "secondary"
  928. ? "secondary"
  929. : "default";
  930. return (
  931. <Button
  932. variant={variant}
  933. disabled={props.disabled ?? false}
  934. onClick={() => emit?.("press")}
  935. >
  936. {props.label}
  937. </Button>
  938. );
  939. },
  940. Link: ({ props, emit }) => (
  941. <Button
  942. variant="link"
  943. className="h-auto p-0"
  944. onClick={() => emit?.("press")}
  945. >
  946. {props.label}
  947. </Button>
  948. ),
  949. DropdownMenu: ({ props, emit }) => {
  950. const items = props.items ?? [];
  951. return (
  952. <DropdownMenuPrimitive>
  953. <DropdownMenuTrigger asChild>
  954. <Button variant="outline">{props.label}</Button>
  955. </DropdownMenuTrigger>
  956. <DropdownMenuContent>
  957. {items.map((item) => (
  958. <DropdownMenuItem
  959. key={item.value}
  960. onClick={() => emit?.("select")}
  961. >
  962. {item.label}
  963. </DropdownMenuItem>
  964. ))}
  965. </DropdownMenuContent>
  966. </DropdownMenuPrimitive>
  967. );
  968. },
  969. Toggle: ({ props, emit }) => {
  970. const [boundValue, setBoundValue] = props.statePath
  971. ? useStateBinding<boolean>(props.statePath) // eslint-disable-line react-hooks/rules-of-hooks
  972. : [undefined, undefined];
  973. const [localPressed, setLocalPressed] = useState(props.pressed ?? false);
  974. const pressed = props.statePath ? (boundValue ?? false) : localPressed;
  975. const setPressed = props.statePath ? setBoundValue! : setLocalPressed;
  976. return (
  977. <Toggle
  978. variant={props.variant ?? "default"}
  979. pressed={pressed}
  980. onPressedChange={(v) => {
  981. setPressed(v);
  982. emit?.("change");
  983. }}
  984. >
  985. {props.label}
  986. </Toggle>
  987. );
  988. },
  989. ToggleGroup: ({ props, emit }) => {
  990. const type = props.type ?? "single";
  991. const items = props.items ?? [];
  992. const [boundValue, setBoundValue] = props.statePath
  993. ? useStateBinding<string>(props.statePath) // eslint-disable-line react-hooks/rules-of-hooks
  994. : [undefined, undefined];
  995. const [localValue, setLocalValue] = useState(items[0]?.value ?? "");
  996. const value = props.statePath ? (boundValue ?? "") : localValue;
  997. const setValue = props.statePath ? setBoundValue! : setLocalValue;
  998. if (type === "multiple") {
  999. return (
  1000. <ToggleGroup type="multiple">
  1001. {items.map((item) => (
  1002. <ToggleGroupItem key={item.value} value={item.value}>
  1003. {item.label}
  1004. </ToggleGroupItem>
  1005. ))}
  1006. </ToggleGroup>
  1007. );
  1008. }
  1009. return (
  1010. <ToggleGroup
  1011. type="single"
  1012. value={value}
  1013. onValueChange={(v) => {
  1014. if (v) {
  1015. setValue(v);
  1016. emit?.("change");
  1017. }
  1018. }}
  1019. >
  1020. {items.map((item) => (
  1021. <ToggleGroupItem key={item.value} value={item.value}>
  1022. {item.label}
  1023. </ToggleGroupItem>
  1024. ))}
  1025. </ToggleGroup>
  1026. );
  1027. },
  1028. ButtonGroup: ({ props, emit }) => {
  1029. const buttons = props.buttons ?? [];
  1030. const [boundValue, setBoundValue] = props.statePath
  1031. ? useStateBinding<string>(props.statePath) // eslint-disable-line react-hooks/rules-of-hooks
  1032. : [undefined, undefined];
  1033. const [localValue, setLocalValue] = useState(buttons[0]?.value ?? "");
  1034. const value = props.statePath ? (boundValue ?? "") : localValue;
  1035. const setValue = props.statePath ? setBoundValue! : setLocalValue;
  1036. return (
  1037. <div className="inline-flex rounded-md border border-border">
  1038. {buttons.map((btn, i) => (
  1039. <button
  1040. key={btn.value}
  1041. className={`px-3 py-1.5 text-sm transition-colors ${
  1042. value === btn.value
  1043. ? "bg-primary text-primary-foreground"
  1044. : "bg-background hover:bg-muted"
  1045. } ${i > 0 ? "border-l border-border" : ""} ${
  1046. i === 0 ? "rounded-l-md" : ""
  1047. } ${i === buttons.length - 1 ? "rounded-r-md" : ""}`}
  1048. onClick={() => {
  1049. setValue(btn.value);
  1050. emit?.("change");
  1051. }}
  1052. >
  1053. {btn.label}
  1054. </button>
  1055. ))}
  1056. </div>
  1057. );
  1058. },
  1059. Pagination: ({ props, emit }) => {
  1060. const [boundValue, setBoundValue] = useStateBinding<number>(
  1061. props.statePath,
  1062. );
  1063. const currentPage = boundValue ?? 1;
  1064. const pages = Array.from({ length: props.totalPages }, (_, i) => i + 1);
  1065. return (
  1066. <PaginationPrimitive>
  1067. <PaginationContent>
  1068. <PaginationItem>
  1069. <PaginationPrevious
  1070. href="#"
  1071. onClick={(e) => {
  1072. e.preventDefault();
  1073. if (currentPage > 1) {
  1074. setBoundValue(currentPage - 1);
  1075. emit?.("change");
  1076. }
  1077. }}
  1078. />
  1079. </PaginationItem>
  1080. {pages.map((page) => (
  1081. <PaginationItem key={page}>
  1082. <PaginationLink
  1083. href="#"
  1084. isActive={page === currentPage}
  1085. onClick={(e) => {
  1086. e.preventDefault();
  1087. setBoundValue(page);
  1088. emit?.("change");
  1089. }}
  1090. >
  1091. {page}
  1092. </PaginationLink>
  1093. </PaginationItem>
  1094. ))}
  1095. <PaginationItem>
  1096. <PaginationNext
  1097. href="#"
  1098. onClick={(e) => {
  1099. e.preventDefault();
  1100. if (currentPage < props.totalPages) {
  1101. setBoundValue(currentPage + 1);
  1102. emit?.("change");
  1103. }
  1104. }}
  1105. />
  1106. </PaginationItem>
  1107. </PaginationContent>
  1108. </PaginationPrimitive>
  1109. );
  1110. },
  1111. },
  1112. actions: {
  1113. // Built-in state actions — handled by ActionProvider, stubs needed for types
  1114. setState: async () => {},
  1115. pushState: async () => {},
  1116. removeState: async () => {},
  1117. // Demo actions — show toasts
  1118. buttonClick: async (params) => {
  1119. const message = (params?.message as string) || "Button clicked!";
  1120. toast.success(message);
  1121. },
  1122. formSubmit: async (params) => {
  1123. const formName = (params?.formName as string) || "Form";
  1124. toast.success(`${formName} submitted successfully!`);
  1125. },
  1126. linkClick: async (params) => {
  1127. const href = (params?.href as string) || "#";
  1128. toast.info(`Navigating to: ${href}`);
  1129. },
  1130. },
  1131. });
  1132. // Fallback component for unknown types
  1133. export function Fallback({ type }: { type: string }) {
  1134. return <div className="text-xs text-muted-foreground">[{type}]</div>;
  1135. }