├── .env.local.example ├── .eslintrc.json ├── .gitignore ├── .idea ├── .gitignore ├── inspectionProfiles │ └── Project_Default.xml ├── jsLinters │ └── eslint.xml ├── misc.xml ├── modules.xml ├── react-preview-editor.iml └── vcs.xml ├── .nvmrc ├── LICENSE ├── README.md ├── components.json ├── next.config.js ├── package.json ├── pnpm-lock.yaml ├── postcss.config.js ├── prisma └── schema.prisma ├── public ├── next.svg └── vercel.svg ├── screenrun-02-27-2024-16-20-25.mp4 ├── screenrun-02-27-2024-16-44-02.mp4 ├── setup.sh ├── src ├── actions │ └── chat.ts ├── app │ ├── api │ │ └── chat │ │ │ └── route.ts │ ├── favicon.ico │ ├── globals.css │ ├── layout.tsx │ └── page.tsx ├── components │ ├── ChatHistory.tsx │ ├── EditorChat.tsx │ ├── EditorSection.tsx │ ├── Navbar.tsx │ ├── Preview.tsx │ ├── Sidebar.tsx │ ├── icons │ │ ├── ChatIcon.tsx │ │ ├── PlusIcon.tsx │ │ └── SendIcon.tsx │ └── ui │ │ ├── accordion.tsx │ │ ├── button.tsx │ │ ├── card.tsx │ │ ├── command.tsx │ │ ├── dialog.tsx │ │ ├── drawer.tsx │ │ ├── dropdown-menu.tsx │ │ ├── form.tsx │ │ ├── hover-card.tsx │ │ ├── input.tsx │ │ ├── label.tsx │ │ ├── menubar.tsx │ │ ├── navigation-menu.tsx │ │ ├── popover.tsx │ │ ├── progress.tsx │ │ ├── resizable.tsx │ │ ├── scroll-area.tsx │ │ ├── select.tsx │ │ ├── slider.tsx │ │ ├── sonner.tsx │ │ └── textarea.tsx ├── hooks │ └── useLocalStorage.ts └── lib │ ├── prisma.ts │ └── utils.ts ├── tailwind.config.js ├── tailwind.config.ts ├── tsconfig.json └── yarn.lock /.env.local.example: -------------------------------------------------------------------------------- 1 | OPENAI_API_KEY= 2 | DATABASE_URL_DIRECT= 3 | DATABASE_URL= 4 | NEXT_PUBLIC_GTM_ID= -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "next/core-web-vitals" 3 | } 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | .env 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # next.js 12 | /.next/ 13 | /out/ 14 | 15 | # production 16 | /build 17 | 18 | # misc 19 | .DS_Store 20 | *.pem 21 | 22 | # debug 23 | npm-debug.log* 24 | yarn-debug.log* 25 | yarn-error.log* 26 | 27 | 28 | # vercel 29 | .vercel 30 | 31 | # typescript 32 | *.tsbuildinfo 33 | next-env.d.ts 34 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Datasource local storage ignored files 5 | /dataSources/ 6 | /dataSources.local.xml 7 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /.idea/jsLinters/eslint.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/react-preview-editor.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | v18.16.1 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Nextjs Page Generator 2 | Inspired by project ChatGPT powered React Code Generator which already allows you to specify what kind of React component you want to build and directly get the code and a live preview. 3 | With Nextjs Page Generator you can easily craft UI for pages in your Nextjs project. Use chat to continue your UI as if you're coding it. Engineers can use it to draft up several pages to copy as pages into your main code base. If starting from scratch, you can export the preview to CodeSandbox, where you can develop within a devbox or initiate a Github Repo. The code generated by Nextjs Page Generator is styled with [TailwindCSS](https://tailwindcss.com/) or plain inline CSS. 4 | 5 | Screenshot 2024-03-02 165534 6 | 7 | ## Goals 8 | 9 | The goal of this project is to have a playground for frontend developers to quickly generate and tweak and export AI generated UI. In the current state it supports TailwindCSS and plain inline CSS but this could easily be extended with prompting. 10 | 11 | Future investments includes: 12 | - Support for other styling frameworks (Shadcn imports TSX & Stackblitz) 13 | - Auto-save and deploy projects to Vercel or Netlify 14 | - Provide context to an existing project that needs to be extended 15 | 16 | ## Getting Started 17 | 18 | Install dependencies with `yarn`, `npm` or `pnpm`. 19 | 20 | 21 | Set your OpenAI key by running the setup script `./setup.sh`. 22 | Or by editing `.env.local` if you're running this code locally. 23 | 24 | Then run the development server: 25 | 26 | ```bash 27 | npm run dev 28 | # or 29 | yarn dev 30 | # or 31 | pnpm dev 32 | ``` 33 | Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. 34 | 35 | ### Demos 36 | For example, this page was generated with a single a prompt and included the axios request setup: 37 | Screenshot 2024-03-02 004705 38 | 39 | https://github.com/cameronking4/nextjs-page-generator-main/assets/35708477/1aacd777-a2b1-4d85-8f90-f4a61c0b4447 40 | 41 | https://github.com/cameronking4/nextjs-ai-page-generator/assets/35708477/add6086d-d314-4be2-b2aa-5b3f71c48c97 42 | 43 | https://github.com/cameronking4/nextjs-page-generator-main/assets/35708477/b5f0698d-720d-4613-809d-4094fc2e4646 44 | 45 | 46 | -------------------------------------------------------------------------------- /components.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://ui.shadcn.com/schema.json", 3 | "style": "default", 4 | "rsc": true, 5 | "tsx": true, 6 | "tailwind": { 7 | "config": "tailwind.config.ts", 8 | "css": "src/app/globals.css", 9 | "baseColor": "zinc", 10 | "cssVariables": true, 11 | "prefix": "" 12 | }, 13 | "aliases": { 14 | "components": "@/components", 15 | "utils": "@/lib/utils" 16 | } 17 | } -------------------------------------------------------------------------------- /next.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('next').NextConfig} */ 2 | const nextConfig = { 3 | experimental: { 4 | serverActions: true, 5 | } 6 | } 7 | 8 | module.exports = nextConfig 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-preview-editor", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "dev": "next dev", 7 | "build": "next build", 8 | "start": "next start", 9 | "lint": "next lint", 10 | "postinstall": "prisma generate" 11 | }, 12 | "dependencies": { 13 | "@babel/standalone": "^7.22.10", 14 | "@codesandbox/nodebox": "^0.1.9", 15 | "@codesandbox/sandpack-react": "^2.13.2", 16 | "@codesandbox/sandpack-themes": "^2.0.21", 17 | "@hookform/resolvers": "^3.3.4", 18 | "@magicul/next-google-tag-manager": "^1.0.0", 19 | "@monaco-editor/react": "^4.5.1", 20 | "@prisma/client": "^5.2.0", 21 | "@radix-ui/react-accordion": "^1.1.2", 22 | "@radix-ui/react-dialog": "^1.0.5", 23 | "@radix-ui/react-dropdown-menu": "^2.0.6", 24 | "@radix-ui/react-hover-card": "^1.0.7", 25 | "@radix-ui/react-label": "^2.0.2", 26 | "@radix-ui/react-menubar": "^1.0.4", 27 | "@radix-ui/react-navigation-menu": "^1.1.4", 28 | "@radix-ui/react-popover": "^1.0.7", 29 | "@radix-ui/react-progress": "^1.0.3", 30 | "@radix-ui/react-scroll-area": "^1.0.5", 31 | "@radix-ui/react-select": "^2.0.0", 32 | "@radix-ui/react-slider": "^1.1.2", 33 | "@radix-ui/react-slot": "^1.0.2", 34 | "@types/node": "20.4.2", 35 | "@types/react": "18.2.14", 36 | "@types/react-dom": "18.2.7", 37 | "@types/uuid": "^9.0.2", 38 | "ai": "^2.2.33", 39 | "autoprefixer": "10.4.14", 40 | "class-variance-authority": "^0.7.0", 41 | "clsx": "^2.1.0", 42 | "cmdk": "^0.2.1", 43 | "eslint": "8.44.0", 44 | "eslint-config-next": "13.4.9", 45 | "lucide-react": "^0.341.0", 46 | "next": "13.4.9", 47 | "next-themes": "^0.2.1", 48 | "openai-edge": "^1.2.0", 49 | "postcss": "8.4.25", 50 | "prisma": "^5.2.0", 51 | "react": "18.2.0", 52 | "react-dom": "18.2.0", 53 | "react-hook-form": "^7.50.1", 54 | "react-resizable-panels": "^2.0.11", 55 | "sonner": "^1.4.2", 56 | "tailwind-merge": "^2.2.1", 57 | "tailwindcss": "3.3.2", 58 | "tailwindcss-animate": "^1.0.7", 59 | "typescript": "5.1.6", 60 | "uuid": "^9.0.0", 61 | "vaul": "^0.9.0", 62 | "zod": "^3.22.4" 63 | }, 64 | "devDependencies": { 65 | "@types/babel__standalone": "^7.1.4" 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /postcss.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: { 3 | tailwindcss: {}, 4 | autoprefixer: {}, 5 | }, 6 | } 7 | -------------------------------------------------------------------------------- /prisma/schema.prisma: -------------------------------------------------------------------------------- 1 | generator client { 2 | provider = "prisma-client-js" 3 | } 4 | 5 | datasource db { 6 | provider = "postgresql" 7 | url = env("DATABASE_URL") 8 | directUrl = env("DATABASE_URL_DIRECT") 9 | } 10 | 11 | model Project { 12 | id String @id @default(cuid()) 13 | createdAt DateTime @default(now()) 14 | messages ChatMessage[] 15 | } 16 | 17 | model ChatMessage { 18 | id String @id @default(cuid()) 19 | createdAt DateTime @default(now()) 20 | content String 21 | role String 22 | project Project @relation(fields: [projectId], references: [id]) 23 | projectId String 24 | } 25 | -------------------------------------------------------------------------------- /public/next.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/vercel.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /screenrun-02-27-2024-16-20-25.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cameronking4/nextjs-ai-page-generator/b859d8d30e554e7a03687f7fbccbe036a7d85746/screenrun-02-27-2024-16-20-25.mp4 -------------------------------------------------------------------------------- /screenrun-02-27-2024-16-44-02.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cameronking4/nextjs-ai-page-generator/b859d8d30e554e7a03687f7fbccbe036a7d85746/screenrun-02-27-2024-16-44-02.mp4 -------------------------------------------------------------------------------- /setup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # copy .env.local.example to .env.local 4 | cp .env.local.example .env.local 5 | 6 | # prompt user to enter OpenAI API key 7 | echo "Please enter your OpenAI API key:" 8 | read openai_key 9 | 10 | # Determine the operating system and run the appropriate sed command 11 | if [[ "$(uname)" == "Darwin" ]]; then 12 | # MacOS 13 | sed -i '' "s|OPENAI_API_KEY=|OPENAI_API_KEY=$openai_key|" .env.local 14 | else 15 | # Linux/Unix 16 | sed -i "s|OPENAI_API_KEY=|OPENAI_API_KEY=$openai_key|" .env.local 17 | fi 18 | 19 | echo "API key has been set in .env.local file." 20 | -------------------------------------------------------------------------------- /src/actions/chat.ts: -------------------------------------------------------------------------------- 1 | 'use server'; 2 | 3 | import prisma from '../lib/prisma'; 4 | import { Message } from 'ai'; 5 | 6 | export const storeProject = async (id: string) => prisma.project.create({ data: { id } }); 7 | 8 | export const storeChatMessages = async ( 9 | projectId: string, 10 | messages: Message[], 11 | ) => prisma.chatMessage.createMany({ 12 | data: messages.map((message) => ({ 13 | id: message.id, 14 | projectId, 15 | content: message.content, 16 | role: message.role, 17 | })), 18 | skipDuplicates: true, 19 | }); 20 | 21 | export const getChatMessages = async (projectId: string) => prisma.chatMessage.findMany({ 22 | where: { projectId }, 23 | }); 24 | -------------------------------------------------------------------------------- /src/app/api/chat/route.ts: -------------------------------------------------------------------------------- 1 | import { Configuration, OpenAIApi } from 'openai-edge' 2 | import { OpenAIStream, StreamingTextResponse } from 'ai' 3 | import { NextRequest } from 'next/server'; 4 | 5 | const config = new Configuration({ 6 | apiKey: process.env.OPENAI_API_KEY 7 | }) 8 | const openai = new OpenAIApi(config) 9 | 10 | export const runtime = 'edge' 11 | 12 | export async function POST(req: NextRequest) { 13 | const { messages } = await req.json() 14 | const response = await openai.createChatCompletion({ 15 | model: 'gpt-4', 16 | stream: true, 17 | max_tokens: 3000, 18 | messages 19 | }) 20 | const stream = OpenAIStream(response) 21 | return new StreamingTextResponse(stream) 22 | } 23 | -------------------------------------------------------------------------------- /src/app/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cameronking4/nextjs-ai-page-generator/b859d8d30e554e7a03687f7fbccbe036a7d85746/src/app/favicon.ico -------------------------------------------------------------------------------- /src/app/globals.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | 5 | @layer base { 6 | :root { 7 | --background: 0 0% 100%; 8 | --foreground: 240 10% 3.9%; 9 | 10 | --card: 0 0% 100%; 11 | --card-foreground: 240 10% 3.9%; 12 | 13 | --popover: 0 0% 100%; 14 | --popover-foreground: 240 10% 3.9%; 15 | 16 | --primary: 240 5.9% 10%; 17 | --primary-foreground: 0 0% 98%; 18 | 19 | --secondary: 240 4.8% 95.9%; 20 | --secondary-foreground: 240 5.9% 10%; 21 | 22 | --muted: 240 4.8% 95.9%; 23 | --muted-foreground: 240 3.8% 46.1%; 24 | 25 | --accent: 240 4.8% 95.9%; 26 | --accent-foreground: 240 5.9% 10%; 27 | 28 | --destructive: 0 84.2% 60.2%; 29 | --destructive-foreground: 0 0% 98%; 30 | 31 | --border: 240 5.9% 90%; 32 | --input: 240 5.9% 90%; 33 | --ring: 240 10% 3.9%; 34 | 35 | --radius: 0.5rem; 36 | } 37 | 38 | .dark { 39 | --background: 240 10% 3.9%; 40 | --foreground: 0 0% 98%; 41 | 42 | --card: 240 10% 3.9%; 43 | --card-foreground: 0 0% 98%; 44 | 45 | --popover: 240 10% 3.9%; 46 | --popover-foreground: 0 0% 98%; 47 | 48 | --primary: 0 0% 98%; 49 | --primary-foreground: 240 5.9% 10%; 50 | 51 | --secondary: 240 3.7% 15.9%; 52 | --secondary-foreground: 0 0% 98%; 53 | 54 | --muted: 240 3.7% 15.9%; 55 | --muted-foreground: 240 5% 64.9%; 56 | 57 | --accent: 240 3.7% 15.9%; 58 | --accent-foreground: 0 0% 98%; 59 | 60 | --destructive: 0 62.8% 30.6%; 61 | --destructive-foreground: 0 0% 98%; 62 | 63 | --border: 240 3.7% 15.9%; 64 | --input: 240 3.7% 15.9%; 65 | --ring: 240 4.9% 83.9%; 66 | } 67 | } -------------------------------------------------------------------------------- /src/app/layout.tsx: -------------------------------------------------------------------------------- 1 | import './globals.css' 2 | import type { Metadata } from 'next' 3 | import { Inter } from 'next/font/google' 4 | import { Toaster } from "@/components/ui/sonner" 5 | import GoogleTagManager from '@magicul/next-google-tag-manager'; 6 | import { Suspense } from "react"; 7 | import NavbarComponent from '@/components/Navbar'; 8 | 9 | const inter = Inter({ subsets: ['latin'] }) 10 | 11 | export const metadata: Metadata = { 12 | title: 'Nextjs Page Generator', 13 | description: 'Easily design pages for your Nextjs app with functional components. Code generated using OpenAI\'s GPT4', 14 | } 15 | export default function RootLayout({ 16 | children, 17 | }: { 18 | children: React.ReactNode 19 | }) { 20 | return ( 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 |
29 | {children} 30 |
31 | 32 |
33 |
34 | 35 | 36 | ) 37 | } -------------------------------------------------------------------------------- /src/app/page.tsx: -------------------------------------------------------------------------------- 1 | 'use client'; 2 | 3 | import { useEffect, useState } from 'react'; 4 | import { Preview } from '@/components/Preview'; 5 | import { EditorChat } from '@/components/EditorChat'; 6 | import { Project, Sidebar } from '@/components/Sidebar'; 7 | import { transform } from '@babel/standalone'; 8 | import { useRouter, useSearchParams } from 'next/navigation'; 9 | import useLocalStorage from '@/hooks/useLocalStorage'; 10 | import { 11 | ResizableHandle, 12 | ResizablePanel, 13 | ResizablePanelGroup, 14 | } from "@/components/ui/resizable" 15 | 16 | const App = () => { 17 | const [code, setCode] = useState(''); 18 | const [preview, setPreview] = useState(null); 19 | const [projects] = useLocalStorage('projects', []); 20 | const searchParams = useSearchParams(); 21 | const project = searchParams.get('project'); 22 | const router = useRouter(); 23 | 24 | const runCode = (code: string | undefined) => { 25 | setCode(code); 26 | 27 | try { 28 | // const transformed = transform(code ?? '', { presets: ['react'] }).code; 29 | // console.log(transformed) 30 | setPreview(code ?? null); 31 | } catch (err) { 32 | setPreview(`Error: ${err}`); 33 | } 34 | }; 35 | 36 | useEffect(() => { 37 | if (!project && projects?.length) { 38 | router.push(`?project=${projects[0].id}`) 39 | } 40 | }, [projects, project, router]); 41 | 42 | return ( 43 |
44 | {project && ( 45 | <> 46 | 47 | 48 | 49 | 50 | 51 | 52 | )} 53 |
54 | ); 55 | }; 56 | 57 | export default App; 58 | -------------------------------------------------------------------------------- /src/components/ChatHistory.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | import { 3 | Select, 4 | SelectContent, 5 | SelectGroup, 6 | SelectItem, 7 | SelectLabel, 8 | SelectTrigger, 9 | SelectValue, 10 | } from "@/components/ui/select" 11 | import { Button } from "@/components/ui/button" 12 | import { useRouter, useSearchParams } from 'next/navigation'; 13 | import { PlusIcon } from '@/components/icons/PlusIcon'; 14 | import useLocalStorage from '@/hooks/useLocalStorage'; 15 | import { storeProject } from '@/actions/chat'; 16 | import { v4 as uuidv4 } from 'uuid'; 17 | import { ChatIcon } from '@/components/icons/ChatIcon'; 18 | import { useEffect } from 'react'; 19 | import Link from "next/link"; 20 | 21 | export type Project = { 22 | id: string; 23 | }; 24 | 25 | export function ChatHistory() { 26 | const searchParams = useSearchParams(); 27 | const currentProject = searchParams.get('project'); 28 | const router = useRouter(); 29 | const [projects, setProjects] = useLocalStorage('projects', []); 30 | const reverseProjects = projects?.slice().reverse(); 31 | 32 | const createNewProject = async () => { 33 | const uuid = uuidv4(); 34 | await storeProject(uuid); 35 | setProjects([...projects ?? [], { id: uuid }]); 36 | router.push(`?project=${uuid}`); 37 | } 38 | 39 | useEffect(() => { 40 | if (projects?.length === 0) console.log("NO PROJECTS FOUND"); 41 | // eslint-disable-next-line react-hooks/exhaustive-deps 42 | }, [projects?.length]); 43 | 44 | return ( 45 |
46 |
47 | 65 |
66 |
67 | ) 68 | } 69 | -------------------------------------------------------------------------------- /src/components/EditorChat.tsx: -------------------------------------------------------------------------------- 1 | import { FC, useEffect, useRef, useState } from 'react'; 2 | import { useChat } from 'ai/react'; 3 | import { EditorSection } from '@/components/EditorSection'; 4 | import { useSearchParams } from 'next/navigation'; 5 | import { getChatMessages, storeChatMessages } from '@/actions/chat'; 6 | import { SendIcon } from '@/components/icons/SendIcon'; 7 | import { Input } from './ui/input'; 8 | import { Button } from './ui/button'; 9 | import { ChatHistory } from './ChatHistory'; 10 | import NavbarComponent from './Navbar'; 11 | 12 | const basePrompt = `I want you to act like a code generator and only return JSX code, nothing else. Can you please provide me with a React function component for a NextJS page? The component should be named "Page". Remember, I am specifically interested in the actual code implementation (a React function component), no description (this also applies for any improving of the component or approach to implementing). 13 | For styling you can use inline TailwindCSS, as you can assume that the styles are present. 14 | 15 | GUIDANCE: 16 | - Use this documentation if you ever want to use icons: https://lucide.dev/guide/packages/lucide-react 17 | - The sandbox only has lucide-react icons, no other framework. 18 | It's critical you include import statements and relevant/accurate dependencies 19 | 20 | RULES: 21 | - Never say a task is too complex, implement the simplest version or MVP 22 | - Never reply with your thoughts or summary, only respond with the code itself 23 | 24 | EXAMPLE RESPONSE: 25 | import { Home } from 'lucide-react'; 26 | export default function Page({ data }) 27 | { 28 | return ( 29 |
30 | 31 |

Hello {data}

32 |
33 | ); 34 | } 35 | 36 | export function getServerSideProps() { 37 | return { 38 | props: { data: "world" }, 39 | } 40 | } 41 | `; 42 | 43 | const disallowed = [ 44 | '```', 45 | '```jsx', 46 | '```js' 47 | ]; 48 | 49 | const removeDisallowedLines = (input: string) => { 50 | return input 51 | .split('\n') 52 | .filter(line => !disallowed.some(disallowedLine => line.trim().startsWith(disallowedLine))) 53 | .join('\n'); 54 | }; 55 | 56 | const formatResponse = (input: string) => { 57 | return removeDisallowedLines(input); 58 | }; 59 | 60 | type EditorChatProps = { 61 | setCode: (code: string | undefined) => void; 62 | code: string; 63 | }; 64 | 65 | const initialMessages = [ 66 | { id: 'code', role: 'system' as const, content: basePrompt } 67 | ]; 68 | 69 | export const EditorChat: FC = ({ code, setCode }) => { 70 | const { messages, setMessages, handleSubmit, setInput, input, isLoading } = useChat({ initialMessages }); 71 | 72 | const [codeFinished, setCodeFinished] = useState(false); 73 | const chatHistoryRef = useRef(null); 74 | const searchParams = useSearchParams(); 75 | const currentProject = searchParams.get('project'); 76 | 77 | const fetchAndSetChatHistory = async (projectId: string) => { 78 | const storedMessages = (await getChatMessages(projectId)) 79 | .map((message) => ({ id: message.id, content: message.content, role: message.role as any })); 80 | 81 | setMessages([...initialMessages, ...storedMessages]); 82 | }; 83 | 84 | useEffect(() => { 85 | if (chatHistoryRef.current) { 86 | chatHistoryRef.current.scrollTop = chatHistoryRef.current.scrollHeight; 87 | } 88 | }, [messages]); 89 | 90 | useEffect(() => { 91 | if (!currentProject) return; 92 | fetchAndSetChatHistory(currentProject); 93 | 94 | // eslint-disable-next-line react-hooks/exhaustive-deps 95 | }, [currentProject]); 96 | 97 | useEffect(() => { 98 | if (codeFinished && currentProject) { 99 | const messagesToStore = messages.filter((message) => message.role !== 'system' && !!message.id); 100 | storeChatMessages(currentProject, messagesToStore); 101 | } 102 | 103 | // eslint-disable-next-line react-hooks/exhaustive-deps 104 | }, [messages, codeFinished]); 105 | 106 | useEffect(() => { 107 | setCodeFinished(false); 108 | const lastBotResponse = messages.filter((message) => message.role === 'assistant').pop(); 109 | setCode(formatResponse(lastBotResponse?.content ?? '')); 110 | // eslint-disable-next-line react-hooks/exhaustive-deps 111 | }, [messages]); 112 | 113 | useEffect(() => { 114 | if (!codeFinished && !isLoading) { 115 | setCodeFinished(true); 116 | } 117 | // eslint-disable-next-line react-hooks/exhaustive-deps 118 | }, [isLoading]); 119 | 120 | return ( 121 |
123 |
124 | 125 | 126 |
127 |
128 | 129 |
130 |
131 |
132 |

Chat History

133 |
134 | {messages.filter((message) => message.role === 'user').map((message) => ( 135 |
139 |

{message.content}

140 |
141 | ))} 142 |
143 |
144 |
145 |
146 | setInput(e.target.value)} /> 150 | 155 |
156 |
157 |
158 |
159 | ); 160 | }; 161 | -------------------------------------------------------------------------------- /src/components/EditorSection.tsx: -------------------------------------------------------------------------------- 1 | import { FC } from 'react'; 2 | import { Editor } from '@monaco-editor/react'; 3 | 4 | type EditorSectionProps = { 5 | code: string; 6 | onChange: (code: string | undefined) => void; 7 | } 8 | 9 | export const EditorSection: FC = ({ code, onChange }) => { 10 | return ( 11 | <> 12 |

Code Editor

13 |
14 | 27 |
28 | 29 | ); 30 | }; 31 | -------------------------------------------------------------------------------- /src/components/Navbar.tsx: -------------------------------------------------------------------------------- 1 | 'use client' 2 | import { useEffect } from "react"; 3 | import { useRouter, useSearchParams } from 'next/navigation'; 4 | import { PlusIcon } from '@/components/icons/PlusIcon'; 5 | import useLocalStorage from '@/hooks/useLocalStorage'; 6 | import { storeProject } from '@/actions/chat'; 7 | import { v4 as uuidv4 } from 'uuid'; 8 | import { Button } from "./ui/button"; 9 | 10 | export type Project = { 11 | id: string; 12 | }; 13 | 14 | export default function NavbarComponent() { 15 | 16 | const searchParams = useSearchParams(); 17 | const currentProject = searchParams.get('project'); 18 | const router = useRouter(); 19 | const [projects, setProjects] = useLocalStorage('projects', []); 20 | 21 | const createNewProject = async () => { 22 | const uuid = uuidv4(); 23 | await storeProject(uuid); 24 | setProjects([...projects ?? [], { id: uuid }]); 25 | router.push(`?project=${uuid}`); 26 | } 27 | 28 | useEffect(() => { 29 | if (projects?.length === 0) createNewProject(); 30 | 31 | // eslint-disable-next-line react-hooks/exhaustive-deps 32 | }, [projects?.length]); 33 | 34 | return ( 35 |
36 | 70 |
71 | ); 72 | 73 | 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/components/Preview.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | import { FC, useEffect, useRef } from 'react'; 3 | import { Sandpack, SandpackCodeEditor, SandpackConsole, SandpackLayout, SandpackPreview, SandpackProvider } from "@codesandbox/sandpack-react"; 4 | import { sandpackDark } from "@codesandbox/sandpack-themes"; 5 | import { 6 | ResizableHandle, 7 | ResizablePanel, 8 | ResizablePanelGroup, 9 | } from "@/components/ui/resizable"; 10 | import { ScrollArea } from './ui/scroll-area'; 11 | 12 | 13 | function prependUseClientIfNeeded(inputString: string): string { 14 | // Define the keywords to search for 15 | const keywords = ["useState", "useEffect", "useRef"]; 16 | 17 | // Check if any of the keywords exist in the input string 18 | const containsHook = keywords.some(keyword => inputString.includes(keyword)); 19 | 20 | // Prepend "use client"; to the string if any keyword is found 21 | if (containsHook) { 22 | return `"use client"; 23 | ${inputString}`; 24 | } 25 | 26 | // Return the original string if no keywords are found 27 | return inputString; 28 | } 29 | 30 | export const Preview: FC<{ code: string | null }> = ({ code }) => { 31 | const rawCode = prependUseClientIfNeeded(code|| ""); 32 | console.log(`inserted the following: ${rawCode}`); 33 | const iframe = useRef(null); 34 | 35 | const files = { 36 | //code 37 | "pages/index.js": rawCode.length > 5 ? rawCode : `import { Home } from 'lucide-react'; 38 | export default function Page({ data }) 39 | { 40 | return ( 41 |
42 | 43 |

Welcome to Nextjs Page Generator

44 |

{data}

45 |
46 |

Example prompts

47 |

Copy and paste an example below

48 |
    49 |
  • Create a connect 4 game for two players. Show alert when game is won.
  • 50 |
  • Create a single page app with a title and get started button. Get started button should launch modal, a form that asks for a github repo. Use axios to fetch repo contents. On submit, it will fetch and display the repo file structure. Allow user to click and drill into file contents.
  • 51 |
  • Create a sodoku board game, make it take up the screen size. Allow user to edit empty cells. Validate rows/columns and add a hint button that shows an answer each time.
  • 52 |
53 |
54 |
55 | ); 56 | } 57 | 58 | export function getServerSideProps() { 59 | return { 60 | props: { data: "Use the AI chat assistant to generate your Nextjs page using Tailwindcss" }, 61 | } 62 | }`, 63 | // styles.css 64 | "styles.css": `/* purgecss start ignore */ 65 | @tailwind base; 66 | /* purgecss end ignore */ 67 | @tailwind components; 68 | @tailwind utilities; 69 | `, 70 | // tailwind.config.js 71 | "tailwind.config.js": `/** @type {import('tailwindcss').Config} */ 72 | module.exports = { 73 | content: [ 74 | "./app/**/*.{js,ts,jsx,tsx}", 75 | "./pages/**/*.{js,ts,jsx,tsx}", 76 | "./components/**/*.{js,ts,jsx,tsx}", 77 | 78 | // Or if using 'src' directory: 79 | "./src/**/*.{js,ts,jsx,tsx}" 80 | ], 81 | theme: { 82 | extend: {} 83 | }, 84 | plugins: [] 85 | }`, 86 | // postcss.config.js 87 | "postcss.config.js": `module.exports = { 88 | plugins: { 89 | tailwindcss: {}, 90 | autoprefixer: {}, 91 | }, 92 | }`, 93 | }; 94 | const customSetup = { 95 | dependencies: { 96 | "react": "latest", 97 | "react-dom": "latest", 98 | "tailwindcss": "latest", 99 | "postcss-easy-import": "latest", 100 | "autoprefixer": "latest", 101 | "postcss": "latest", 102 | "axios": "latest", 103 | "lucide-react": "latest", 104 | "openai": "latest", 105 | "ai": "latest", 106 | "react-modal": "latest" 107 | } 108 | }; 109 | 110 | useEffect(() => { 111 | if (!iframe.current) return; 112 | }, [code]); 113 | 114 | return ( 115 |
116 |

Preview Sandbox

117 | {/*