demo.tsx 51 KB

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