Skip to content

shubhamV123/code-playground

Repository files navigation

Code Playground

A full-featured browser-based code playground for React applications, built with React, TypeScript, and modern web technologies. Write, bundle, and preview React code entirely in your browser!

✨ Features

🎨 Template System

  • Multiple Project Templates:
    • Plain React - Lightweight React starter with modern gradient UI
    • Material UI - Full MUI setup with comprehensive component examples
  • One-Click Switching: Switch between templates with confirmation dialog
  • Template Persistence: Active template and files saved in state

πŸ“ Advanced File System

  • Hierarchical File Tree: Nested folders and files with expand/collapse
  • Inline Operations: Hover over any folder to show action buttons:
    • Create new files and folders at any level
    • Rename files and folders inline
    • Delete files and folders with confirmation
  • Smart Icons: File type detection with colored icons (.js, .jsx, .ts, .tsx, .html, .css, .json)
  • Visual Feedback: Active file highlighting and hover states

πŸ’» Modern Code Editor

  • CodeMirror 6 Integration: Lightning-fast, extensible code editor
  • Language Support: JavaScript, JSX, TypeScript, TSX, HTML, CSS, JSON
  • Auto-save: Changes automatically saved to state
  • Dark Theme: OneDark color scheme optimized for long coding sessions

πŸš€ Live Preview

  • Real-time Bundling: ESBuild-powered bundling in the browser
  • React Rendering: Full React 18 support with JSX transformation
  • Iframe Isolation: Sandboxed preview with clean error handling
  • Auto-refresh: Smooth transitions when code changes
  • Console Integration: Captured console.log, error, warn, and info messages

πŸ“¦ Package Management

  • Restricted Public Demo Mode: Public deployments only expose a curated dependency list
  • Local Open NPM Mode: Clone the repo and enable VITE_ENABLE_OPEN_NPM=true to search and install arbitrary npm packages locally
  • Smart Dependency Resolution: Automatic peer dependency detection
  • Version Selection: Choose specific package versions
  • Visual Dependencies Panel: See installed packages with versions
  • One-Click Install/Uninstall: Easy package management

🎯 Advanced Bundling

  • Dual Resolver System:
    • Base Resolver: Standard React packages
    • MUI Resolver: Material UI with external React handling
  • Import Map Generation: Dynamic ESM import maps via esm.sh
  • Peer Dependency Handling: Automatic resolution of peer dependencies
  • Virtual File System: In-memory file resolution for imports

πŸŽ›οΈ Flexible Layout

  • Resizable Panels: Four-panel layout with drag-to-resize:
    • File tree (vertical split with dependencies)
    • Dependencies panel (resizable height)
    • Code editor
    • Live preview with console
  • Responsive Design: Clean, VS Code-inspired dark UI
  • Collapsible Sections: Toggle dependencies and console visibility

πŸ› οΈ Tech Stack

Frontend

  • React 18 - UI library with hooks
  • TypeScript - Type safety and better DX
  • Vite - Lightning-fast build tool and dev server
  • Tailwind CSS - Utility-first styling

State Management

  • Zustand - Lightweight state management for file system and packages

Code Editor

  • CodeMirror 6 - Extensible code editor
  • @codemirror/lang-javascript - JavaScript/JSX syntax
  • @codemirror/theme-one-dark - Dark theme

Bundling & Execution

  • esbuild-wasm - WebAssembly-based bundler
  • esm.sh - CDN for ES modules with import maps
  • Virtual FS Plugin - In-memory file resolution

UI Components

  • react-resizable-panels - Draggable panel layout
  • react-icons - VS Code and file type icons
  • Material UI (optional) - Template with full MUI setup

Package Management

  • NPM Registry API - Package search and metadata
  • Custom Dependency Resolver - Smart peer dependency detection

πŸš€ Getting Started

# Install dependencies
npm install

# Start development server
npm run dev

# Enable full npm search/install for local experiments
echo "VITE_ENABLE_OPEN_NPM=true" > .env.local
npm run dev

# Build for production
npm run build

The application will be available at http://localhost:5173

πŸ”’ Public Demo Safety

The hosted demo is intentionally restricted. It is meant to show the artifact runtime, editor, templates, browser bundling, and sandboxed preview without letting the public subdomain become a general-purpose npm execution surface.

By default, the public app:

  • Searches only a curated package list used by the built-in demos.
  • Blocks non-curated package names even if someone edits package.json manually.
  • Caps dependency count and install batch size.
  • Runs previews in a sandboxed iframe without same-origin, form submission, or popup escape permissions.
  • Ships Netlify/Vercel security headers, including CSP, frame blocking, MIME sniffing protection, referrer policy, and restricted browser permissions.

For unrestricted package experiments, clone the repo and set:

VITE_ENABLE_OPEN_NPM=true

πŸ“‚ Project Structure

code-playground/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”œβ”€β”€ FileTree.tsx          # File tree with hover actions
β”‚   β”‚   β”œβ”€β”€ FileToolbar.tsx       # Top toolbar with file operations
β”‚   β”‚   β”œβ”€β”€ CodeEditor.tsx        # CodeMirror 6 editor wrapper
β”‚   β”‚   β”œβ”€β”€ Preview.tsx           # Live preview with iframe
β”‚   β”‚   β”œβ”€β”€ Console.tsx           # Console output panel
β”‚   β”‚   β”œβ”€β”€ PackageManager.tsx    # NPM package search & install
β”‚   β”‚   └── TemplateModal.tsx     # Template selection dialog
β”‚   β”œβ”€β”€ store/
β”‚   β”‚   └── fileSystemStore.ts    # Zustand store (files, packages, templates)
β”‚   β”œβ”€β”€ types/
β”‚   β”‚   └── fileSystem.ts         # TypeScript type definitions
β”‚   β”œβ”€β”€ utils/
β”‚   β”‚   β”œβ”€β”€ bundler.ts            # ESBuild bundler with plugins
β”‚   β”‚   β”œβ”€β”€ npmApi.ts             # NPM registry API wrapper
β”‚   β”‚   β”œβ”€β”€ dependencyResolver.ts # Peer dependency resolver
β”‚   β”‚   β”œβ”€β”€ templates/            # Project templates
β”‚   β”‚   β”‚   β”œβ”€β”€ index.ts          # Template exports
β”‚   β”‚   β”‚   β”œβ”€β”€ types.ts          # Template types
β”‚   β”‚   β”‚   β”œβ”€β”€ defaultTemplate.ts # Plain React template
β”‚   β”‚   β”‚   └── muiTemplate.ts    # Material UI template
β”‚   β”‚   └── resolvers/            # Dependency resolvers
β”‚   β”‚       β”œβ”€β”€ index.ts          # Resolver factory
β”‚   β”‚       β”œβ”€β”€ baseResolver.ts   # Standard React resolver
β”‚   β”‚       └── muiResolver.ts    # MUI with external handling
β”‚   β”œβ”€β”€ App.tsx                   # Main app with layout
β”‚   β”œβ”€β”€ main.tsx                  # Entry point
β”‚   └── index.css                 # Global styles
β”œβ”€β”€ public/
β”‚   └── esbuild.wasm             # ESBuild WebAssembly binary
β”œβ”€β”€ index.html
β”œβ”€β”€ package.json
β”œβ”€β”€ tailwind.config.js
β”œβ”€β”€ tsconfig.json
└── vite.config.ts

πŸ“– Usage

Choosing a Template

  1. Click the Templates button (layers icon) in the top toolbar
  2. Select from available templates:
    • Plain React: Lightweight starter with gradient UI
    • Material UI: Full MUI setup with component examples
  3. Confirm to replace all files (warning: this clears current work)

Creating Files & Folders

From Toolbar:

  1. Click "New File" or "New Folder" in the top toolbar
  2. Enter name and press Enter (or click Create)

From File Tree (Hover Actions):

  1. Hover over any folder in the tree
  2. Click the folder/file icon that appears
  3. Type name inline and press Enter
  4. Press Escape to cancel

Editing Files

  1. Click any file in the tree to open it
  2. Start typing in the editor
  3. Changes auto-save to state
  4. Preview updates automatically

Renaming & Deleting

Hover over any folder:

  • πŸ“„ New File button
  • πŸ“ New Folder button
  • ✏️ Rename button (folders only)
  • πŸ—‘οΈ Delete button

Hover over any file:

  • πŸ—‘οΈ Delete button

Installing Packages

  1. Click the Dependencies button to expand the panel
  2. Search for packages in the search box
  3. Click Add on any package
  4. Select version and click Install
  5. Package and dependencies auto-install
  6. View installed packages in the list
  7. Hover and click trash icon to uninstall

Using Installed Packages

// Just import them in your code
import { Button } from "@mui/material";
import axios from "axios";

// They'll be automatically resolved via esm.sh

Viewing Console Output

  • Console logs appear automatically in the bottom panel
  • Color-coded: errors (red), warnings (yellow), info (blue), logs (white)
  • Click "Clear" to clear console output
  • Toggle with chevron icon to expand/collapse

πŸ—οΈ Architecture

Bundling Flow

  1. File Changes β†’ Zustand store updates
  2. Bundler Triggered β†’ ESBuild compiles JSX/TSX to JS
  3. Dependency Resolution β†’ Appropriate resolver detects package type
  4. Import Map Generation β†’ Creates ESM import map for esm.sh
  5. Code Injection β†’ Bundles with React runtime and user code
  6. Iframe Render β†’ Sandboxed execution with console capture

Resolver Strategy

The app automatically selects the right resolver based on installed packages:

Base Resolver (default):

  • Standard React packages
  • Uses https://esm.sh/package@version format

MUI Resolver (when MUI detected):

  • Adds ?external=react,react-dom to prevent multiple React instances
  • Handles @emotion/* packages properly
  • Adds JSX runtime for Emotion

Virtual File System

  • In-memory file structure stored in Zustand
  • ESBuild plugin resolves imports from virtual FS
  • Supports relative imports: import './Component'
  • Package imports resolved via import maps

βœ… Features Checklist

  • βœ… Hierarchical file system with CRUD operations
  • βœ… Nested folders with hover actions
  • βœ… CodeMirror 6 code editor with syntax highlighting
  • βœ… Resizable panels (horizontal & vertical)
  • βœ… File type icons
  • βœ… Auto-save functionality
  • βœ… TypeScript/JSX/TSX support
  • βœ… Dark theme UI
  • βœ… Live preview with iframe isolation
  • βœ… Console output capture
  • βœ… React 18 execution with JSX
  • βœ… ESM package imports via esm.sh
  • βœ… NPM package search and install
  • βœ… Automatic peer dependency resolution
  • βœ… Multiple project templates
  • βœ… Material UI support with proper external handling
  • βœ… Template switching with state reset

🎯 Future Enhancements

  • TypeScript type checking in editor
  • Multiple file upload/import
  • Export project as ZIP
  • Share playground via URL
  • Dark/Light theme toggle
  • More templates (Vue, Svelte, Solid)
  • Code formatting (Prettier)
  • Cloud save/load projects

πŸ› Troubleshooting

Preview not updating

  • Check browser console for errors
  • Ensure all imports are installed in Dependencies panel
  • Try clearing console and refreshing

Package installation fails

  • Verify package name is correct on npm
  • Check if package has peer dependencies that conflict
  • Some packages may not work in browser environment

Material UI styles not working

  • Ensure you're using the Material UI template
  • Check that @emotion/react and @emotion/styled are installed
  • The app uses the MUI resolver automatically when MUI is detected

TypeScript errors

  • The editor shows syntax highlighting but doesn't do type checking yet
  • TypeScript/TSX files are transpiled to JavaScript for execution
  • Type errors won't prevent code from running

πŸ’‘ Tips

  • Use Cmd/Ctrl + S - Auto-saves, but manual save triggers re-bundle
  • Hover over folders to reveal quick actions
  • Drag panel borders to resize sections
  • Check console output for runtime errors
  • Install packages before importing them
  • Templates come with working examples to start from

🀝 Contributing

Contributions are welcome! Feel free to open issues or submit PRs.

About

Code playground

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages