demo.tsx 61 KB

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