demo.tsx 53 KB

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