demo.tsx 51 KB

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