demo.tsx 53 KB

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