You are an expert AI software architect and senior full-stack developer tasked with creating a single-page application (SPA) for a visual Terminal UI (TUI) design tool. This application should provide a user-friendly, Figma-like experience for designing TUI interfaces and exporting code for various TUI frameworks. The goal is to empower developers and even non-technical users to create professional-looking terminal applications without extensive coding knowledge.
## 1. PROJECT OVERVIEW
**Project Name:** TUI Studio
**Objective:** To create a visual, drag-and-drop interface for designing Terminal User Interfaces (TUIs) and exporting production-ready code for popular TUI frameworks. It aims to significantly speed up the development process for terminal applications and make TUI design accessible to a wider audience.
**Problem Solved:** Designing TUIs traditionally involves writing code directly, which is time-consuming, error-prone, and requires deep knowledge of specific TUI libraries. This tool democratizes TUI design by providing a visual editor, akin to Figma for web design, enabling users to see their designs in real-time and export code with a single click.
**Value Proposition:** Design terminal UIs visually, iterate faster, and generate code for multiple frameworks instantly. Reduce development time, improve UI consistency, and lower the barrier to entry for TUI development.
## 2. TECH STACK
* **Frontend Framework:** React (using functional components and Hooks)
* **UI Library/Framework:** Tailwind CSS for rapid and utility-first styling.
* **State Management:** Zustand for lightweight and efficient global state management. For complex local component state, React's `useState` and `useReducer` will be used.
* **Canvas Rendering:** Potentially use a library like `react-konva` or a custom SVG/HTML canvas implementation if complex interactions and rendering optimizations are needed. For simpler drag-and-drop, `react-dnd` can be integrated.
* **Code Generation:** Custom logic to transform the design state into framework-specific code (e.g., Ink, Textual).
* **Routing (if needed for future expansion, not for initial SPA):** React Router DOM
* **Build Tool:** Vite for fast development server and optimized builds.
* **Icons:** Heroicons or Lucide React for clean, accessible icons.
## 3. CORE FEATURES & USER FLOWS
**A. Visual Canvas & Drag-and-Drop Interface:**
* **User Flow:**
1. User lands on the main design page.
2. A central canvas area displays the TUI layout.
3. A component toolbar (left side) shows available TUI components (e.g., Box, Text, Button, Input, Table).
4. User drags a component (e.g., 'Box') from the toolbar onto the canvas.
5. The component appears on the canvas with default dimensions and properties.
6. User can resize, reposition, and modify component properties using a properties panel (right side).
7. The canvas provides a live ANSI preview, simulating how the TUI will look in a terminal.
8. Users can zoom in/out of the canvas.
* **Details:** Implement drag-and-drop using `react-dnd`. The canvas should render components efficiently. Real-time preview is crucial.
**B. 20+ TUI Components:**
* **User Flow:**
1. User selects a component from the toolbar or canvas.
2. The properties panel updates to show specific properties for that component (e.g., 'Text' component shows `value`, `color`; 'Button' component shows `label`, `onClick` placeholder).
3. User modifies properties (e.g., changes text content, button label, color). Changes reflect instantly on the canvas.
* **Components to Implement (MVP):** Screen, Box, Text, Button, TextInput, Table, List, Tree, Tabs, Modal, Spinner, ProgressBar.
* **Details:** Each component needs a corresponding data structure and a set of editable properties. Map these properties to the visual representation on the canvas and the eventual code output.
**C. Layout Engine (Absolute, Flexbox, Grid):**
* **User Flow:**
1. User selects a container component (e.g., 'Box' acting as a container).
2. In the properties panel, the user can switch the layout mode between 'Absolute', 'Flex', and 'Grid'.
3. When 'Flex' or 'Grid' is selected, relevant properties (e.g., `flexDirection`, `justifyContent`, `alignItems`, `gridCols`, `gap`) appear.
4. User adjusts these properties, and the child components within the container rearrange accordingly on the canvas.
* **Details:** This mimics CSS Box Model and Flexbox/Grid. The underlying rendering engine must handle these layout calculations accurately.
**D. 8 Color Themes:**
* **User Flow:**
1. User accesses a theme switcher (e.g., in the header or settings).
2. User selects a theme (e.g., 'Dracula', 'Nord', 'Solarized').
3. The canvas and all components instantly update to reflect the selected theme's color palette.
* **Themes to Support (MVP):** Dracula, Nord, Solarized, Monokai, Gruvbox, Tokyo Night, Nightfox, Sonokai.
* **Details:** Define color palettes for each theme. Use CSS variables or a theming context in React to apply themes dynamically.
**E. Multi-Framework Export:**
* **User Flow:**
1. User clicks an 'Export' button.
2. A modal or dropdown appears, allowing the user to select the target framework (e.g., 'Ink', 'Textual').
3. User selects a framework.
4. The application generates and displays/downloads the corresponding code (e.g., a `.js` or `.tsx` file for Ink, a `.py` file for Textual).
* **Frameworks to Support (MVP):** Ink (TypeScript/JavaScript), Textual (Python).
* **Details:** This requires mapping the design's component structure and properties to the syntax and conventions of each target framework. Implement a robust code generation engine. Initially, this feature might be in Alpha with a clear notice.
**F. Save/Load Projects:**
* **User Flow:**
1. User clicks 'Save'.
2. The current design state is converted into a JSON object.
3. This JSON is saved, likely using browser's Local Storage for MVP, or downloaded as a `.tui` file.
4. User clicks 'Load', selects a previously saved `.tui` file or loads from Local Storage.
5. The application parses the JSON and reconstructs the design on the canvas.
* **Details:** Define a clear JSON schema for the project state. Ensure efficient serialization and deserialization.
## 4. UI/UX DESIGN
* **Layout:** Single Page Application (SPA) layout. A three-column structure is recommended:
* **Left Sidebar:** Component Toolbar (Icons + Names).
* **Center:** Main Canvas (visual editor).
* **Right Sidebar:** Properties Panel (contextual, shows properties for selected element).
* **Top Header:** Project Name, Save/Load buttons, Export button, Theme Switcher, Zoom controls, Command Palette access.
* **Color Palette:** Default to a neutral, developer-friendly palette (e.g., dark background, light text, subtle accent colors). Ensure contrast ratios meet accessibility standards. Allow easy switching to the 8 TUI themes.
* **Typography:** Use a clean, readable monospace font for the canvas preview (to mimic terminal) and a sans-serif font for the UI controls. Ensure consistent font sizes and weights.
* **Responsive Design:** While the primary design space is the canvas, the UI controls (sidebars, header) must be responsive. Consider a collapsed sidebar mode for smaller screens or a mobile-first approach if a mobile app version is ever considered.
* **Interactions:** Smooth drag-and-drop, intuitive property editing (sliders, color pickers, text inputs), clear visual feedback on hover and selection.
## 5. DATA MODEL & STATE MANAGEMENT
* **State Structure:** Use Zustand for global state.
* `designState`: { `canvasWidth`, `canvasHeight`, `elements`: [ { `id`, `type`, `x`, `y`, `width`, `height`, `layoutMode`?, `styles` { `color`, `bgColor`, `border`?, ... }, `properties` { `text`, `label`, `options`?, ... }, `children`? (for containers) } ] }
* `selectedElementId`: string | null
* `currentTheme`: string (e.g., 'dracula')
* `exportFramework`: string (e.g., 'ink')
* `uiState`: { `showPropertiesPanel`, `showComponentToolbar`, ... }
* **Local State:** Use `useState` within components for managing transient UI states like input field values before commit.
* **Data Persistence:** Utilize `localStorage` for saving/loading projects in the MVP. The data will be a JSON representation of `designState`.
## 6. COMPONENT BREAKDOWN
* **`App.jsx`:** Main application component, sets up layout, state provider.
* **`Header.jsx`:** Contains project actions (Save, Load, Export), theme switcher, zoom controls. Receives props for theme, project name, action handlers.
* **`Sidebar.jsx`:** Container for `ComponentToolbar` and `PropertiesPanel`. Manages visibility.
* **`ComponentToolbar.jsx`:** Displays available TUI components. Handles drag start events. Receives `components` list and `onDragStart` prop.
* **`Canvas.jsx`:** The main drawing area. Renders selected theme. Uses `react-dnd` for dropping components. Renders `RenderedElement` for each element in `designState.elements`. Handles canvas-level interactions (zoom, pan). Receives `elements`, `selectedElementId`, `theme`, `onSelectElement`, `onDropElement`.
* **`RenderedElement.jsx`:** Renders a single TUI element based on its type and properties. Handles selection. Displays children if it's a container. Receives `element` data, `isSelected`, `theme`, `onClick`, `onDrag`. Uses specific components like `BoxRenderer`, `TextRenderer`, etc.
* **`PropertiesPanel.jsx`:** Displays input fields/controls for the properties of the `selectedElementId`. Dynamically renders controls based on element type. Receives `selectedElement`, `onUpdateElement`, `theme`.
* **`ExportModal.jsx`:** Pops up when 'Export' is clicked. Allows framework selection and displays generated code. Receives `isOpen`, `designState`, `onClose`, `onSubmit`.
* **`ThemeSelector.jsx`:** Part of `Header` or standalone. Displays theme options and handles theme change. Receives `currentTheme`, `onThemeChange`.
* **`ComponentConfigurator` (Internal to `PropertiesPanel`):** A component that maps element types to specific property editing forms (e.g., `TextInputConfig`, `ButtonConfig`).
## 7. ANIMATIONS & INTERACTIONS
* **Drag and Drop:** Smooth visual feedback during drag (ghost image, outline). Snap-to-grid or alignment guides.
* **Hover Effects:** Subtle highlight or border change when hovering over elements on the canvas or in the toolbar.
* **Selection:** Clear visual indicator for the selected element on the canvas (e.g., bounding box with handles, distinct border).
* **Transitions:** Smooth transitions when properties change (e.g., color fades, size adjustments). Use CSS transitions or React transition libraries.
* **Loading States:** Show spinners or placeholder states when loading projects or generating code.
* **Micro-interactions:** Subtle animations on button clicks, toggles, or input focus.
* **Export Modal:** Fade-in/slide-in animation for the modal.
## 8. EDGE CASES & ACCESSIBILITY
* **Empty State:** Canvas should show helpful tips or a prompt to add the first component when empty.
* **No Selected Element:** Properties panel should display canvas-level settings or a general prompt.
* **Error Handling:** Gracefully handle errors during code generation, file loading/saving. Display user-friendly error messages.
* **Validation:** Validate property inputs (e.g., ensure color codes are valid, numbers are within reasonable ranges). Provide inline validation feedback.
* **Accessibility (a11y):** Use semantic HTML where possible. Ensure keyboard navigation for controls (toolbars, properties panel). Use ARIA attributes for custom components and interactions. Ensure sufficient color contrast.
* **Large Designs:** Optimize rendering for canvases with many elements. Consider virtualized rendering for the canvas.
* **Framework Specifics:** Handle potential differences in how layouts or components are represented in different frameworks.
## 9. SAMPLE DATA
**A. Component Definitions (Conceptual JSON):**
```json
{
"id": "comp-123",
"type": "Box",
"x": 50,
"y": 50,
"width": 300,
"height": 150,
"styles": {
"backgroundColor": "#334155", // Tailwind gray-800
"border": "1px solid #cbd5e1" // Tailwind gray-300
},
"layoutMode": "flex",
"flexProps": {
"flexDirection": "column",
"justifyContent": "center",
"alignItems": "center"
},
"children": [ /* nested elements */ ]
}
```
```json
{
"id": "comp-456",
"type": "Text",
"x": 0,
"y": 10,
"width": "auto",
"height": "auto",
"styles": {
"color": "#f8fafc" // Tailwind slate-50
},
"properties": {
"value": "Hello, TUI World!"
}
}
```
```json
{
"id": "comp-789",
"type": "Button",
"x": 0,
"y": 50,
"width": 150,
"height": 40,
"styles": {
"backgroundColor": "#2563eb", // Tailwind blue-600
"color": "#ffffff"
},
"properties": {
"label": "Click Me"
}
}
```
**B. Project Save Data (JSON):**
```json
{
"version": "1.0",
"projectName": "My First TUI App",
"designState": {
"canvasWidth": 1024,
"canvasHeight": 768,
"elements": [
// ... array of component definition JSON objects
],
"currentTheme": "dracula"
}
}
```
**C. Framework Code Examples (Conceptual Snippets):**
* **Ink (TypeScript):**
```typescript
import { Box, Text, Button, useInput } from 'ink';
const App = () => (
<Box borderStyle="round" borderColor="gray" padding={1}>
<Box flexDirection="column" paddingLeft={2} paddingBottom={1}>
<Text color="cyan">Welcome to Ink!</Text>
<Box marginTop={1}>
<Text>This is a sample UI.</Text>
</Box>
<Button label="Press Me" onClick={() => console.log('Button clicked!')} />
</Box>
</Box>
);
export default App;
```
* **Textual (Python):**
```python
from textual.app import App, ComposeResult
from textual.widgets import Button, Header, Footer, Static
from textual.containers import Container
class TUIApp(App):
def compose(self) -> ComposeResult:
yield Header()
with Container():
yield Static("Welcome to Textual!")
yield Button("Click Me", id="my-button")
yield Footer()
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "my-button":
self.bell()
if __name__ == "__main__":
app = TUIApp()
app.run()
```
## 10. DEPLOYMENT NOTES
* **Build:** Use Vite's build command (`npm run build` or `yarn build`). Configure `base` path if deploying to a subdirectory.
* **Environment Variables:** Use `.env` files for configuration. Potentially use `VITE_API_URL` if integrating with a backend later.
* **Hosting:** Static hosting platforms like Vercel, Netlify, GitHub Pages are suitable for the SPA.
* **Performance:** Optimize image assets (if any). Code-split components for faster initial load. Use memoization (`React.memo`) where appropriate. Ensure efficient state updates to avoid unnecessary re-renders.
* **Error Boundary:** Implement React Error Boundaries to catch rendering errors gracefully and display a fallback UI.
* **PWA (Optional):** Consider making it a Progressive Web App for offline capabilities and easier installation.