demo.tsx 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772
  1. "use client";
  2. import React, {
  3. useEffect,
  4. useState,
  5. useCallback,
  6. useRef,
  7. useMemo,
  8. } from "react";
  9. import { useUIStream } from "@json-render/react";
  10. import type { Spec } from "@json-render/core";
  11. import { collectUsedComponents, serializeProps } from "@json-render/codegen";
  12. import { toast } from "sonner";
  13. import { CodeBlock } from "./code-block";
  14. import { CopyButton } from "./copy-button";
  15. import { Toaster } from "./ui/sonner";
  16. import { PlaygroundRenderer } from "@/lib/render/renderer";
  17. import { playgroundCatalog } from "@/lib/render/catalog";
  18. import { buildCatalogDisplayData } from "@/lib/render/catalog-display";
  19. const SIMULATION_PROMPT = "Create a contact form with name, email, and message";
  20. interface SimulationStage {
  21. tree: Spec;
  22. stream: string;
  23. }
  24. // Shared state & element definitions for the progressive simulation stages.
  25. const FORM_STATE = { form: { name: "", email: "", message: "" } };
  26. const NAME_INPUT = {
  27. type: "Input",
  28. props: {
  29. label: "Name",
  30. name: "name",
  31. statePath: "/form/name",
  32. checks: [{ type: "required", message: "Name is required" }],
  33. },
  34. } as const;
  35. const EMAIL_INPUT = {
  36. type: "Input",
  37. props: {
  38. label: "Email",
  39. name: "email",
  40. type: "email",
  41. statePath: "/form/email",
  42. checks: [
  43. { type: "required", message: "Email is required" },
  44. { type: "email", message: "Please enter a valid email" },
  45. ],
  46. },
  47. } as const;
  48. const MESSAGE_INPUT = {
  49. type: "Textarea",
  50. props: {
  51. label: "Message",
  52. name: "message",
  53. statePath: "/form/message",
  54. checks: [{ type: "required", message: "Message is required" }],
  55. },
  56. } as const;
  57. const SUBMIT_BUTTON = {
  58. type: "Button",
  59. props: { label: "Send Message", variant: "primary" },
  60. on: { press: { action: "formSubmit" } },
  61. } as const;
  62. const SIMULATION_STAGES: SimulationStage[] = [
  63. {
  64. tree: {
  65. root: "card",
  66. state: FORM_STATE,
  67. elements: {
  68. card: {
  69. type: "Card",
  70. props: { title: "Contact Us", maxWidth: "md" },
  71. children: [],
  72. },
  73. },
  74. },
  75. stream: '{"op":"add","path":"/root","value":"card"}',
  76. },
  77. {
  78. tree: {
  79. root: "card",
  80. state: FORM_STATE,
  81. elements: {
  82. card: {
  83. type: "Card",
  84. props: { title: "Contact Us", maxWidth: "md" },
  85. children: ["name"],
  86. },
  87. name: NAME_INPUT,
  88. },
  89. },
  90. stream:
  91. '{"op":"add","path":"/elements/name","value":{"type":"Input","props":{"label":"Name","name":"name","statePath":"/form/name","checks":[{"type":"required","message":"Name is required"}]}}}',
  92. },
  93. {
  94. tree: {
  95. root: "card",
  96. state: FORM_STATE,
  97. elements: {
  98. card: {
  99. type: "Card",
  100. props: { title: "Contact Us", maxWidth: "md" },
  101. children: ["name", "email"],
  102. },
  103. name: NAME_INPUT,
  104. email: EMAIL_INPUT,
  105. },
  106. },
  107. stream:
  108. '{"op":"add","path":"/elements/email","value":{"type":"Input","props":{"label":"Email","name":"email","type":"email","statePath":"/form/email","checks":[{"type":"required","message":"Email is required"},{"type":"email","message":"Please enter a valid email"}]}}}',
  109. },
  110. {
  111. tree: {
  112. root: "card",
  113. state: FORM_STATE,
  114. elements: {
  115. card: {
  116. type: "Card",
  117. props: { title: "Contact Us", maxWidth: "md" },
  118. children: ["name", "email", "message"],
  119. },
  120. name: NAME_INPUT,
  121. email: EMAIL_INPUT,
  122. message: MESSAGE_INPUT,
  123. },
  124. },
  125. stream:
  126. '{"op":"add","path":"/elements/message","value":{"type":"Textarea","props":{"label":"Message","name":"message","statePath":"/form/message","checks":[{"type":"required","message":"Message is required"}]}}}',
  127. },
  128. {
  129. tree: {
  130. root: "card",
  131. state: FORM_STATE,
  132. elements: {
  133. card: {
  134. type: "Card",
  135. props: { title: "Contact Us", maxWidth: "md" },
  136. children: ["name", "email", "message", "submit"],
  137. },
  138. name: NAME_INPUT,
  139. email: EMAIL_INPUT,
  140. message: MESSAGE_INPUT,
  141. submit: SUBMIT_BUTTON,
  142. },
  143. },
  144. stream:
  145. '{"op":"add","path":"/elements/submit","value":{"type":"Button","props":{"label":"Send Message","variant":"primary"},"on":{"press":{"action":"formSubmit"}}}}',
  146. },
  147. ];
  148. type Mode = "simulation" | "interactive";
  149. type Phase = "typing" | "streaming" | "complete";
  150. type Tab = "stream" | "json" | "nested" | "catalog";
  151. type RenderView = "dynamic" | "static";
  152. interface DemoProps {
  153. fullscreen?: boolean;
  154. skipSimulation?: boolean;
  155. }
  156. /**
  157. * Convert a flat Spec into a nested tree structure that is easier for humans
  158. * to read. Children keys are resolved recursively into inline objects.
  159. */
  160. function specToNested(spec: Spec): Record<string, unknown> {
  161. function resolve(key: string): Record<string, unknown> {
  162. const el = spec.elements[key];
  163. if (!el) return { _key: key, _missing: true };
  164. const node: Record<string, unknown> = { type: el.type };
  165. if (el.props && Object.keys(el.props).length > 0) {
  166. node.props = el.props;
  167. }
  168. if (el.visible !== undefined) {
  169. node.visible = el.visible;
  170. }
  171. if (el.on && Object.keys(el.on).length > 0) {
  172. node.on = el.on;
  173. }
  174. if (el.repeat) {
  175. node.repeat = el.repeat;
  176. }
  177. if (el.children && el.children.length > 0) {
  178. node.children = el.children.map(resolve);
  179. }
  180. return node;
  181. }
  182. const result: Record<string, unknown> = {};
  183. if (spec.state && Object.keys(spec.state).length > 0) {
  184. result.state = spec.state;
  185. }
  186. result.elements = resolve(spec.root);
  187. return result;
  188. }
  189. const EXAMPLE_PROMPTS = [
  190. "Create a login form with email and password",
  191. "Build a feedback form with rating stars",
  192. "Design a contact card with avatar",
  193. "Make a settings panel with toggles",
  194. ];
  195. export function Demo({
  196. fullscreen = false,
  197. skipSimulation = false,
  198. }: DemoProps) {
  199. const [mode, setMode] = useState<Mode>(
  200. skipSimulation ? "interactive" : "simulation",
  201. );
  202. const [phase, setPhase] = useState<Phase>(
  203. skipSimulation ? "complete" : "typing",
  204. );
  205. const [typedPrompt, setTypedPrompt] = useState("");
  206. const [userPrompt, setUserPrompt] = useState("");
  207. const [stageIndex, setStageIndex] = useState(-1);
  208. const [streamLines, setStreamLines] = useState<string[]>([]);
  209. const [activeTab, setActiveTab] = useState<Tab>("json");
  210. const [renderView, setRenderView] = useState<RenderView>("dynamic");
  211. const [simulationTree, setSimulationTree] = useState<Spec | null>(null);
  212. const [isFullscreen, setIsFullscreen] = useState(false);
  213. const [showExportModal, setShowExportModal] = useState(false);
  214. const [selectedExportFile, setSelectedExportFile] = useState<string | null>(
  215. null,
  216. );
  217. const [showMobileFileTree, setShowMobileFileTree] = useState(false);
  218. const [collapsedFolders, setCollapsedFolders] = useState<Set<string>>(
  219. new Set(),
  220. );
  221. const inputRef = useRef<HTMLInputElement>(null);
  222. const [catalogSection, setCatalogSection] = useState<
  223. "components" | "actions"
  224. >("components");
  225. // Catalog data for the catalog tab
  226. const catalogData = useMemo(
  227. () => buildCatalogDisplayData(playgroundCatalog.data),
  228. [],
  229. );
  230. // Disable body scroll when any modal is open
  231. useEffect(() => {
  232. if (isFullscreen || showExportModal) {
  233. document.body.style.overflow = "hidden";
  234. } else {
  235. document.body.style.overflow = "";
  236. }
  237. return () => {
  238. document.body.style.overflow = "";
  239. };
  240. }, [isFullscreen, showExportModal]);
  241. // Use the library's useUIStream hook for real API calls
  242. const {
  243. spec: apiSpec,
  244. isStreaming,
  245. send,
  246. clear,
  247. rawLines: apiRawLines,
  248. } = useUIStream({
  249. api: "/api/generate",
  250. onError: (err: Error) => {
  251. console.error("Generation error:", err);
  252. toast.error(err.message || "Generation failed. Please try again.");
  253. },
  254. } as Parameters<typeof useUIStream>[0]);
  255. const currentSimulationStage =
  256. stageIndex >= 0 ? SIMULATION_STAGES[stageIndex] : null;
  257. // Determine which tree to display - keep simulation tree until new API response
  258. const currentTree =
  259. mode === "simulation"
  260. ? currentSimulationStage?.tree || simulationTree
  261. : apiSpec || simulationTree;
  262. const stopGeneration = useCallback(() => {
  263. if (mode === "simulation") {
  264. setMode("interactive");
  265. setPhase("complete");
  266. setTypedPrompt(SIMULATION_PROMPT);
  267. setUserPrompt("");
  268. }
  269. clear();
  270. }, [mode, clear]);
  271. // Typing effect for simulation
  272. useEffect(() => {
  273. if (mode !== "simulation" || phase !== "typing") return;
  274. let i = 0;
  275. const interval = setInterval(() => {
  276. if (i < SIMULATION_PROMPT.length) {
  277. setTypedPrompt(SIMULATION_PROMPT.slice(0, i + 1));
  278. i++;
  279. } else {
  280. clearInterval(interval);
  281. setTimeout(() => setPhase("streaming"), 500);
  282. }
  283. }, 20);
  284. return () => clearInterval(interval);
  285. }, [mode, phase]);
  286. // Streaming effect for simulation
  287. useEffect(() => {
  288. if (mode !== "simulation" || phase !== "streaming") return;
  289. let i = 0;
  290. const interval = setInterval(() => {
  291. if (i < SIMULATION_STAGES.length) {
  292. const stage = SIMULATION_STAGES[i];
  293. if (stage) {
  294. setStageIndex(i);
  295. setStreamLines((prev) => [...prev, stage.stream]);
  296. setSimulationTree(stage.tree);
  297. }
  298. i++;
  299. } else {
  300. clearInterval(interval);
  301. setTimeout(() => {
  302. setPhase("complete");
  303. setMode("interactive");
  304. setUserPrompt("");
  305. }, 500);
  306. }
  307. }, 600);
  308. return () => clearInterval(interval);
  309. }, [mode, phase]);
  310. // Track stream lines from real API (use raw JSONL patch lines)
  311. useEffect(() => {
  312. if (mode === "interactive" && apiRawLines.length > 0) {
  313. setStreamLines(apiRawLines);
  314. }
  315. }, [mode, apiRawLines]);
  316. const handleSubmit = useCallback(async () => {
  317. if (!userPrompt.trim() || isStreaming) return;
  318. setStreamLines([]);
  319. await send(userPrompt);
  320. }, [userPrompt, isStreaming, send]);
  321. const jsonCode = currentTree
  322. ? JSON.stringify(currentTree, null, 2)
  323. : "// waiting...";
  324. const nestedCode = useMemo(() => {
  325. if (!currentTree || !currentTree.root) return "// waiting...";
  326. return JSON.stringify(specToNested(currentTree), null, 2);
  327. }, [currentTree]);
  328. // Generate all export files for Next.js project
  329. const exportedFiles = useMemo(() => {
  330. if (!currentTree || !currentTree.root) {
  331. return [];
  332. }
  333. const tree = currentTree;
  334. const components = collectUsedComponents(tree);
  335. const files: { path: string; content: string }[] = [];
  336. // Helper to generate JSX
  337. function generateJSX(key: string, indent: number): string {
  338. const element = tree.elements[key];
  339. if (!element) return "";
  340. const spaces = " ".repeat(indent);
  341. const componentName = element.type;
  342. const propsObj: Record<string, unknown> = {};
  343. for (const [k, v] of Object.entries(element.props)) {
  344. if (v !== null && v !== undefined) {
  345. propsObj[k] = v;
  346. }
  347. }
  348. const propsStr = serializeProps(propsObj);
  349. const hasChildren = element.children && element.children.length > 0;
  350. if (!hasChildren) {
  351. return propsStr
  352. ? `${spaces}<${componentName} ${propsStr} />`
  353. : `${spaces}<${componentName} />`;
  354. }
  355. const lines: string[] = [];
  356. lines.push(
  357. propsStr
  358. ? `${spaces}<${componentName} ${propsStr}>`
  359. : `${spaces}<${componentName}>`,
  360. );
  361. for (const childKey of element.children!) {
  362. lines.push(generateJSX(childKey, indent + 1));
  363. }
  364. lines.push(`${spaces}</${componentName}>`);
  365. return lines.join("\n");
  366. }
  367. // 1. package.json
  368. files.push({
  369. path: "package.json",
  370. content: JSON.stringify(
  371. {
  372. name: "generated-app",
  373. version: "0.1.0",
  374. private: true,
  375. scripts: {
  376. dev: "next dev",
  377. build: "next build",
  378. start: "next start",
  379. },
  380. dependencies: {
  381. next: "^16.1.3",
  382. react: "^19.2.3",
  383. "react-dom": "^19.2.3",
  384. },
  385. devDependencies: {
  386. "@types/node": "^25.0.9",
  387. "@types/react": "^19.2.8",
  388. typescript: "^5.9.3",
  389. },
  390. },
  391. null,
  392. 2,
  393. ),
  394. });
  395. // 2. tsconfig.json
  396. files.push({
  397. path: "tsconfig.json",
  398. content: JSON.stringify(
  399. {
  400. compilerOptions: {
  401. target: "ES2017",
  402. lib: ["dom", "dom.iterable", "esnext"],
  403. allowJs: true,
  404. skipLibCheck: true,
  405. strict: true,
  406. noEmit: true,
  407. esModuleInterop: true,
  408. module: "esnext",
  409. moduleResolution: "bundler",
  410. resolveJsonModule: true,
  411. isolatedModules: true,
  412. jsx: "preserve",
  413. incremental: true,
  414. plugins: [{ name: "next" }],
  415. paths: { "@/*": ["./*"] },
  416. },
  417. include: ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  418. exclude: ["node_modules"],
  419. },
  420. null,
  421. 2,
  422. ),
  423. });
  424. // 3. next.config.js
  425. files.push({
  426. path: "next.config.js",
  427. content: `/** @type {import('next').NextConfig} */
  428. module.exports = {
  429. reactStrictMode: true,
  430. };
  431. `,
  432. });
  433. // 4. app/globals.css
  434. files.push({
  435. path: "app/globals.css",
  436. content: `@tailwind base;
  437. @tailwind components;
  438. @tailwind utilities;
  439. :root {
  440. --background: #ffffff;
  441. --foreground: #171717;
  442. --border: #e5e5e5;
  443. --muted-foreground: #737373;
  444. }
  445. @media (prefers-color-scheme: dark) {
  446. :root {
  447. --background: #0a0a0a;
  448. --foreground: #ededed;
  449. --border: #262626;
  450. --muted-foreground: #a3a3a3;
  451. }
  452. }
  453. body {
  454. background: var(--background);
  455. color: var(--foreground);
  456. font-family: system-ui, sans-serif;
  457. }
  458. `,
  459. });
  460. // 5. tailwind.config.js
  461. files.push({
  462. path: "tailwind.config.js",
  463. content: `/** @type {import('tailwindcss').Config} */
  464. module.exports = {
  465. content: ["./app/**/*.{ts,tsx}", "./components/**/*.{ts,tsx}"],
  466. theme: {
  467. extend: {
  468. colors: {
  469. background: "var(--background)",
  470. foreground: "var(--foreground)",
  471. border: "var(--border)",
  472. "muted-foreground": "var(--muted-foreground)",
  473. },
  474. },
  475. },
  476. plugins: [],
  477. };
  478. `,
  479. });
  480. // 6. app/layout.tsx
  481. files.push({
  482. path: "app/layout.tsx",
  483. content: `import type { Metadata } from "next";
  484. import "./globals.css";
  485. export const metadata: Metadata = {
  486. title: "Generated App",
  487. };
  488. export default function RootLayout({
  489. children,
  490. }: {
  491. children: React.ReactNode;
  492. }) {
  493. return (
  494. <html lang="en">
  495. <body>{children}</body>
  496. </html>
  497. );
  498. }
  499. `,
  500. });
  501. // 7. Component files
  502. const componentTemplates: Record<string, string> = {
  503. Card: `"use client";
  504. import { ReactNode } from "react";
  505. interface CardProps {
  506. title?: string;
  507. description?: string;
  508. maxWidth?: "sm" | "md" | "lg";
  509. children?: ReactNode;
  510. }
  511. export function Card({ title, description, maxWidth, children }: CardProps) {
  512. const widthClass = maxWidth === "sm" ? "max-w-xs" : maxWidth === "md" ? "max-w-sm" : maxWidth === "lg" ? "max-w-md" : "w-full";
  513. return (
  514. <div className={\`border border-border rounded-lg p-4 bg-background \${widthClass}\`}>
  515. {title && <div className="font-semibold text-sm mb-1">{title}</div>}
  516. {description && <div className="text-xs text-muted-foreground mb-2">{description}</div>}
  517. <div className="space-y-3">{children}</div>
  518. </div>
  519. );
  520. }
  521. `,
  522. Input: `"use client";
  523. interface InputProps {
  524. label?: string;
  525. name?: string;
  526. type?: string;
  527. placeholder?: string;
  528. }
  529. export function Input({ label, name, type = "text", placeholder }: InputProps) {
  530. return (
  531. <div>
  532. {label && <label className="text-xs text-muted-foreground block mb-1">{label}</label>}
  533. <input
  534. type={type}
  535. name={name}
  536. placeholder={placeholder}
  537. className="h-9 w-full bg-background border border-border rounded px-3 text-sm focus:outline-none focus:ring-2 focus:ring-foreground/20"
  538. />
  539. </div>
  540. );
  541. }
  542. `,
  543. Textarea: `"use client";
  544. interface TextareaProps {
  545. label?: string;
  546. name?: string;
  547. placeholder?: string;
  548. rows?: number;
  549. }
  550. export function Textarea({ label, name, placeholder, rows = 3 }: TextareaProps) {
  551. return (
  552. <div>
  553. {label && <label className="text-xs text-muted-foreground block mb-1">{label}</label>}
  554. <textarea
  555. name={name}
  556. placeholder={placeholder}
  557. rows={rows}
  558. className="w-full bg-background border border-border rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-foreground/20 resize-none"
  559. />
  560. </div>
  561. );
  562. }
  563. `,
  564. Button: `"use client";
  565. interface ButtonProps {
  566. label: string;
  567. variant?: "primary" | "secondary" | "outline";
  568. onClick?: () => void;
  569. }
  570. export function Button({ label, variant = "primary", onClick }: ButtonProps) {
  571. const baseClass = "px-4 py-2 rounded text-sm font-medium transition-colors";
  572. const variantClass = variant === "primary"
  573. ? "bg-foreground text-background hover:bg-foreground/90"
  574. : variant === "outline"
  575. ? "border border-border hover:bg-border/50"
  576. : "bg-border/50 hover:bg-border";
  577. return (
  578. <button onClick={onClick} className={\`\${baseClass} \${variantClass}\`}>
  579. {label}
  580. </button>
  581. );
  582. }
  583. `,
  584. Text: `"use client";
  585. interface TextProps {
  586. content: string;
  587. variant?: "body" | "caption" | "label";
  588. }
  589. export function Text({ content, variant = "body" }: TextProps) {
  590. const sizeClass = variant === "caption" ? "text-xs" : variant === "label" ? "text-sm font-medium" : "text-sm";
  591. return <p className={\`\${sizeClass} text-muted-foreground\`}>{content}</p>;
  592. }
  593. `,
  594. Heading: `"use client";
  595. interface HeadingProps {
  596. text: string;
  597. level?: "h1" | "h2" | "h3" | "h4";
  598. }
  599. export function Heading({ text, level = "h2" }: HeadingProps) {
  600. const Tag = level;
  601. const sizeClass = level === "h1" ? "text-2xl" : level === "h2" ? "text-xl" : level === "h3" ? "text-lg" : "text-base";
  602. return <Tag className={\`\${sizeClass} font-semibold\`}>{text}</Tag>;
  603. }
  604. `,
  605. Stack: `"use client";
  606. import { ReactNode } from "react";
  607. interface StackProps {
  608. direction?: "horizontal" | "vertical";
  609. gap?: "sm" | "md" | "lg";
  610. children?: ReactNode;
  611. }
  612. export function Stack({ direction = "vertical", gap = "md", children }: StackProps) {
  613. const gapClass = gap === "sm" ? "gap-2" : gap === "lg" ? "gap-6" : "gap-4";
  614. const dirClass = direction === "horizontal" ? "flex-row" : "flex-col";
  615. return <div className={\`flex \${dirClass} \${gapClass}\`}>{children}</div>;
  616. }
  617. `,
  618. Grid: `"use client";
  619. import { ReactNode } from "react";
  620. interface GridProps {
  621. columns?: number;
  622. gap?: "sm" | "md" | "lg";
  623. children?: ReactNode;
  624. }
  625. export function Grid({ columns = 2, gap = "md", children }: GridProps) {
  626. const gapClass = gap === "sm" ? "gap-2" : gap === "lg" ? "gap-6" : "gap-4";
  627. return (
  628. <div className={\`grid \${gapClass}\`} style={{ gridTemplateColumns: \`repeat(\${columns}, 1fr)\` }}>
  629. {children}
  630. </div>
  631. );
  632. }
  633. `,
  634. Select: `"use client";
  635. interface SelectProps {
  636. label?: string;
  637. name?: string;
  638. options?: Array<{ value: string; label: string }>;
  639. placeholder?: string;
  640. }
  641. export function Select({ label, name, options = [], placeholder }: SelectProps) {
  642. return (
  643. <div>
  644. {label && <label className="text-xs text-muted-foreground block mb-1">{label}</label>}
  645. <select
  646. name={name}
  647. className="h-9 w-full bg-background border border-border rounded px-3 text-sm focus:outline-none focus:ring-2 focus:ring-foreground/20"
  648. >
  649. {placeholder && <option value="">{placeholder}</option>}
  650. {options.map((opt) => (
  651. <option key={opt.value} value={opt.value}>{opt.label}</option>
  652. ))}
  653. </select>
  654. </div>
  655. );
  656. }
  657. `,
  658. Checkbox: `"use client";
  659. interface CheckboxProps {
  660. label?: string;
  661. name?: string;
  662. checked?: boolean;
  663. }
  664. export function Checkbox({ label, name, checked }: CheckboxProps) {
  665. return (
  666. <label className="flex items-center gap-2 text-sm">
  667. <input type="checkbox" name={name} defaultChecked={checked} className="rounded border-border" />
  668. {label}
  669. </label>
  670. );
  671. }
  672. `,
  673. Radio: `"use client";
  674. interface RadioProps {
  675. label?: string;
  676. name?: string;
  677. options?: Array<{ value: string; label: string }>;
  678. }
  679. export function Radio({ label, name, options = [] }: RadioProps) {
  680. return (
  681. <div>
  682. {label && <div className="text-xs text-muted-foreground mb-1">{label}</div>}
  683. <div className="space-y-1">
  684. {options.map((opt) => (
  685. <label key={opt.value} className="flex items-center gap-2 text-sm">
  686. <input type="radio" name={name} value={opt.value} className="border-border" />
  687. {opt.label}
  688. </label>
  689. ))}
  690. </div>
  691. </div>
  692. );
  693. }
  694. `,
  695. Divider: `"use client";
  696. export function Divider() {
  697. return <hr className="border-border my-4" />;
  698. }
  699. `,
  700. Badge: `"use client";
  701. interface BadgeProps {
  702. text: string;
  703. variant?: "default" | "success" | "warning" | "error";
  704. }
  705. export function Badge({ text, variant = "default" }: BadgeProps) {
  706. const colorClass = variant === "success" ? "bg-green-100 text-green-800"
  707. : variant === "warning" ? "bg-yellow-100 text-yellow-800"
  708. : variant === "error" ? "bg-red-100 text-red-800"
  709. : "bg-border text-foreground";
  710. return <span className={\`px-2 py-0.5 rounded text-xs \${colorClass}\`}>{text}</span>;
  711. }
  712. `,
  713. Switch: `"use client";
  714. interface SwitchProps {
  715. label?: string;
  716. name?: string;
  717. checked?: boolean;
  718. }
  719. export function Switch({ label, name, checked }: SwitchProps) {
  720. return (
  721. <label className="flex items-center justify-between gap-2 text-sm">
  722. {label}
  723. <input type="checkbox" name={name} defaultChecked={checked} className="sr-only peer" />
  724. <div className="w-9 h-5 bg-border rounded-full peer-checked:bg-foreground transition-colors relative after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:w-4 after:h-4 after:bg-background after:rounded-full after:transition-transform peer-checked:after:translate-x-4" />
  725. </label>
  726. );
  727. }
  728. `,
  729. Rating: `"use client";
  730. interface RatingProps {
  731. label?: string;
  732. value?: number;
  733. max?: number;
  734. }
  735. export function Rating({ label, value = 0, max = 5 }: RatingProps) {
  736. return (
  737. <div>
  738. {label && <div className="text-xs text-muted-foreground mb-1">{label}</div>}
  739. <div className="flex gap-1">
  740. {Array.from({ length: max }).map((_, i) => (
  741. <span key={i} className={\`text-lg \${i < value ? "text-yellow-400" : "text-border"}\`}>★</span>
  742. ))}
  743. </div>
  744. </div>
  745. );
  746. }
  747. `,
  748. Form: `"use client";
  749. import { ReactNode } from "react";
  750. interface FormProps {
  751. children?: ReactNode;
  752. }
  753. export function Form({ children }: FormProps) {
  754. return <form className="space-y-4" onSubmit={(e) => e.preventDefault()}>{children}</form>;
  755. }
  756. `,
  757. };
  758. // Add component files
  759. for (const comp of components) {
  760. const template = componentTemplates[comp];
  761. if (template) {
  762. files.push({
  763. path: `components/ui/${comp.toLowerCase()}.tsx`,
  764. content: template,
  765. });
  766. }
  767. }
  768. // 8. components/ui/index.ts
  769. const indexExports = Array.from(components)
  770. .filter((c) => componentTemplates[c])
  771. .map((c) => `export { ${c} } from "./${c.toLowerCase()}";`)
  772. .join("\n");
  773. files.push({
  774. path: "components/ui/index.ts",
  775. content: indexExports + "\n",
  776. });
  777. // 9. app/page.tsx
  778. const jsx = generateJSX(tree.root, 2);
  779. const imports = Array.from(components)
  780. .filter((c) => componentTemplates[c])
  781. .sort()
  782. .join(", ");
  783. files.push({
  784. path: "app/page.tsx",
  785. content: `"use client";
  786. import { ${imports} } from "@/components/ui";
  787. export default function Page() {
  788. return (
  789. <div className="min-h-screen p-8 flex items-center justify-center">
  790. ${jsx}
  791. </div>
  792. );
  793. }
  794. `,
  795. });
  796. // 10. README.md
  797. files.push({
  798. path: "README.md",
  799. content: `# Generated App
  800. This app was generated from a json-render UI tree.
  801. ## Getting Started
  802. \`\`\`bash
  803. npm install
  804. npm run dev
  805. \`\`\`
  806. Open [http://localhost:3000](http://localhost:3000) to view.
  807. `,
  808. });
  809. return files;
  810. }, [currentTree]);
  811. // Reset state when export modal closes
  812. useEffect(() => {
  813. if (!showExportModal) {
  814. setCollapsedFolders(new Set());
  815. setSelectedExportFile(null);
  816. }
  817. }, [showExportModal]);
  818. // Get active file content
  819. const activeExportFile =
  820. selectedExportFile ||
  821. (exportedFiles.length > 0 ? exportedFiles[0]?.path : null);
  822. const activeExportContent =
  823. exportedFiles.find((f) => f.path === activeExportFile)?.content || "";
  824. // Get generated page code for the code tab
  825. const generatedCode =
  826. exportedFiles.find((f) => f.path === "app/page.tsx")?.content ||
  827. "// Generate a UI to see the code";
  828. const downloadAllFiles = useCallback(() => {
  829. const allContent = exportedFiles
  830. .map((f) => `// ========== ${f.path} ==========\n${f.content}`)
  831. .join("\n\n");
  832. const blob = new Blob([allContent], { type: "text/plain" });
  833. const url = URL.createObjectURL(blob);
  834. const a = document.createElement("a");
  835. a.href = url;
  836. a.download = "generated-app.txt";
  837. a.click();
  838. URL.revokeObjectURL(url);
  839. toast("Downloaded generated-app.txt");
  840. }, [exportedFiles]);
  841. const copyFileContent = useCallback((content: string) => {
  842. navigator.clipboard.writeText(content);
  843. toast("Copied to clipboard");
  844. }, []);
  845. const isTypingSimulation = mode === "simulation" && phase === "typing";
  846. const isStreamingSimulation = mode === "simulation" && phase === "streaming";
  847. const showLoadingDots = isStreamingSimulation || isStreaming;
  848. const handleExampleClick = useCallback((prompt: string) => {
  849. setMode("interactive");
  850. setPhase("complete");
  851. setUserPrompt(prompt);
  852. setTimeout(() => {
  853. const el = inputRef.current;
  854. if (el) {
  855. el.focus();
  856. el.setSelectionRange(prompt.length, prompt.length);
  857. }
  858. }, 0);
  859. }, []);
  860. return (
  861. <div
  862. className={`w-full text-left ${fullscreen ? "h-full flex flex-col" : "max-w-5xl mx-auto"}`}
  863. >
  864. {/* Prompt input */}
  865. <div className={fullscreen ? "mb-4" : "mb-6"}>
  866. <div
  867. className="border border-border rounded p-3 bg-background font-mono text-sm min-h-[44px] flex items-center justify-between cursor-text"
  868. onClick={() => {
  869. if (mode === "simulation") {
  870. setMode("interactive");
  871. setPhase("complete");
  872. setUserPrompt("");
  873. setTimeout(() => inputRef.current?.focus(), 0);
  874. } else {
  875. inputRef.current?.focus();
  876. }
  877. }}
  878. >
  879. {mode === "simulation" ? (
  880. <div className="flex items-center flex-1">
  881. <span className="inline-flex items-center h-5">
  882. {typedPrompt}
  883. </span>
  884. {isTypingSimulation && (
  885. <span className="inline-block w-2 h-4 bg-foreground ml-0.5 animate-pulse" />
  886. )}
  887. </div>
  888. ) : (
  889. <form
  890. className="flex items-center flex-1"
  891. onSubmit={(e) => {
  892. e.preventDefault();
  893. handleSubmit();
  894. }}
  895. >
  896. <input
  897. ref={inputRef}
  898. type="text"
  899. value={userPrompt}
  900. onChange={(e) => setUserPrompt(e.target.value)}
  901. placeholder="Describe what you want to build..."
  902. className="flex-1 bg-transparent outline-none placeholder:text-muted-foreground/50 text-base"
  903. disabled={isStreaming}
  904. maxLength={140}
  905. />
  906. </form>
  907. )}
  908. {mode === "simulation" || isStreaming ? (
  909. <button
  910. onClick={(e) => {
  911. e.stopPropagation();
  912. stopGeneration();
  913. }}
  914. className="ml-2 w-7 h-7 rounded-full bg-primary text-primary-foreground flex items-center justify-center hover:bg-primary/90 transition-colors"
  915. aria-label="Stop"
  916. >
  917. <svg
  918. width="16"
  919. height="16"
  920. viewBox="0 0 24 24"
  921. fill="currentColor"
  922. stroke="none"
  923. >
  924. <rect x="6" y="6" width="12" height="12" />
  925. </svg>
  926. </button>
  927. ) : (
  928. <button
  929. onClick={(e) => {
  930. e.stopPropagation();
  931. handleSubmit();
  932. }}
  933. disabled={!userPrompt.trim()}
  934. className="ml-2 w-7 h-7 rounded-full bg-primary text-primary-foreground flex items-center justify-center hover:bg-primary/90 transition-colors disabled:opacity-30"
  935. aria-label="Submit"
  936. >
  937. <svg
  938. width="16"
  939. height="16"
  940. viewBox="0 0 24 24"
  941. fill="none"
  942. stroke="currentColor"
  943. strokeWidth="2"
  944. strokeLinecap="round"
  945. strokeLinejoin="round"
  946. >
  947. <path d="M12 5v14" />
  948. <path d="M19 12l-7 7-7-7" />
  949. </svg>
  950. </button>
  951. )}
  952. </div>
  953. {fullscreen ? (
  954. <div className="mt-3 flex flex-wrap gap-2 justify-center">
  955. {EXAMPLE_PROMPTS.map((prompt) => (
  956. <button
  957. key={prompt}
  958. onClick={() => handleExampleClick(prompt)}
  959. className="text-xs px-3 py-1.5 rounded-full border border-border text-muted-foreground hover:text-foreground hover:border-foreground/50 transition-colors"
  960. >
  961. {prompt}
  962. </button>
  963. ))}
  964. </div>
  965. ) : (
  966. <div className="mt-2 flex flex-wrap gap-1.5 justify-center">
  967. {EXAMPLE_PROMPTS.slice(0, 2).map((prompt) => (
  968. <button
  969. key={prompt}
  970. onClick={() => handleExampleClick(prompt)}
  971. className="text-xs px-2 py-1 rounded-full border border-border text-muted-foreground hover:text-foreground hover:border-foreground/50 transition-colors"
  972. >
  973. {prompt}
  974. </button>
  975. ))}
  976. </div>
  977. )}
  978. </div>
  979. <div
  980. className={`grid lg:grid-cols-2 gap-4 ${fullscreen ? "flex-1 min-h-0" : ""}`}
  981. >
  982. {/* Tabbed code/stream/json panel */}
  983. <div className={`min-w-0 ${fullscreen ? "flex flex-col" : ""}`}>
  984. <div className="flex items-center gap-4 mb-2 h-6 shrink-0">
  985. {(["json", "nested", "stream", "catalog"] as const).map((tab) => (
  986. <button
  987. key={tab}
  988. onClick={() => setActiveTab(tab)}
  989. className={`text-xs font-mono transition-colors ${
  990. activeTab === tab
  991. ? "text-foreground"
  992. : "text-muted-foreground hover:text-foreground"
  993. }`}
  994. >
  995. {tab}
  996. </button>
  997. ))}
  998. </div>
  999. <div
  1000. className={`border border-border rounded bg-background font-mono text-xs text-left grid relative group ${fullscreen ? "flex-1 min-h-0" : "h-[28rem]"}`}
  1001. >
  1002. {activeTab !== "catalog" && (
  1003. <div className="absolute top-2 right-2 z-10">
  1004. <CopyButton
  1005. text={
  1006. activeTab === "stream"
  1007. ? streamLines.join("\n")
  1008. : activeTab === "nested"
  1009. ? nestedCode
  1010. : jsonCode
  1011. }
  1012. className="opacity-0 group-hover:opacity-100 text-muted-foreground"
  1013. />
  1014. </div>
  1015. )}
  1016. <div
  1017. className={`overflow-auto ${activeTab === "stream" ? "" : "hidden"}`}
  1018. >
  1019. {streamLines.length > 0 ? (
  1020. <>
  1021. <CodeBlock
  1022. code={streamLines.join("\n")}
  1023. lang="json"
  1024. fillHeight
  1025. hideCopyButton
  1026. />
  1027. {showLoadingDots && (
  1028. <div className="flex gap-1 p-3 pt-0">
  1029. <span className="w-1 h-1 bg-muted-foreground rounded-full animate-pulse" />
  1030. <span className="w-1 h-1 bg-muted-foreground rounded-full animate-pulse [animation-delay:75ms]" />
  1031. <span className="w-1 h-1 bg-muted-foreground rounded-full animate-pulse [animation-delay:150ms]" />
  1032. </div>
  1033. )}
  1034. </>
  1035. ) : (
  1036. <div className="text-muted-foreground/50 p-3 h-full">
  1037. {showLoadingDots ? "streaming..." : "waiting..."}
  1038. </div>
  1039. )}
  1040. </div>
  1041. <div
  1042. className={`overflow-auto ${activeTab === "json" ? "" : "hidden"}`}
  1043. >
  1044. <CodeBlock
  1045. code={jsonCode}
  1046. lang="json"
  1047. fillHeight
  1048. hideCopyButton
  1049. />
  1050. </div>
  1051. <div
  1052. className={`overflow-auto ${activeTab === "nested" ? "" : "hidden"}`}
  1053. >
  1054. <CodeBlock
  1055. code={nestedCode}
  1056. lang="json"
  1057. fillHeight
  1058. hideCopyButton
  1059. />
  1060. </div>
  1061. <div
  1062. className={`overflow-auto ${activeTab === "catalog" ? "" : "hidden"}`}
  1063. >
  1064. <div className="h-full flex flex-col text-sm font-sans">
  1065. <div className="flex items-center gap-3 px-3 h-9 border-b border-border">
  1066. {(
  1067. [
  1068. {
  1069. key: "components",
  1070. label: `components (${catalogData.components.length})`,
  1071. },
  1072. {
  1073. key: "actions",
  1074. label: `actions (${catalogData.actions.length})`,
  1075. },
  1076. ] as const
  1077. ).map(({ key, label }) => (
  1078. <button
  1079. key={key}
  1080. onClick={() => setCatalogSection(key)}
  1081. className={`text-xs font-mono transition-colors ${
  1082. catalogSection === key
  1083. ? "text-foreground"
  1084. : "text-muted-foreground hover:text-foreground"
  1085. }`}
  1086. >
  1087. {label}
  1088. </button>
  1089. ))}
  1090. </div>
  1091. <div className="flex-1 overflow-auto p-3">
  1092. {catalogSection === "components" ? (
  1093. <div className="space-y-3">
  1094. {catalogData.components.map((comp) => (
  1095. <div
  1096. key={comp.name}
  1097. className="pb-3 border-b border-border last:border-b-0"
  1098. >
  1099. <div className="flex items-baseline gap-2 mb-1">
  1100. <span className="font-mono font-medium text-foreground">
  1101. {comp.name}
  1102. </span>
  1103. {comp.slots.length > 0 && (
  1104. <span className="text-[10px] font-mono px-1.5 py-0.5 rounded bg-muted text-muted-foreground">
  1105. slots: {comp.slots.join(", ")}
  1106. </span>
  1107. )}
  1108. </div>
  1109. {comp.description && (
  1110. <p className="text-xs text-muted-foreground mb-2">
  1111. {comp.description}
  1112. </p>
  1113. )}
  1114. {comp.props.length > 0 && (
  1115. <div className="flex flex-wrap gap-1 mb-1">
  1116. {comp.props.map((p) => (
  1117. <span
  1118. key={p.name}
  1119. className="text-[11px] font-mono px-1.5 py-0.5 rounded bg-green-500/10 text-green-700 dark:text-green-400"
  1120. >
  1121. {p.name}
  1122. <span className="text-green-700/50 dark:text-green-400/50">
  1123. : {p.type}
  1124. </span>
  1125. </span>
  1126. ))}
  1127. </div>
  1128. )}
  1129. {comp.events.length > 0 && (
  1130. <div className="flex flex-wrap gap-1 mt-1.5">
  1131. {comp.events.map((e) => (
  1132. <span
  1133. key={e}
  1134. className="text-[11px] font-mono px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-600 dark:text-blue-400"
  1135. >
  1136. on.{e}
  1137. </span>
  1138. ))}
  1139. </div>
  1140. )}
  1141. </div>
  1142. ))}
  1143. </div>
  1144. ) : (
  1145. <div className="space-y-3">
  1146. {catalogData.actions.map((action) => (
  1147. <div
  1148. key={action.name}
  1149. className="pb-3 border-b border-border last:border-b-0"
  1150. >
  1151. <span className="font-mono font-medium text-foreground">
  1152. {action.name}
  1153. </span>
  1154. {action.description && (
  1155. <p className="text-xs text-muted-foreground mt-1 mb-2">
  1156. {action.description}
  1157. </p>
  1158. )}
  1159. {action.params.length > 0 && (
  1160. <div className="flex flex-wrap gap-1">
  1161. {action.params.map((p) => (
  1162. <span
  1163. key={p.name}
  1164. className="text-[11px] font-mono px-1.5 py-0.5 rounded bg-green-500/10 text-green-700 dark:text-green-400"
  1165. >
  1166. {p.name}
  1167. <span className="text-green-700/50 dark:text-green-400/50">
  1168. : {p.type}
  1169. </span>
  1170. </span>
  1171. ))}
  1172. </div>
  1173. )}
  1174. </div>
  1175. ))}
  1176. </div>
  1177. )}
  1178. </div>
  1179. </div>
  1180. </div>
  1181. </div>
  1182. </div>
  1183. {/* Rendered output using json-render */}
  1184. <div className={`min-w-0 ${fullscreen ? "flex flex-col" : ""}`}>
  1185. <div className="flex items-center justify-between mb-2 h-6 shrink-0">
  1186. <div className="flex items-center gap-4">
  1187. {(
  1188. [
  1189. { key: "dynamic", label: "live render" },
  1190. { key: "static", label: "static code" },
  1191. ] as const
  1192. ).map(({ key, label }) => (
  1193. <button
  1194. key={key}
  1195. onClick={() => setRenderView(key)}
  1196. className={`text-xs font-mono transition-colors ${
  1197. renderView === key
  1198. ? "text-foreground"
  1199. : "text-muted-foreground hover:text-foreground"
  1200. }`}
  1201. >
  1202. {label}
  1203. </button>
  1204. ))}
  1205. </div>
  1206. <div className="flex items-center gap-2">
  1207. <button
  1208. onClick={() => setShowExportModal(true)}
  1209. disabled={!currentTree?.root}
  1210. className="text-xs font-mono text-muted-foreground hover:text-foreground transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
  1211. title="Export as Next.js project"
  1212. >
  1213. export
  1214. </button>
  1215. <button
  1216. onClick={() => setIsFullscreen(true)}
  1217. className="text-muted-foreground hover:text-foreground transition-colors"
  1218. aria-label="Maximize"
  1219. >
  1220. <svg
  1221. width="14"
  1222. height="14"
  1223. viewBox="0 0 24 24"
  1224. fill="none"
  1225. stroke="currentColor"
  1226. strokeWidth="2"
  1227. strokeLinecap="round"
  1228. strokeLinejoin="round"
  1229. >
  1230. <path d="M8 3H5a2 2 0 0 0-2 2v3" />
  1231. <path d="M21 8V5a2 2 0 0 0-2-2h-3" />
  1232. <path d="M3 16v3a2 2 0 0 0 2 2h3" />
  1233. <path d="M16 21h3a2 2 0 0 0 2-2v-3" />
  1234. </svg>
  1235. </button>
  1236. </div>
  1237. </div>
  1238. <div
  1239. className={`border border-border rounded bg-background grid relative group ${fullscreen ? "flex-1 min-h-0" : "h-[28rem]"}`}
  1240. >
  1241. {renderView === "static" && (
  1242. <div className="absolute top-2 right-2 z-10">
  1243. <CopyButton
  1244. text={generatedCode}
  1245. className="opacity-0 group-hover:opacity-100 text-muted-foreground"
  1246. />
  1247. </div>
  1248. )}
  1249. {renderView === "dynamic" ? (
  1250. <div className="overflow-auto">
  1251. {currentTree && currentTree.root ? (
  1252. <div className="animate-in fade-in duration-200 w-full min-h-full flex items-center justify-center p-3 py-4">
  1253. <PlaygroundRenderer
  1254. spec={currentTree}
  1255. loading={isStreaming || isStreamingSimulation}
  1256. />
  1257. </div>
  1258. ) : (
  1259. <div className="h-full flex items-center justify-center text-muted-foreground/50 text-sm">
  1260. {isStreaming ? "generating..." : "waiting..."}
  1261. </div>
  1262. )}
  1263. </div>
  1264. ) : (
  1265. <div className="overflow-auto h-full font-mono text-xs text-left">
  1266. <CodeBlock
  1267. code={generatedCode}
  1268. lang="tsx"
  1269. fillHeight
  1270. hideCopyButton
  1271. />
  1272. </div>
  1273. )}
  1274. </div>
  1275. <Toaster position="bottom-right" />
  1276. </div>
  1277. </div>
  1278. {/* Fullscreen modal */}
  1279. {isFullscreen && (
  1280. <div className="fixed inset-0 z-50 bg-background flex flex-col">
  1281. <div className="flex items-center justify-between px-6 h-14 border-b border-border">
  1282. <div className="text-sm font-mono">render</div>
  1283. <button
  1284. onClick={() => setIsFullscreen(false)}
  1285. className="text-muted-foreground hover:text-foreground transition-colors p-1"
  1286. aria-label="Close"
  1287. >
  1288. <svg
  1289. width="20"
  1290. height="20"
  1291. viewBox="0 0 24 24"
  1292. fill="none"
  1293. stroke="currentColor"
  1294. strokeWidth="2"
  1295. strokeLinecap="round"
  1296. strokeLinejoin="round"
  1297. >
  1298. <path d="M18 6L6 18" />
  1299. <path d="M6 6l12 12" />
  1300. </svg>
  1301. </button>
  1302. </div>
  1303. <div className="flex-1 overflow-auto p-6">
  1304. {currentTree && currentTree.root ? (
  1305. <div className="w-full min-h-full flex items-center justify-center">
  1306. <PlaygroundRenderer
  1307. spec={currentTree}
  1308. loading={isStreaming || isStreamingSimulation}
  1309. />
  1310. </div>
  1311. ) : (
  1312. <div className="h-full flex items-center justify-center text-muted-foreground/50 text-sm">
  1313. {isStreaming ? "generating..." : "waiting..."}
  1314. </div>
  1315. )}
  1316. </div>
  1317. </div>
  1318. )}
  1319. {/* Export Modal */}
  1320. {showExportModal && (
  1321. <div className="fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4 sm:p-8">
  1322. <div className="bg-background border border-border rounded-lg w-full max-w-5xl h-full max-h-[80vh] flex flex-col shadow-2xl">
  1323. {/* Header */}
  1324. <div className="flex items-center justify-between px-4 sm:px-6 h-14 border-b border-border shrink-0">
  1325. <div className="flex items-center gap-2 sm:gap-3">
  1326. {/* Mobile file tree toggle */}
  1327. <button
  1328. onClick={() => setShowMobileFileTree(!showMobileFileTree)}
  1329. className="sm:hidden text-muted-foreground hover:text-foreground transition-colors p-1"
  1330. aria-label="Toggle file tree"
  1331. >
  1332. <svg
  1333. width="18"
  1334. height="18"
  1335. viewBox="0 0 24 24"
  1336. fill="none"
  1337. stroke="currentColor"
  1338. strokeWidth="2"
  1339. strokeLinecap="round"
  1340. strokeLinejoin="round"
  1341. >
  1342. <path d="M3 6h18M3 12h18M3 18h18" />
  1343. </svg>
  1344. </button>
  1345. <span className="text-sm font-mono">export static code</span>
  1346. <span className="text-xs text-muted-foreground bg-muted px-2 py-0.5 rounded hidden sm:inline">
  1347. {exportedFiles.length} files
  1348. </span>
  1349. </div>
  1350. <div className="flex items-center gap-2">
  1351. <button
  1352. onClick={downloadAllFiles}
  1353. className="flex items-center gap-1.5 px-3 py-1.5 text-xs bg-foreground text-background rounded hover:bg-foreground/90 transition-colors"
  1354. >
  1355. <svg
  1356. width="12"
  1357. height="12"
  1358. viewBox="0 0 24 24"
  1359. fill="none"
  1360. stroke="currentColor"
  1361. strokeWidth="2"
  1362. strokeLinecap="round"
  1363. strokeLinejoin="round"
  1364. >
  1365. <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
  1366. <polyline points="7 10 12 15 17 10" />
  1367. <line x1="12" y1="15" x2="12" y2="3" />
  1368. </svg>
  1369. Download All
  1370. </button>
  1371. <button
  1372. onClick={() => setShowExportModal(false)}
  1373. className="text-muted-foreground hover:text-foreground transition-colors p-1"
  1374. aria-label="Close"
  1375. >
  1376. <svg
  1377. width="20"
  1378. height="20"
  1379. viewBox="0 0 24 24"
  1380. fill="none"
  1381. stroke="currentColor"
  1382. strokeWidth="2"
  1383. strokeLinecap="round"
  1384. strokeLinejoin="round"
  1385. >
  1386. <path d="M18 6L6 18" />
  1387. <path d="M6 6l12 12" />
  1388. </svg>
  1389. </button>
  1390. </div>
  1391. </div>
  1392. {/* Content */}
  1393. <div className="flex flex-1 min-h-0 relative">
  1394. {/* File Tree - hidden on mobile, overlay when shown */}
  1395. <div
  1396. className={`
  1397. ${showMobileFileTree ? "absolute inset-0 z-10 bg-background" : "hidden"}
  1398. sm:relative sm:block sm:w-56 sm:bg-transparent
  1399. border-r border-border overflow-auto py-2
  1400. `}
  1401. >
  1402. {(() => {
  1403. // Build tree structure from flat file list
  1404. type TreeNode = {
  1405. name: string;
  1406. path: string;
  1407. isFolder: boolean;
  1408. children: TreeNode[];
  1409. file?: { path: string; content: string };
  1410. };
  1411. const root: TreeNode = {
  1412. name: "",
  1413. path: "",
  1414. isFolder: true,
  1415. children: [],
  1416. };
  1417. exportedFiles.forEach((file) => {
  1418. const parts = file.path.split("/");
  1419. let current = root;
  1420. parts.forEach((part, idx) => {
  1421. const isLast = idx === parts.length - 1;
  1422. const path = parts.slice(0, idx + 1).join("/");
  1423. let child = current.children.find((c) => c.name === part);
  1424. if (!child) {
  1425. child = {
  1426. name: part,
  1427. path,
  1428. isFolder: !isLast,
  1429. children: [],
  1430. file: isLast ? file : undefined,
  1431. };
  1432. current.children.push(child);
  1433. }
  1434. current = child;
  1435. });
  1436. });
  1437. // Sort: folders first, then alphabetically
  1438. const sortNodes = (nodes: TreeNode[]): TreeNode[] => {
  1439. return nodes.sort((a, b) => {
  1440. if (a.isFolder && !b.isFolder) return -1;
  1441. if (!a.isFolder && b.isFolder) return 1;
  1442. return a.name.localeCompare(b.name);
  1443. });
  1444. };
  1445. const toggleFolder = (path: string) => {
  1446. setCollapsedFolders((prev) => {
  1447. const next = new Set(prev);
  1448. if (next.has(path)) {
  1449. next.delete(path);
  1450. } else {
  1451. next.add(path);
  1452. }
  1453. return next;
  1454. });
  1455. };
  1456. const renderNode = (
  1457. node: TreeNode,
  1458. depth: number,
  1459. ): React.ReactNode[] => {
  1460. const result: React.ReactNode[] = [];
  1461. const isExpanded = !collapsedFolders.has(node.path);
  1462. if (node.isFolder && node.name) {
  1463. result.push(
  1464. <button
  1465. key={`folder-${node.path}`}
  1466. onClick={() => toggleFolder(node.path)}
  1467. className="w-full text-left px-3 py-1 text-xs font-mono text-muted-foreground hover:text-foreground hover:bg-foreground/5 transition-colors"
  1468. style={{ paddingLeft: `${12 + depth * 12}px` }}
  1469. >
  1470. <span className="flex items-center gap-1.5">
  1471. <span
  1472. className={`text-gray-400 transition-transform ${isExpanded ? "rotate-90" : ""}`}
  1473. >
  1474. <svg
  1475. width="8"
  1476. height="8"
  1477. viewBox="0 0 24 24"
  1478. fill="currentColor"
  1479. >
  1480. <path d="M8 5l10 7-10 7V5z" />
  1481. </svg>
  1482. </span>
  1483. <span className="text-gray-400">
  1484. <svg
  1485. width="12"
  1486. height="12"
  1487. viewBox="0 0 24 24"
  1488. fill="currentColor"
  1489. >
  1490. <path d="M10 4H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2z" />
  1491. </svg>
  1492. </span>
  1493. {node.name}
  1494. </span>
  1495. </button>,
  1496. );
  1497. }
  1498. if (node.file) {
  1499. const isActive = node.file.path === activeExportFile;
  1500. result.push(
  1501. <button
  1502. key={node.file.path}
  1503. onClick={() => {
  1504. setSelectedExportFile(node.file!.path);
  1505. setShowMobileFileTree(false);
  1506. }}
  1507. className={`w-full text-left px-3 py-1 text-xs font-mono transition-colors ${
  1508. isActive
  1509. ? "bg-foreground/10 text-foreground"
  1510. : "text-muted-foreground hover:text-foreground hover:bg-foreground/5"
  1511. }`}
  1512. style={{ paddingLeft: `${12 + depth * 12}px` }}
  1513. >
  1514. <span className="flex items-center gap-1.5">
  1515. {node.name.endsWith(".tsx") ||
  1516. node.name.endsWith(".ts") ? (
  1517. <span className="text-blue-400">
  1518. <svg
  1519. width="12"
  1520. height="12"
  1521. viewBox="0 0 24 24"
  1522. fill="currentColor"
  1523. >
  1524. <path d="M3 3h18v18H3V3zm16.525 13.707c-.131-.821-.666-1.511-2.252-2.155-.552-.259-1.165-.438-1.349-.854-.068-.248-.083-.382-.039-.527.11-.373.458-.487.757-.381.193.07.37.258.482.52.51-.332.51-.332.86-.553-.132-.203-.203-.293-.297-.382-.335-.382-.78-.58-1.502-.558l-.375.047c-.361.09-.705.272-.923.531-.613.721-.437 1.976.245 2.494.674.476 1.661.59 1.791 1.052.12.543-.406.717-.919.65-.387-.071-.6-.273-.831-.641l-.871.529c.1.217.217.31.39.494.803.796 2.8.749 3.163-.476.013-.04.113-.33.071-.765zm-7.158-2.032c-.227.574-.446 1.148-.677 1.722-.204-.54-.42-1.102-.648-1.68l-.002-.02h-1.09v4.4h.798v-3.269l.796 2.011h.69l.793-2.012v3.27h.798v-4.4h-1.06l-.398 1.02v-.042zm-3.39-3.15v1.2h2.99v8.424h1.524v-8.424h2.99v-1.2H8.977z" />
  1525. </svg>
  1526. </span>
  1527. ) : node.name.endsWith(".json") ? (
  1528. <span className="text-yellow-400">
  1529. <svg
  1530. width="12"
  1531. height="12"
  1532. viewBox="0 0 24 24"
  1533. fill="none"
  1534. stroke="currentColor"
  1535. strokeWidth="2"
  1536. >
  1537. <path d="M4 4h16v16H4z" />
  1538. <path d="M8 8h8M8 12h8M8 16h4" />
  1539. </svg>
  1540. </span>
  1541. ) : node.name.endsWith(".css") ? (
  1542. <span className="text-pink-400">
  1543. <svg
  1544. width="12"
  1545. height="12"
  1546. viewBox="0 0 24 24"
  1547. fill="currentColor"
  1548. >
  1549. <path d="M3 3h18v18H3V3zm15.751 10.875l-.634 7.125-6.125 2-6.125-2-.625-7.125h3.125l.312 3.625 3.313 1.125 3.312-1.125.375-3.625H6.125l-.313-3.125h12.376l-.312 3.125H9.125l.25 1.875h8.376v.125z" />
  1550. </svg>
  1551. </span>
  1552. ) : node.name.endsWith(".md") ? (
  1553. <span className="text-gray-400">
  1554. <svg
  1555. width="12"
  1556. height="12"
  1557. viewBox="0 0 24 24"
  1558. fill="currentColor"
  1559. >
  1560. <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6zM13 9V3.5L18.5 9H13z" />
  1561. </svg>
  1562. </span>
  1563. ) : (
  1564. <span className="text-gray-400">
  1565. <svg
  1566. width="12"
  1567. height="12"
  1568. viewBox="0 0 24 24"
  1569. fill="currentColor"
  1570. >
  1571. <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6zM13 9V3.5L18.5 9H13z" />
  1572. </svg>
  1573. </span>
  1574. )}
  1575. {node.name}
  1576. </span>
  1577. </button>,
  1578. );
  1579. }
  1580. // Only render children if not a folder or if folder is expanded (or root)
  1581. if (!node.isFolder || !node.name || isExpanded) {
  1582. sortNodes(node.children).forEach((child) => {
  1583. result.push(
  1584. ...renderNode(child, node.name ? depth + 1 : depth),
  1585. );
  1586. });
  1587. }
  1588. return result;
  1589. };
  1590. return renderNode(root, 0);
  1591. })()}
  1592. </div>
  1593. {/* Code Preview */}
  1594. <div className="flex-1 flex flex-col min-w-0">
  1595. <div className="flex items-center justify-between px-4 py-2 border-b border-border bg-muted/30">
  1596. <span className="text-xs font-mono text-muted-foreground">
  1597. {activeExportFile}
  1598. </span>
  1599. <button
  1600. onClick={() => copyFileContent(activeExportContent)}
  1601. className="text-xs text-muted-foreground hover:text-foreground transition-colors flex items-center gap-1"
  1602. >
  1603. <svg
  1604. width="12"
  1605. height="12"
  1606. viewBox="0 0 24 24"
  1607. fill="none"
  1608. stroke="currentColor"
  1609. strokeWidth="2"
  1610. strokeLinecap="round"
  1611. strokeLinejoin="round"
  1612. >
  1613. <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
  1614. <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
  1615. </svg>
  1616. Copy
  1617. </button>
  1618. </div>
  1619. <div className="flex-1 overflow-auto">
  1620. <CodeBlock
  1621. code={activeExportContent}
  1622. lang={activeExportFile?.endsWith(".json") ? "json" : "tsx"}
  1623. fillHeight
  1624. hideCopyButton
  1625. />
  1626. </div>
  1627. </div>
  1628. </div>
  1629. </div>
  1630. </div>
  1631. )}
  1632. </div>
  1633. );
  1634. }