demo.tsx 51 KB

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