registry.tsx 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815
  1. "use client";
  2. import { Children, useEffect, useState } from "react";
  3. import {
  4. defineRegistry,
  5. useBoundProp,
  6. useStateBinding,
  7. useFieldValidation,
  8. } from "@json-render/react";
  9. import { toast } from "sonner";
  10. import { playgroundCatalog } from "./catalog";
  11. // shadcn components
  12. import { Button } from "@/components/ui/button";
  13. import { Input } from "@/components/ui/input";
  14. import { Label } from "@/components/ui/label";
  15. import { Textarea } from "@/components/ui/textarea";
  16. import { Checkbox } from "@/components/ui/checkbox";
  17. import { Switch } from "@/components/ui/switch";
  18. import { Progress } from "@/components/ui/progress";
  19. import { Separator } from "@/components/ui/separator";
  20. import { Alert, AlertTitle, AlertDescription } from "@/components/ui/alert";
  21. import {
  22. Dialog as DialogPrimitive,
  23. DialogContent,
  24. DialogDescription,
  25. DialogHeader,
  26. DialogTitle,
  27. } from "@/components/ui/dialog";
  28. import {
  29. Accordion as AccordionPrimitive,
  30. AccordionContent,
  31. AccordionItem,
  32. AccordionTrigger,
  33. } from "@/components/ui/accordion";
  34. import { Badge } from "@/components/ui/badge";
  35. import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
  36. import {
  37. Select,
  38. SelectContent,
  39. SelectItem,
  40. SelectTrigger,
  41. SelectValue,
  42. } from "@/components/ui/select";
  43. import {
  44. Carousel as CarouselPrimitive,
  45. CarouselContent,
  46. CarouselItem,
  47. CarouselNext,
  48. CarouselPrevious,
  49. } from "@/components/ui/carousel";
  50. import {
  51. Collapsible,
  52. CollapsibleContent,
  53. CollapsibleTrigger,
  54. } from "@/components/ui/collapsible";
  55. import {
  56. Table as TablePrimitive,
  57. TableBody,
  58. TableCaption,
  59. TableCell,
  60. TableHead,
  61. TableHeader,
  62. TableRow,
  63. } from "@/components/ui/table";
  64. import {
  65. Drawer as DrawerPrimitive,
  66. DrawerContent,
  67. DrawerDescription,
  68. DrawerHeader,
  69. DrawerTitle,
  70. } from "@/components/ui/drawer";
  71. import {
  72. DropdownMenu as DropdownMenuPrimitive,
  73. DropdownMenuContent,
  74. DropdownMenuItem,
  75. DropdownMenuTrigger,
  76. } from "@/components/ui/dropdown-menu";
  77. import {
  78. Pagination as PaginationPrimitive,
  79. PaginationContent,
  80. PaginationItem,
  81. PaginationLink,
  82. PaginationNext,
  83. PaginationPrevious,
  84. } from "@/components/ui/pagination";
  85. import {
  86. Popover as PopoverPrimitive,
  87. PopoverContent,
  88. PopoverTrigger,
  89. } from "@/components/ui/popover";
  90. import { Skeleton } from "@/components/ui/skeleton";
  91. import { Slider } from "@/components/ui/slider";
  92. import {
  93. Tabs as TabsPrimitive,
  94. TabsList,
  95. TabsTrigger,
  96. TabsContent,
  97. } from "@/components/ui/tabs";
  98. import { Toggle } from "@/components/ui/toggle";
  99. import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
  100. import {
  101. Tooltip as TooltipPrimitive,
  102. TooltipContent,
  103. TooltipProvider,
  104. TooltipTrigger,
  105. } from "@/components/ui/tooltip";
  106. import { icons as lucideIcons } from "lucide-react";
  107. // =============================================================================
  108. // Registry — components + actions, types inferred from catalog
  109. // =============================================================================
  110. export const { registry, executeAction } = defineRegistry(playgroundCatalog, {
  111. components: {
  112. // ── Layout ────────────────────────────────────────────────────────
  113. Card: ({ props, children }) => {
  114. const maxWidthClass =
  115. props.maxWidth === "sm"
  116. ? "max-w-xs sm:min-w-[280px]"
  117. : props.maxWidth === "md"
  118. ? "max-w-sm sm:min-w-[320px]"
  119. : props.maxWidth === "lg"
  120. ? "max-w-md sm:min-w-[360px]"
  121. : "w-full";
  122. const centeredClass = props.centered ? "mx-auto" : "";
  123. return (
  124. <div
  125. className={`border border-border rounded-xl p-5 bg-card text-card-foreground shadow-sm overflow-hidden h-full flex flex-col ${maxWidthClass} ${centeredClass}`}
  126. >
  127. {(props.title || props.description) && (
  128. <div className="mb-4">
  129. {props.title && (
  130. <h3 className="font-semibold text-lg tracking-tight">
  131. {props.title}
  132. </h3>
  133. )}
  134. {props.description && (
  135. <p className="text-sm text-muted-foreground mt-1">
  136. {props.description}
  137. </p>
  138. )}
  139. </div>
  140. )}
  141. <div className="flex-1 flex flex-col gap-4 [&>:last-child]:mt-auto">
  142. {children}
  143. </div>
  144. </div>
  145. );
  146. },
  147. Stack: ({ props, children }) => {
  148. const isHorizontal = props.direction === "horizontal";
  149. const gapClass =
  150. props.gap === "lg"
  151. ? "gap-4"
  152. : props.gap === "md"
  153. ? "gap-3"
  154. : props.gap === "sm"
  155. ? "gap-2"
  156. : props.gap === "none"
  157. ? "gap-0"
  158. : "gap-3";
  159. let alignClass: string;
  160. if (isHorizontal) {
  161. alignClass =
  162. props.align === "center"
  163. ? "items-center"
  164. : props.align === "end"
  165. ? "items-end"
  166. : props.align === "stretch"
  167. ? "items-stretch"
  168. : "items-start";
  169. } else {
  170. // Vertical: items-center/end lets inline elements (Avatar, Badge, Button)
  171. // center/align naturally. Block containers (Grid, Accordion, Table) add
  172. // their own w-full to stretch regardless.
  173. alignClass =
  174. props.align === "center"
  175. ? "items-center"
  176. : props.align === "end"
  177. ? "items-end"
  178. : props.align === "start"
  179. ? "items-start"
  180. : "items-stretch";
  181. }
  182. const justifyClass =
  183. props.justify === "center"
  184. ? "justify-center"
  185. : props.justify === "end"
  186. ? "justify-end"
  187. : props.justify === "between"
  188. ? "justify-between"
  189. : props.justify === "around"
  190. ? "justify-around"
  191. : "";
  192. // Horizontal stacks wrap by default; wrap:false keeps a single scrolling
  193. // row (Kanban boards / column layouts that must sit side by side).
  194. const horizontalFlow =
  195. props.wrap === false
  196. ? "flex-row flex-nowrap overflow-x-auto w-full [&>*]:shrink-0"
  197. : "flex-row flex-wrap";
  198. return (
  199. <div
  200. className={`flex ${isHorizontal ? horizontalFlow : "flex-col w-full"} ${gapClass} ${alignClass} ${justifyClass}`}
  201. >
  202. {children}
  203. </div>
  204. );
  205. },
  206. Grid: ({ props, children }) => {
  207. const childCount = Array.isArray(children)
  208. ? children.length
  209. : children
  210. ? 1
  211. : 0;
  212. const n = Math.min(props.columns ?? 1, childCount || 1);
  213. const cols =
  214. n >= 7
  215. ? "grid-cols-7"
  216. : n >= 6
  217. ? "grid-cols-6"
  218. : n >= 5
  219. ? "grid-cols-5"
  220. : n >= 4
  221. ? "grid-cols-4"
  222. : n >= 3
  223. ? "grid-cols-3"
  224. : n >= 2
  225. ? "grid-cols-2"
  226. : "grid-cols-1";
  227. const gridGap =
  228. props.gap === "lg" ? "gap-4" : props.gap === "sm" ? "gap-2" : "gap-3";
  229. return <div className={`grid w-full ${cols} ${gridGap}`}>{children}</div>;
  230. },
  231. Separator: ({ props }) => (
  232. <Separator
  233. orientation={props.orientation ?? "horizontal"}
  234. className={
  235. props.orientation === "vertical" ? "h-full mx-3" : "my-4 opacity-50"
  236. }
  237. />
  238. ),
  239. Tabs: ({ props, bindings, emit, children }) => {
  240. const tabs = props.tabs ?? [];
  241. const [boundValue, setBoundValue] = useBoundProp<string>(
  242. props.value as string | undefined,
  243. bindings?.value,
  244. );
  245. const [localValue, setLocalValue] = useState(
  246. props.defaultValue ?? tabs[0]?.value ?? "",
  247. );
  248. const isBound = !!bindings?.value;
  249. const value = isBound ? (boundValue ?? tabs[0]?.value ?? "") : localValue;
  250. const setValue = isBound ? setBoundValue : setLocalValue;
  251. // Children map positionally to tabs: children[i] is the panel for tabs[i].
  252. const panels = Children.toArray(children);
  253. return (
  254. <TabsPrimitive
  255. value={value}
  256. onValueChange={(v) => {
  257. setValue(v);
  258. emit("change");
  259. }}
  260. >
  261. <TabsList>
  262. {tabs.map((tab) => (
  263. <TabsTrigger key={tab.value} value={tab.value}>
  264. {tab.label}
  265. </TabsTrigger>
  266. ))}
  267. </TabsList>
  268. {tabs.map((tab, i) => (
  269. <TabsContent key={tab.value} value={tab.value} className="pt-4">
  270. {panels[i] ?? null}
  271. </TabsContent>
  272. ))}
  273. </TabsPrimitive>
  274. );
  275. },
  276. Accordion: ({ props }) => {
  277. const items = props.items ?? [];
  278. const accordionType = props.type ?? "single";
  279. if (accordionType === "multiple") {
  280. return (
  281. <AccordionPrimitive type="multiple" className="w-full">
  282. {items.map((item, i) => (
  283. <AccordionItem key={i} value={`item-${i}`}>
  284. <AccordionTrigger>{item.title}</AccordionTrigger>
  285. <AccordionContent>{item.content}</AccordionContent>
  286. </AccordionItem>
  287. ))}
  288. </AccordionPrimitive>
  289. );
  290. }
  291. return (
  292. <AccordionPrimitive type="single" collapsible className="w-full">
  293. {items.map((item, i) => (
  294. <AccordionItem key={i} value={`item-${i}`}>
  295. <AccordionTrigger>{item.title}</AccordionTrigger>
  296. <AccordionContent>{item.content}</AccordionContent>
  297. </AccordionItem>
  298. ))}
  299. </AccordionPrimitive>
  300. );
  301. },
  302. Collapsible: ({ props, children }) => {
  303. const [open, setOpen] = useState(props.defaultOpen ?? false);
  304. return (
  305. <Collapsible open={open} onOpenChange={setOpen} className="w-full">
  306. <CollapsibleTrigger asChild>
  307. <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">
  308. {props.title}
  309. <svg
  310. className={`h-4 w-4 transition-transform ${open ? "rotate-180" : ""}`}
  311. fill="none"
  312. viewBox="0 0 24 24"
  313. stroke="currentColor"
  314. strokeWidth={2}
  315. >
  316. <path
  317. strokeLinecap="round"
  318. strokeLinejoin="round"
  319. d="M19 9l-7 7-7-7"
  320. />
  321. </svg>
  322. </button>
  323. </CollapsibleTrigger>
  324. <CollapsibleContent className="pt-2">{children}</CollapsibleContent>
  325. </Collapsible>
  326. );
  327. },
  328. Dialog: ({ props, children }) => {
  329. const [open, setOpen] = useStateBinding<boolean>(props.openPath);
  330. return (
  331. <DialogPrimitive open={open ?? false} onOpenChange={(v) => setOpen(v)}>
  332. <DialogContent>
  333. <DialogHeader>
  334. <DialogTitle>{props.title}</DialogTitle>
  335. {props.description && (
  336. <DialogDescription>{props.description}</DialogDescription>
  337. )}
  338. </DialogHeader>
  339. {children}
  340. </DialogContent>
  341. </DialogPrimitive>
  342. );
  343. },
  344. Drawer: ({ props, children }) => {
  345. const [open, setOpen] = useStateBinding<boolean>(props.openPath);
  346. return (
  347. <DrawerPrimitive open={open ?? false} onOpenChange={(v) => setOpen(v)}>
  348. <DrawerContent>
  349. <DrawerHeader>
  350. <DrawerTitle>{props.title}</DrawerTitle>
  351. {props.description && (
  352. <DrawerDescription>{props.description}</DrawerDescription>
  353. )}
  354. </DrawerHeader>
  355. <div className="p-4">{children}</div>
  356. </DrawerContent>
  357. </DrawerPrimitive>
  358. );
  359. },
  360. Carousel: ({ props }) => {
  361. const items = props.items ?? [];
  362. return (
  363. <CarouselPrimitive className="w-full">
  364. <CarouselContent>
  365. {items.map((item, i) => (
  366. <CarouselItem
  367. key={i}
  368. className="basis-3/4 md:basis-1/2 lg:basis-1/3"
  369. >
  370. <div className="border border-border rounded-lg p-4 bg-card h-full">
  371. {item.title && (
  372. <h4 className="font-semibold text-sm mb-1">{item.title}</h4>
  373. )}
  374. {item.description && (
  375. <p className="text-sm text-muted-foreground">
  376. {item.description}
  377. </p>
  378. )}
  379. </div>
  380. </CarouselItem>
  381. ))}
  382. </CarouselContent>
  383. <CarouselPrevious />
  384. <CarouselNext />
  385. </CarouselPrimitive>
  386. );
  387. },
  388. // ── Data Display ──────────────────────────────────────────────────
  389. Table: ({ props }) => {
  390. const columns = props.columns ?? [];
  391. const rawRows: unknown[] = Array.isArray(props.rows) ? props.rows : [];
  392. const rows = rawRows.map((row) => {
  393. if (Array.isArray(row)) return row.map(String);
  394. if (row && typeof row === "object") {
  395. const obj = row as Record<string, unknown>;
  396. return columns.map((col) =>
  397. String(obj[col] ?? obj[col.toLowerCase()] ?? ""),
  398. );
  399. }
  400. return columns.map(() => "");
  401. });
  402. return (
  403. <div className="w-full rounded-md border border-border overflow-hidden">
  404. <TablePrimitive>
  405. {props.caption && <TableCaption>{props.caption}</TableCaption>}
  406. <TableHeader>
  407. <TableRow>
  408. {columns.map((col) => (
  409. <TableHead key={col}>{col}</TableHead>
  410. ))}
  411. </TableRow>
  412. </TableHeader>
  413. <TableBody>
  414. {rows.map((row, i) => (
  415. <TableRow key={i}>
  416. {row.map((cell, j) => (
  417. <TableCell key={j}>{cell}</TableCell>
  418. ))}
  419. </TableRow>
  420. ))}
  421. </TableBody>
  422. </TablePrimitive>
  423. </div>
  424. );
  425. },
  426. Heading: ({ props }) => {
  427. const level = props.level ?? "h2";
  428. const headingClass =
  429. level === "h1"
  430. ? "text-2xl font-bold tracking-tight"
  431. : level === "h3"
  432. ? "text-base font-semibold tracking-tight"
  433. : level === "h4"
  434. ? "text-sm font-medium uppercase tracking-wider text-muted-foreground"
  435. : "text-xl font-semibold tracking-tight";
  436. if (level === "h1") return <h1 className={headingClass}>{props.text}</h1>;
  437. if (level === "h3") return <h3 className={headingClass}>{props.text}</h3>;
  438. if (level === "h4") return <h4 className={headingClass}>{props.text}</h4>;
  439. return <h2 className={headingClass}>{props.text}</h2>;
  440. },
  441. Text: ({ props }) => {
  442. const textClass =
  443. props.variant === "caption"
  444. ? "text-xs"
  445. : props.variant === "muted"
  446. ? "text-sm text-muted-foreground"
  447. : props.variant === "lead"
  448. ? "text-xl text-muted-foreground"
  449. : props.variant === "code"
  450. ? "font-mono text-sm bg-muted px-1.5 py-0.5 rounded"
  451. : "text-sm";
  452. if (props.variant === "code") {
  453. return <code className={textClass}>{props.text}</code>;
  454. }
  455. return <p className={textClass}>{props.text}</p>;
  456. },
  457. Image: ({ props }) => {
  458. const src = typeof props.src === "string" ? props.src.trim() : "";
  459. if (src) {
  460. return (
  461. // eslint-disable-next-line @next/next/no-img-element
  462. <img
  463. src={src}
  464. alt={props.alt ?? ""}
  465. loading="lazy"
  466. className="w-full rounded-lg object-cover bg-muted"
  467. style={{
  468. maxWidth: props.width ?? undefined,
  469. height: props.height ?? undefined,
  470. aspectRatio:
  471. props.height == null && props.width == null
  472. ? "16 / 9"
  473. : undefined,
  474. }}
  475. />
  476. );
  477. }
  478. return (
  479. <div
  480. 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"
  481. style={{
  482. maxWidth: props.width ?? undefined,
  483. height: props.height ?? 120,
  484. minHeight: 80,
  485. }}
  486. >
  487. <svg
  488. width="32"
  489. height="32"
  490. viewBox="0 0 24 24"
  491. fill="none"
  492. stroke="currentColor"
  493. strokeWidth="1.5"
  494. strokeLinecap="round"
  495. strokeLinejoin="round"
  496. className="opacity-50"
  497. >
  498. <rect width="18" height="18" x="3" y="3" rx="2" ry="2" />
  499. <circle cx="9" cy="9" r="2" />
  500. <path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" />
  501. </svg>
  502. {props.alt && <span className="text-xs">{props.alt}</span>}
  503. </div>
  504. );
  505. },
  506. Map: ({ props }) => {
  507. const query = String(props.query ?? "");
  508. const zoom = typeof props.zoom === "number" ? props.zoom : 14;
  509. const height = typeof props.height === "number" ? props.height : 320;
  510. const src = `https://maps.google.com/maps?q=${encodeURIComponent(
  511. query,
  512. )}&z=${zoom}&output=embed`;
  513. return (
  514. <iframe
  515. title={query ? `Map: ${query}` : "Map"}
  516. src={src}
  517. className="w-full rounded-lg border border-border"
  518. style={{ height, minHeight: 200 }}
  519. loading="lazy"
  520. referrerPolicy="no-referrer-when-downgrade"
  521. />
  522. );
  523. },
  524. Pressable: ({ children, emit }) => (
  525. <button
  526. type="button"
  527. onClick={() => emit("press")}
  528. 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"
  529. >
  530. {children}
  531. </button>
  532. ),
  533. // Self-contained photo gallery + lightbox. Manages its own open/index state
  534. // with React useState — does NOT depend on the json-render setState action.
  535. Lightbox: ({ props }) => {
  536. const images = (
  537. Array.isArray(props.images) ? props.images : []
  538. ) as Array<{ src: string; caption?: string | null }>;
  539. const cols =
  540. props.columns === 2
  541. ? "grid-cols-2"
  542. : props.columns === 4
  543. ? "grid-cols-4"
  544. : props.columns === 5
  545. ? "grid-cols-5"
  546. : props.columns === 6
  547. ? "grid-cols-6"
  548. : "grid-cols-3";
  549. const [openIndex, setOpenIndex] = useState<number | null>(null);
  550. const current = openIndex !== null ? images[openIndex] : undefined;
  551. useEffect(() => {
  552. if (openIndex === null) return;
  553. const onKey = (e: KeyboardEvent) => {
  554. if (e.key === "Escape") setOpenIndex(null);
  555. if (e.key === "ArrowLeft")
  556. setOpenIndex((i) =>
  557. i === null ? i : (i - 1 + images.length) % images.length,
  558. );
  559. if (e.key === "ArrowRight")
  560. setOpenIndex((i) => (i === null ? i : (i + 1) % images.length));
  561. };
  562. window.addEventListener("keydown", onKey);
  563. return () => window.removeEventListener("keydown", onKey);
  564. }, [openIndex, images.length]);
  565. return (
  566. <>
  567. <div className={`grid w-full gap-3 ${cols}`}>
  568. {images.map((img, i) => (
  569. <button
  570. key={i}
  571. type="button"
  572. onClick={() => setOpenIndex(i)}
  573. className="group relative aspect-square overflow-hidden rounded-lg bg-muted focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"
  574. >
  575. {/* eslint-disable-next-line @next/next/no-img-element */}
  576. <img
  577. src={img.src}
  578. alt={img.caption ?? ""}
  579. loading="lazy"
  580. className="h-full w-full object-cover transition-transform duration-200 group-hover:scale-105"
  581. />
  582. </button>
  583. ))}
  584. </div>
  585. {current && (
  586. <div
  587. className="fixed inset-0 z-50 flex items-center justify-center bg-black/85 p-4 backdrop-blur-sm"
  588. onClick={() => setOpenIndex(null)}
  589. >
  590. <button
  591. type="button"
  592. aria-label="Close"
  593. onClick={() => setOpenIndex(null)}
  594. 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"
  595. >
  596. </button>
  597. {images.length > 1 && (
  598. <button
  599. type="button"
  600. aria-label="Previous"
  601. onClick={(e) => {
  602. e.stopPropagation();
  603. setOpenIndex((i) =>
  604. i === null ? i : (i - 1 + images.length) % images.length,
  605. );
  606. }}
  607. 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"
  608. >
  609. </button>
  610. )}
  611. <figure
  612. className="flex max-h-[90vh] max-w-[92vw] flex-col items-center gap-3"
  613. onClick={(e) => e.stopPropagation()}
  614. >
  615. {/* eslint-disable-next-line @next/next/no-img-element */}
  616. <img
  617. src={current.src}
  618. alt={current.caption ?? ""}
  619. className="max-h-[82vh] max-w-full rounded-lg object-contain shadow-2xl"
  620. />
  621. {current.caption && (
  622. <figcaption className="text-sm text-white/80">
  623. {current.caption}
  624. <span className="ml-2 text-white/50">
  625. {(openIndex ?? 0) + 1} / {images.length}
  626. </span>
  627. </figcaption>
  628. )}
  629. </figure>
  630. {images.length > 1 && (
  631. <button
  632. type="button"
  633. aria-label="Next"
  634. onClick={(e) => {
  635. e.stopPropagation();
  636. setOpenIndex((i) =>
  637. i === null ? i : (i + 1) % images.length,
  638. );
  639. }}
  640. 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"
  641. >
  642. </button>
  643. )}
  644. </div>
  645. )}
  646. </>
  647. );
  648. },
  649. // Self-contained modal: renders its own trigger button and manages open
  650. // state with React useState — no setState / openPath / Dialog needed.
  651. Modal: ({ props, children }) => {
  652. const [open, setOpen] = useState(false);
  653. const variant =
  654. props.triggerVariant === "outline"
  655. ? "outline"
  656. : props.triggerVariant === "secondary"
  657. ? "secondary"
  658. : props.triggerVariant === "danger"
  659. ? "destructive"
  660. : "default";
  661. const sizeClass =
  662. props.size === "lg"
  663. ? "max-w-2xl"
  664. : props.size === "sm"
  665. ? "max-w-sm"
  666. : "max-w-lg";
  667. useEffect(() => {
  668. if (!open) return;
  669. const onKey = (e: KeyboardEvent) => {
  670. if (e.key === "Escape") setOpen(false);
  671. };
  672. window.addEventListener("keydown", onKey);
  673. return () => window.removeEventListener("keydown", onKey);
  674. }, [open]);
  675. return (
  676. <>
  677. <Button variant={variant} onClick={() => setOpen(true)}>
  678. {props.triggerLabel ?? "Open"}
  679. </Button>
  680. {open && (
  681. <div
  682. className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm"
  683. onClick={() => setOpen(false)}
  684. >
  685. <div
  686. role="dialog"
  687. aria-modal="true"
  688. className={`w-full ${sizeClass} rounded-xl border border-border bg-background p-6 shadow-2xl`}
  689. onClick={(e) => e.stopPropagation()}
  690. >
  691. <div className="flex items-start justify-between gap-4">
  692. <div className="min-w-0">
  693. {props.title && (
  694. <h2 className="text-lg font-semibold leading-tight">
  695. {props.title}
  696. </h2>
  697. )}
  698. {props.description && (
  699. <p className="mt-1 text-sm text-muted-foreground">
  700. {props.description}
  701. </p>
  702. )}
  703. </div>
  704. <button
  705. type="button"
  706. aria-label="Close"
  707. onClick={() => setOpen(false)}
  708. className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground"
  709. >
  710. </button>
  711. </div>
  712. {children && <div className="mt-4">{children}</div>}
  713. </div>
  714. </div>
  715. )}
  716. </>
  717. );
  718. },
  719. Icon: ({ props }) => {
  720. const IconComponent = lucideIcons[props.name as keyof typeof lucideIcons];
  721. if (!IconComponent) return null;
  722. const sizeMap = {
  723. sm: 16,
  724. md: 20,
  725. lg: 24,
  726. xl: 32,
  727. "2xl": 48,
  728. "3xl": 64,
  729. } as const;
  730. const px = sizeMap[props.size ?? "md"] ?? 20;
  731. const colorClass =
  732. props.color === "muted"
  733. ? "text-muted-foreground"
  734. : props.color === "primary"
  735. ? "text-primary"
  736. : props.color === "success"
  737. ? "text-green-600 dark:text-green-400"
  738. : props.color === "warning"
  739. ? "text-yellow-600 dark:text-yellow-400"
  740. : props.color === "danger"
  741. ? "text-red-600 dark:text-red-400"
  742. : "";
  743. return <IconComponent size={px} className={`shrink-0 ${colorClass}`} />;
  744. },
  745. Avatar: ({ props }) => {
  746. const name = props.name || "?";
  747. const initials = name
  748. .split(" ")
  749. .map((n) => n[0])
  750. .join("")
  751. .slice(0, 2)
  752. .toUpperCase();
  753. const sizeStyles =
  754. props.size === "lg"
  755. ? { outer: "w-[72px] h-[72px]", text: "text-xl", ring: "ring-[3px]" }
  756. : props.size === "sm"
  757. ? { outer: "w-8 h-8", text: "text-xs", ring: "ring-2" }
  758. : { outer: "w-10 h-10", text: "text-sm", ring: "ring-2" };
  759. return (
  760. <div
  761. 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`}
  762. >
  763. {initials}
  764. </div>
  765. );
  766. },
  767. Badge: ({ props }) => {
  768. const variant =
  769. props.variant === "success" || props.variant === "warning"
  770. ? "secondary"
  771. : props.variant === "danger"
  772. ? "destructive"
  773. : "default";
  774. const customClass =
  775. props.variant === "success"
  776. ? "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-100"
  777. : props.variant === "warning"
  778. ? "bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-100"
  779. : "";
  780. const dotColor =
  781. props.variant === "success"
  782. ? "bg-green-500"
  783. : props.variant === "warning"
  784. ? "bg-yellow-500"
  785. : props.variant === "danger"
  786. ? "bg-red-500"
  787. : "";
  788. return (
  789. <Badge variant={variant} className={`${customClass} gap-1.5`}>
  790. {dotColor && (
  791. <span className={`w-1.5 h-1.5 rounded-full ${dotColor} shrink-0`} />
  792. )}
  793. {props.text}
  794. </Badge>
  795. );
  796. },
  797. Alert: ({ props }) => {
  798. const variant = props.type === "error" ? "destructive" : "default";
  799. const customClass =
  800. props.type === "success"
  801. ? "border-green-200 bg-green-50 text-green-900 dark:border-green-800 dark:bg-green-950 dark:text-green-100"
  802. : props.type === "warning"
  803. ? "border-yellow-200 bg-yellow-50 text-yellow-900 dark:border-yellow-800 dark:bg-yellow-950 dark:text-yellow-100"
  804. : props.type === "info"
  805. ? "border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"
  806. : "";
  807. const iconProps = {
  808. width: 16,
  809. height: 16,
  810. viewBox: "0 0 24 24",
  811. fill: "none",
  812. stroke: "currentColor",
  813. strokeWidth: 2,
  814. strokeLinecap: "round" as const,
  815. strokeLinejoin: "round" as const,
  816. className: "shrink-0",
  817. };
  818. const icon =
  819. props.type === "success" ? (
  820. <svg {...iconProps}>
  821. <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
  822. <polyline points="22 4 12 14.01 9 11.01" />
  823. </svg>
  824. ) : props.type === "warning" ? (
  825. <svg {...iconProps}>
  826. <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" />
  827. <line x1="12" y1="9" x2="12" y2="13" />
  828. <line x1="12" y1="17" x2="12.01" y2="17" />
  829. </svg>
  830. ) : props.type === "error" ? (
  831. <svg {...iconProps}>
  832. <circle cx="12" cy="12" r="10" />
  833. <line x1="15" y1="9" x2="9" y2="15" />
  834. <line x1="9" y1="9" x2="15" y2="15" />
  835. </svg>
  836. ) : (
  837. <svg {...iconProps}>
  838. <circle cx="12" cy="12" r="10" />
  839. <line x1="12" y1="16" x2="12" y2="12" />
  840. <line x1="12" y1="8" x2="12.01" y2="8" />
  841. </svg>
  842. );
  843. return (
  844. <Alert variant={variant} className={customClass}>
  845. {icon}
  846. <AlertTitle>{props.title}</AlertTitle>
  847. {props.message && (
  848. <AlertDescription>{props.message}</AlertDescription>
  849. )}
  850. </Alert>
  851. );
  852. },
  853. Progress: ({ props }) => {
  854. const value = Math.min(100, Math.max(0, props.value || 0));
  855. return (
  856. <div className="w-full space-y-2">
  857. {props.label && (
  858. <Label className="text-sm text-muted-foreground">
  859. {props.label}
  860. </Label>
  861. )}
  862. <Progress value={value} />
  863. </div>
  864. );
  865. },
  866. Skeleton: ({ props }) => (
  867. <Skeleton
  868. className={props.rounded ? "rounded-full" : "rounded-md"}
  869. style={{
  870. width: props.width ?? "100%",
  871. height: props.height ?? "1.25rem",
  872. }}
  873. />
  874. ),
  875. Spinner: ({ props }) => {
  876. const sizeClass =
  877. props.size === "lg"
  878. ? "h-8 w-8"
  879. : props.size === "sm"
  880. ? "h-4 w-4"
  881. : "h-6 w-6";
  882. return (
  883. <div className="flex items-center gap-2">
  884. <svg
  885. className={`${sizeClass} animate-spin text-muted-foreground`}
  886. viewBox="0 0 24 24"
  887. fill="none"
  888. >
  889. <circle
  890. className="opacity-25"
  891. cx="12"
  892. cy="12"
  893. r="10"
  894. stroke="currentColor"
  895. strokeWidth="4"
  896. />
  897. <path
  898. className="opacity-75"
  899. fill="currentColor"
  900. d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
  901. />
  902. </svg>
  903. {props.label && (
  904. <span className="text-sm text-muted-foreground">{props.label}</span>
  905. )}
  906. </div>
  907. );
  908. },
  909. Tooltip: ({ props }) => (
  910. <TooltipProvider>
  911. <TooltipPrimitive>
  912. <TooltipTrigger asChild>
  913. <span className="text-sm underline decoration-dotted cursor-help">
  914. {props.text}
  915. </span>
  916. </TooltipTrigger>
  917. <TooltipContent>
  918. <p>{props.content}</p>
  919. </TooltipContent>
  920. </TooltipPrimitive>
  921. </TooltipProvider>
  922. ),
  923. Popover: ({ props }) => (
  924. <PopoverPrimitive>
  925. <PopoverTrigger asChild>
  926. <Button variant="outline" className="text-sm">
  927. {props.trigger}
  928. </Button>
  929. </PopoverTrigger>
  930. <PopoverContent className="w-64">
  931. <p className="text-sm">{props.content}</p>
  932. </PopoverContent>
  933. </PopoverPrimitive>
  934. ),
  935. Rating: ({ props, bindings, emit }) => {
  936. const [boundValue, setBoundValue] = useBoundProp<number>(
  937. props.value as number | undefined,
  938. bindings?.value,
  939. );
  940. const [localValue, setLocalValue] = useState(props.value || 0);
  941. const isBound = !!bindings?.value;
  942. const ratingValue = isBound ? (boundValue ?? 0) : localValue;
  943. const setValue = isBound ? setBoundValue : setLocalValue;
  944. const maxRating = props.max ?? 5;
  945. const interactive = props.interactive !== false;
  946. const [hoverIndex, setHoverIndex] = useState(-1);
  947. return (
  948. <div className="space-y-2">
  949. {props.label && (
  950. <Label className="text-sm text-muted-foreground">
  951. {props.label}
  952. </Label>
  953. )}
  954. <div
  955. className="flex gap-0.5"
  956. onMouseLeave={() => interactive && setHoverIndex(-1)}
  957. >
  958. {Array.from({ length: maxRating }).map((_, i) => {
  959. const filled =
  960. hoverIndex >= 0 ? i <= hoverIndex : i < ratingValue;
  961. return (
  962. <button
  963. key={i}
  964. type="button"
  965. className={`p-0.5 transition-colors ${interactive ? "cursor-pointer hover:scale-110" : "cursor-default"}`}
  966. onMouseEnter={() => interactive && setHoverIndex(i)}
  967. onClick={() => {
  968. if (!interactive) return;
  969. const newVal = i + 1 === ratingValue ? 0 : i + 1;
  970. setValue(newVal);
  971. emit("change");
  972. }}
  973. >
  974. <svg
  975. width="20"
  976. height="20"
  977. viewBox="0 0 24 24"
  978. fill={filled ? "currentColor" : "none"}
  979. stroke="currentColor"
  980. strokeWidth="1.5"
  981. strokeLinecap="round"
  982. strokeLinejoin="round"
  983. className={
  984. filled ? "text-yellow-400" : "text-muted-foreground/40"
  985. }
  986. >
  987. <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" />
  988. </svg>
  989. </button>
  990. );
  991. })}
  992. </div>
  993. </div>
  994. );
  995. },
  996. Timeline: ({ props }) => (
  997. <div className="relative pl-8">
  998. <div className="absolute left-[5.5px] top-3 bottom-3 w-px bg-border" />
  999. <div className="flex flex-col gap-6">
  1000. {(props.items ?? []).map((item, i) => {
  1001. const dotColor =
  1002. item.status === "completed"
  1003. ? "bg-emerald-500"
  1004. : item.status === "current"
  1005. ? "bg-blue-500"
  1006. : "bg-muted-foreground/30";
  1007. return (
  1008. <div key={i} className="relative">
  1009. <div
  1010. className={`absolute -left-8 top-0.5 h-3 w-3 rounded-full ${dotColor} ring-2 ring-background`}
  1011. />
  1012. <div className="flex-1 min-w-0">
  1013. <div className="flex items-center gap-2 flex-wrap">
  1014. <p className="font-medium text-sm">{item.title}</p>
  1015. {item.date && (
  1016. <span className="text-xs text-muted-foreground bg-muted px-1.5 py-0.5 rounded">
  1017. {item.date}
  1018. </span>
  1019. )}
  1020. </div>
  1021. {item.description && (
  1022. <p className="text-sm text-muted-foreground mt-1">
  1023. {item.description}
  1024. </p>
  1025. )}
  1026. </div>
  1027. </div>
  1028. );
  1029. })}
  1030. </div>
  1031. </div>
  1032. ),
  1033. Metric: ({ props }) => {
  1034. const changeColor =
  1035. props.changeType === "positive"
  1036. ? "text-green-600 dark:text-green-400"
  1037. : props.changeType === "negative"
  1038. ? "text-red-600 dark:text-red-400"
  1039. : "text-muted-foreground";
  1040. const changeIcon =
  1041. props.changeType === "positive"
  1042. ? "\u2191"
  1043. : props.changeType === "negative"
  1044. ? "\u2193"
  1045. : "";
  1046. return (
  1047. <div className="space-y-1">
  1048. <div className="text-sm text-muted-foreground">{props.label}</div>
  1049. <div className="flex items-baseline gap-1.5">
  1050. <span className="text-2xl font-semibold tracking-tight tabular-nums">
  1051. {props.prefix}
  1052. {props.value}
  1053. {props.suffix}
  1054. </span>
  1055. {props.change && (
  1056. <span className={`text-sm font-medium ${changeColor}`}>
  1057. {changeIcon}
  1058. {props.change}
  1059. </span>
  1060. )}
  1061. </div>
  1062. </div>
  1063. );
  1064. },
  1065. // ── Charts ────────────────────────────────────────────────────────
  1066. BarGraph: ({ props }) => {
  1067. const data = props.data || [];
  1068. const maxValue = Math.max(...data.map((d) => d.value), 1);
  1069. const barColors = [
  1070. "bg-primary",
  1071. "bg-primary/80",
  1072. "bg-primary/60",
  1073. "bg-primary/70",
  1074. "bg-primary/90",
  1075. "bg-primary/50",
  1076. ];
  1077. return (
  1078. <div className="space-y-3">
  1079. {props.title && (
  1080. <div className="text-sm font-medium">{props.title}</div>
  1081. )}
  1082. <div className="flex items-end gap-2" style={{ height: 160 }}>
  1083. {data.map((d, i) => (
  1084. <div
  1085. key={i}
  1086. className="flex-1 flex flex-col items-center gap-1.5 h-full justify-end group"
  1087. >
  1088. <div className="text-[11px] font-medium text-muted-foreground tabular-nums">
  1089. {d.value}
  1090. </div>
  1091. <div className="w-full flex-1 flex items-end">
  1092. <div
  1093. className={`w-full ${barColors[i % barColors.length]} rounded-t-md transition-all group-hover:opacity-80`}
  1094. style={{
  1095. height: `${(d.value / maxValue) * 100}%`,
  1096. minHeight: 4,
  1097. }}
  1098. />
  1099. </div>
  1100. <div className="text-[11px] text-muted-foreground truncate w-full text-center">
  1101. {d.label}
  1102. </div>
  1103. </div>
  1104. ))}
  1105. </div>
  1106. </div>
  1107. );
  1108. },
  1109. LineGraph: ({ props }) => {
  1110. const data = props.data || [];
  1111. const maxValue = Math.max(...data.map((d) => d.value));
  1112. const minValue = Math.min(...data.map((d) => d.value));
  1113. const range = maxValue - minValue || 1;
  1114. const width = 300;
  1115. const height = 140;
  1116. const padding = { top: 12, right: 12, bottom: 12, left: 12 };
  1117. const chartWidth = width - padding.left - padding.right;
  1118. const chartHeight = height - padding.top - padding.bottom;
  1119. const points = data.map((d, i) => {
  1120. const x =
  1121. padding.left +
  1122. (data.length > 1
  1123. ? (i / (data.length - 1)) * chartWidth
  1124. : chartWidth / 2);
  1125. const y =
  1126. padding.top +
  1127. chartHeight -
  1128. ((d.value - minValue) / range) * chartHeight;
  1129. return { x, y, ...d };
  1130. });
  1131. // Build smooth cubic bezier curve through points
  1132. let smoothPath = "";
  1133. let areaPath = "";
  1134. if (points.length > 1) {
  1135. const first = points[0]!;
  1136. const last = points[points.length - 1]!;
  1137. smoothPath = `M ${first.x} ${first.y}`;
  1138. for (let i = 0; i < points.length - 1; i++) {
  1139. const curr = points[i]!;
  1140. const next = points[i + 1]!;
  1141. const cpx = (curr.x + next.x) / 2;
  1142. smoothPath += ` C ${cpx} ${curr.y}, ${cpx} ${next.y}, ${next.x} ${next.y}`;
  1143. }
  1144. const bottomY = height - padding.bottom;
  1145. areaPath = `${smoothPath} L ${last.x} ${bottomY} L ${first.x} ${bottomY} Z`;
  1146. } else if (points.length === 1) {
  1147. const only = points[0]!;
  1148. smoothPath = `M ${only.x} ${only.y}`;
  1149. }
  1150. const gradientId = `line-gradient-${Math.random().toString(36).slice(2, 8)}`;
  1151. return (
  1152. <div className="space-y-3">
  1153. {props.title && (
  1154. <div className="text-sm font-medium">{props.title}</div>
  1155. )}
  1156. <div className="relative" style={{ height: 160 }}>
  1157. <svg
  1158. viewBox={`0 0 ${width} ${height}`}
  1159. className="w-full h-full"
  1160. preserveAspectRatio="none"
  1161. >
  1162. <defs>
  1163. <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
  1164. <stop
  1165. offset="0%"
  1166. stopColor="currentColor"
  1167. stopOpacity="0.15"
  1168. />
  1169. <stop
  1170. offset="100%"
  1171. stopColor="currentColor"
  1172. stopOpacity="0"
  1173. />
  1174. </linearGradient>
  1175. </defs>
  1176. {[0, 0.25, 0.5, 0.75, 1].map((frac) => (
  1177. <line
  1178. key={frac}
  1179. x1={padding.left}
  1180. y1={padding.top + chartHeight * frac}
  1181. x2={width - padding.right}
  1182. y2={padding.top + chartHeight * frac}
  1183. stroke="currentColor"
  1184. strokeOpacity="0.07"
  1185. vectorEffect="non-scaling-stroke"
  1186. strokeWidth="1"
  1187. />
  1188. ))}
  1189. {areaPath && (
  1190. <path
  1191. d={areaPath}
  1192. fill={`url(#${gradientId})`}
  1193. className="text-primary"
  1194. />
  1195. )}
  1196. {smoothPath && (
  1197. <path
  1198. d={smoothPath}
  1199. fill="none"
  1200. stroke="currentColor"
  1201. strokeWidth="2"
  1202. strokeLinecap="round"
  1203. strokeLinejoin="round"
  1204. vectorEffect="non-scaling-stroke"
  1205. className="text-primary"
  1206. />
  1207. )}
  1208. </svg>
  1209. {points.map((p, i) => (
  1210. <div
  1211. key={i}
  1212. className="absolute w-[7px] h-[7px] rounded-full bg-primary -translate-x-1/2 -translate-y-1/2"
  1213. style={{
  1214. left: `${(p.x / width) * 100}%`,
  1215. top: `${(p.y / height) * 100}%`,
  1216. }}
  1217. />
  1218. ))}
  1219. </div>
  1220. {points.length > 0 && (
  1221. <div className="relative h-4">
  1222. {points.map((p, i) => (
  1223. <span
  1224. key={i}
  1225. className="absolute text-[11px] text-muted-foreground -translate-x-1/2"
  1226. style={{ left: `${(p.x / width) * 100}%` }}
  1227. >
  1228. {data[i]?.label}
  1229. </span>
  1230. ))}
  1231. </div>
  1232. )}
  1233. </div>
  1234. );
  1235. },
  1236. // ── Form Inputs ───────────────────────────────────────────────────
  1237. Input: ({ props, bindings, emit }) => {
  1238. const [boundValue, setBoundValue] = useBoundProp<string>(
  1239. props.value as string | undefined,
  1240. bindings?.value,
  1241. );
  1242. const [localValue, setLocalValue] = useState("");
  1243. const isBound = !!bindings?.value;
  1244. const value = isBound ? (boundValue ?? "") : localValue;
  1245. const setValue = isBound ? setBoundValue : setLocalValue;
  1246. const hasValidation = !!(bindings?.value && props.checks?.length);
  1247. const { errors, validate } = useFieldValidation(
  1248. bindings?.value ?? "",
  1249. hasValidation ? { checks: props.checks ?? [] } : undefined,
  1250. );
  1251. return (
  1252. <div className="w-full space-y-2">
  1253. {props.label && <Label htmlFor={props.name}>{props.label}</Label>}
  1254. <Input
  1255. id={props.name}
  1256. name={props.name}
  1257. type={props.type ?? "text"}
  1258. placeholder={props.placeholder ?? ""}
  1259. value={value}
  1260. onChange={(e) => setValue(e.target.value)}
  1261. onKeyDown={(e) => {
  1262. if (e.key === "Enter") emit("submit");
  1263. }}
  1264. onFocus={() => emit("focus")}
  1265. onBlur={() => {
  1266. if (hasValidation) validate();
  1267. emit("blur");
  1268. }}
  1269. />
  1270. {errors.length > 0 && (
  1271. <p className="text-sm text-destructive">{errors[0]}</p>
  1272. )}
  1273. </div>
  1274. );
  1275. },
  1276. Textarea: ({ props, bindings }) => {
  1277. const [boundValue, setBoundValue] = useBoundProp<string>(
  1278. props.value as string | undefined,
  1279. bindings?.value,
  1280. );
  1281. const [localValue, setLocalValue] = useState("");
  1282. const isBound = !!bindings?.value;
  1283. const value = isBound ? (boundValue ?? "") : localValue;
  1284. const setValue = isBound ? setBoundValue : setLocalValue;
  1285. const hasValidation = !!(bindings?.value && props.checks?.length);
  1286. const { errors, validate } = useFieldValidation(
  1287. bindings?.value ?? "",
  1288. hasValidation ? { checks: props.checks ?? [] } : undefined,
  1289. );
  1290. return (
  1291. <div className="w-full space-y-2">
  1292. {props.label && <Label htmlFor={props.name}>{props.label}</Label>}
  1293. <Textarea
  1294. id={props.name}
  1295. name={props.name}
  1296. placeholder={props.placeholder ?? ""}
  1297. rows={props.rows ?? 3}
  1298. value={value}
  1299. onChange={(e) => setValue(e.target.value)}
  1300. onBlur={() => {
  1301. if (hasValidation) validate();
  1302. }}
  1303. />
  1304. {errors.length > 0 && (
  1305. <p className="text-sm text-destructive">{errors[0]}</p>
  1306. )}
  1307. </div>
  1308. );
  1309. },
  1310. Select: ({ props, bindings, emit }) => {
  1311. const [boundValue, setBoundValue] = useBoundProp<string>(
  1312. props.value as string | undefined,
  1313. bindings?.value,
  1314. );
  1315. const [localValue, setLocalValue] = useState<string>("");
  1316. const isBound = !!bindings?.value;
  1317. const value = isBound ? (boundValue ?? "") : localValue;
  1318. const setValue = isBound ? setBoundValue : setLocalValue;
  1319. const rawOptions = props.options ?? [];
  1320. // Coerce options to strings – AI may produce objects/numbers instead of
  1321. // plain strings which would cause duplicate `[object Object]` keys.
  1322. const options = rawOptions.map((opt) =>
  1323. typeof opt === "string" ? opt : String(opt ?? ""),
  1324. );
  1325. const hasValidation = !!(bindings?.value && props.checks?.length);
  1326. const { errors, validate } = useFieldValidation(
  1327. bindings?.value ?? "",
  1328. hasValidation ? { checks: props.checks ?? [] } : undefined,
  1329. );
  1330. return (
  1331. <div className="w-full space-y-2">
  1332. <Label>{props.label}</Label>
  1333. <Select
  1334. value={value}
  1335. onValueChange={(v) => {
  1336. setValue(v);
  1337. if (hasValidation) validate();
  1338. emit("change");
  1339. }}
  1340. >
  1341. <SelectTrigger className="w-full">
  1342. <SelectValue placeholder={props.placeholder ?? "Select..."} />
  1343. </SelectTrigger>
  1344. <SelectContent>
  1345. {options.map((opt, idx) => (
  1346. <SelectItem
  1347. key={`${idx}-${opt}`}
  1348. value={opt || `option-${idx}`}
  1349. >
  1350. {opt}
  1351. </SelectItem>
  1352. ))}
  1353. </SelectContent>
  1354. </Select>
  1355. {errors.length > 0 && (
  1356. <p className="text-sm text-destructive">{errors[0]}</p>
  1357. )}
  1358. </div>
  1359. );
  1360. },
  1361. Checkbox: ({ props, bindings, emit }) => {
  1362. const [boundChecked, setBoundChecked] = useBoundProp<boolean>(
  1363. props.checked as boolean | undefined,
  1364. bindings?.checked,
  1365. );
  1366. const [localChecked, setLocalChecked] = useState(!!props.checked);
  1367. const isBound = !!bindings?.checked;
  1368. const checked = isBound ? (boundChecked ?? false) : localChecked;
  1369. const setChecked = isBound ? setBoundChecked : setLocalChecked;
  1370. return (
  1371. <div className="flex items-center space-x-2">
  1372. <Checkbox
  1373. id={props.name}
  1374. checked={checked}
  1375. onCheckedChange={(c) => {
  1376. setChecked(c === true);
  1377. emit("change");
  1378. }}
  1379. />
  1380. <Label htmlFor={props.name} className="cursor-pointer">
  1381. {props.label}
  1382. </Label>
  1383. </div>
  1384. );
  1385. },
  1386. Radio: ({ props, bindings, emit }) => {
  1387. const rawOptions = props.options ?? [];
  1388. const options = rawOptions.map((opt) =>
  1389. typeof opt === "string" ? opt : String(opt ?? ""),
  1390. );
  1391. const [boundValue, setBoundValue] = useBoundProp<string>(
  1392. props.value as string | undefined,
  1393. bindings?.value,
  1394. );
  1395. const [localValue, setLocalValue] = useState(options[0] ?? "");
  1396. const isBound = !!bindings?.value;
  1397. const value = isBound ? (boundValue ?? "") : localValue;
  1398. const setValue = isBound ? setBoundValue : setLocalValue;
  1399. return (
  1400. <div className="w-full space-y-2">
  1401. {props.label && <Label>{props.label}</Label>}
  1402. <RadioGroup
  1403. value={value}
  1404. onValueChange={(v) => {
  1405. setValue(v);
  1406. emit("change");
  1407. }}
  1408. >
  1409. {options.map((opt, idx) => (
  1410. <div
  1411. key={`${idx}-${opt}`}
  1412. className="flex items-center space-x-2"
  1413. >
  1414. <RadioGroupItem
  1415. value={opt || `option-${idx}`}
  1416. id={`${props.name}-${idx}-${opt}`}
  1417. />
  1418. <Label
  1419. htmlFor={`${props.name}-${idx}-${opt}`}
  1420. className="cursor-pointer"
  1421. >
  1422. {opt}
  1423. </Label>
  1424. </div>
  1425. ))}
  1426. </RadioGroup>
  1427. </div>
  1428. );
  1429. },
  1430. Switch: ({ props, bindings, emit }) => {
  1431. const [boundChecked, setBoundChecked] = useBoundProp<boolean>(
  1432. props.checked as boolean | undefined,
  1433. bindings?.checked,
  1434. );
  1435. const [localChecked, setLocalChecked] = useState(!!props.checked);
  1436. const isBound = !!bindings?.checked;
  1437. const checked = isBound ? (boundChecked ?? false) : localChecked;
  1438. const setChecked = isBound ? setBoundChecked : setLocalChecked;
  1439. return (
  1440. <div className="w-full flex items-center justify-between space-x-2">
  1441. <Label htmlFor={props.name} className="cursor-pointer">
  1442. {props.label}
  1443. </Label>
  1444. <Switch
  1445. id={props.name}
  1446. checked={checked}
  1447. onCheckedChange={(c) => {
  1448. setChecked(c);
  1449. emit("change");
  1450. }}
  1451. />
  1452. </div>
  1453. );
  1454. },
  1455. Slider: ({ props, bindings, emit }) => {
  1456. const [boundValue, setBoundValue] = useBoundProp<number>(
  1457. props.value as number | undefined,
  1458. bindings?.value,
  1459. );
  1460. const [localValue, setLocalValue] = useState(props.min ?? 0);
  1461. const isBound = !!bindings?.value;
  1462. const value = isBound ? (boundValue ?? props.min ?? 0) : localValue;
  1463. const setValue = isBound ? setBoundValue : setLocalValue;
  1464. return (
  1465. <div className="w-full space-y-2">
  1466. {props.label && (
  1467. <div className="flex justify-between">
  1468. <Label className="text-sm">{props.label}</Label>
  1469. <span className="text-sm text-muted-foreground">{value}</span>
  1470. </div>
  1471. )}
  1472. <Slider
  1473. value={[value]}
  1474. min={props.min ?? 0}
  1475. max={props.max ?? 100}
  1476. step={props.step ?? 1}
  1477. onValueChange={(v) => {
  1478. setValue(v[0] ?? 0);
  1479. emit("change");
  1480. }}
  1481. />
  1482. </div>
  1483. );
  1484. },
  1485. // ── Actions ───────────────────────────────────────────────────────
  1486. Button: ({ props, emit }) => {
  1487. const variant =
  1488. props.variant === "danger"
  1489. ? "destructive"
  1490. : props.variant === "outline"
  1491. ? "outline"
  1492. : props.variant === "secondary"
  1493. ? "secondary"
  1494. : "default";
  1495. return (
  1496. <Button
  1497. variant={variant}
  1498. disabled={props.disabled ?? false}
  1499. onClick={() => emit("press")}
  1500. >
  1501. {props.label}
  1502. </Button>
  1503. );
  1504. },
  1505. Link: ({ props, emit }) => (
  1506. <Button
  1507. variant="link"
  1508. className="h-auto p-0"
  1509. onClick={() => emit("press")}
  1510. >
  1511. {props.label}
  1512. </Button>
  1513. ),
  1514. DropdownMenu: ({ props, emit }) => {
  1515. const items = props.items ?? [];
  1516. return (
  1517. <DropdownMenuPrimitive>
  1518. <DropdownMenuTrigger asChild>
  1519. <Button variant="outline">{props.label}</Button>
  1520. </DropdownMenuTrigger>
  1521. <DropdownMenuContent>
  1522. {items.map((item) => (
  1523. <DropdownMenuItem key={item.value} onClick={() => emit("select")}>
  1524. {item.label}
  1525. </DropdownMenuItem>
  1526. ))}
  1527. </DropdownMenuContent>
  1528. </DropdownMenuPrimitive>
  1529. );
  1530. },
  1531. Toggle: ({ props, bindings, emit }) => {
  1532. const [boundPressed, setBoundPressed] = useBoundProp<boolean>(
  1533. props.pressed as boolean | undefined,
  1534. bindings?.pressed,
  1535. );
  1536. const [localPressed, setLocalPressed] = useState(props.pressed ?? false);
  1537. const isBound = !!bindings?.pressed;
  1538. const pressed = isBound ? (boundPressed ?? false) : localPressed;
  1539. const setPressed = isBound ? setBoundPressed : setLocalPressed;
  1540. return (
  1541. <Toggle
  1542. variant={props.variant ?? "default"}
  1543. pressed={pressed}
  1544. onPressedChange={(v) => {
  1545. setPressed(v);
  1546. emit("change");
  1547. }}
  1548. >
  1549. {props.label}
  1550. </Toggle>
  1551. );
  1552. },
  1553. ToggleGroup: ({ props, bindings, emit }) => {
  1554. const type = props.type ?? "single";
  1555. const items = props.items ?? [];
  1556. const [boundValue, setBoundValue] = useBoundProp<string>(
  1557. props.value as string | undefined,
  1558. bindings?.value,
  1559. );
  1560. const [localValue, setLocalValue] = useState(items[0]?.value ?? "");
  1561. const isBound = !!bindings?.value;
  1562. const value = isBound ? (boundValue ?? "") : localValue;
  1563. const setValue = isBound ? setBoundValue : setLocalValue;
  1564. if (type === "multiple") {
  1565. return (
  1566. <ToggleGroup type="multiple">
  1567. {items.map((item) => (
  1568. <ToggleGroupItem key={item.value} value={item.value}>
  1569. {item.label}
  1570. </ToggleGroupItem>
  1571. ))}
  1572. </ToggleGroup>
  1573. );
  1574. }
  1575. return (
  1576. <ToggleGroup
  1577. type="single"
  1578. value={value}
  1579. onValueChange={(v) => {
  1580. if (v) {
  1581. setValue(v);
  1582. emit("change");
  1583. }
  1584. }}
  1585. >
  1586. {items.map((item) => (
  1587. <ToggleGroupItem key={item.value} value={item.value}>
  1588. {item.label}
  1589. </ToggleGroupItem>
  1590. ))}
  1591. </ToggleGroup>
  1592. );
  1593. },
  1594. ButtonGroup: ({ props, bindings, emit }) => {
  1595. const buttons = props.buttons ?? [];
  1596. const [boundSelected, setBoundSelected] = useBoundProp<string>(
  1597. props.selected as string | undefined,
  1598. bindings?.selected,
  1599. );
  1600. const [localValue, setLocalValue] = useState(buttons[0]?.value ?? "");
  1601. const isBound = !!bindings?.selected;
  1602. const value = isBound ? (boundSelected ?? "") : localValue;
  1603. const setValue = isBound ? setBoundSelected : setLocalValue;
  1604. return (
  1605. <div className="inline-flex rounded-md border border-border">
  1606. {buttons.map((btn, i) => (
  1607. <button
  1608. key={btn.value}
  1609. className={`px-3 py-1.5 text-sm transition-colors ${
  1610. value === btn.value
  1611. ? "bg-primary text-primary-foreground"
  1612. : "bg-background hover:bg-muted"
  1613. } ${i > 0 ? "border-l border-border" : ""} ${
  1614. i === 0 ? "rounded-l-md" : ""
  1615. } ${i === buttons.length - 1 ? "rounded-r-md" : ""}`}
  1616. onClick={() => {
  1617. setValue(btn.value);
  1618. emit("change");
  1619. }}
  1620. >
  1621. {btn.label}
  1622. </button>
  1623. ))}
  1624. </div>
  1625. );
  1626. },
  1627. Pagination: ({ props, bindings, emit }) => {
  1628. const [boundPage, setBoundPage] = useBoundProp<number>(
  1629. props.page as number | undefined,
  1630. bindings?.page,
  1631. );
  1632. const currentPage = boundPage ?? 1;
  1633. const pages = Array.from({ length: props.totalPages }, (_, i) => i + 1);
  1634. return (
  1635. <PaginationPrimitive>
  1636. <PaginationContent>
  1637. <PaginationItem>
  1638. <PaginationPrevious
  1639. href="#"
  1640. onClick={(e) => {
  1641. e.preventDefault();
  1642. if (currentPage > 1) {
  1643. setBoundPage(currentPage - 1);
  1644. emit("change");
  1645. }
  1646. }}
  1647. />
  1648. </PaginationItem>
  1649. {pages.map((page) => (
  1650. <PaginationItem key={page}>
  1651. <PaginationLink
  1652. href="#"
  1653. isActive={page === currentPage}
  1654. onClick={(e) => {
  1655. e.preventDefault();
  1656. setBoundPage(page);
  1657. emit("change");
  1658. }}
  1659. >
  1660. {page}
  1661. </PaginationLink>
  1662. </PaginationItem>
  1663. ))}
  1664. <PaginationItem>
  1665. <PaginationNext
  1666. href="#"
  1667. onClick={(e) => {
  1668. e.preventDefault();
  1669. if (currentPage < props.totalPages) {
  1670. setBoundPage(currentPage + 1);
  1671. emit("change");
  1672. }
  1673. }}
  1674. />
  1675. </PaginationItem>
  1676. </PaginationContent>
  1677. </PaginationPrimitive>
  1678. );
  1679. },
  1680. },
  1681. actions: {
  1682. // Built-in state actions — handled by ActionProvider, stubs needed for types
  1683. setState: async () => {},
  1684. pushState: async () => {},
  1685. removeState: async () => {},
  1686. // Demo actions — show toasts
  1687. buttonClick: async (params) => {
  1688. const message = (params?.message as string) || "Button clicked!";
  1689. toast.success(message);
  1690. },
  1691. formSubmit: async (params) => {
  1692. const formName = (params?.formName as string) || "Form";
  1693. toast.success(`${formName} submitted successfully!`);
  1694. },
  1695. linkClick: async (params) => {
  1696. const href = (params?.href as string) || "#";
  1697. toast.info(`Navigating to: ${href}`);
  1698. },
  1699. },
  1700. });
  1701. // Fallback component for unknown types
  1702. export function Fallback({ type }: { type: string }) {
  1703. return <div className="text-xs text-muted-foreground">[{type}]</div>;
  1704. }