You are an expert AI assistant specializing in full-stack development and UI/UX design. Your task is to generate a complete, single-page React application based on the provided concept and requirements. The application should be a Single Page Application (SPA) and allow developers to interact with the Abstract Syntax Tree (AST) of their code.
**1. PROJECT OVERVIEW:**
The application, tentatively named 'AST Weaver', is a SaaS platform designed to revolutionize code editing. It addresses the inefficiency and cognitive load associated with traditional code editors by enabling direct manipulation of a code's Abstract Syntax Tree (AST). This allows developers to perform complex edits, refactoring, and parallel operations with unprecedented speed and precision. The core value proposition lies in bridging the gap between coding intent and action, empowering developers to "weave" their code by manipulating its fundamental structure.
**2. TECH STACK:**
- **Frontend Framework:** React (using Vite for a fast development experience)
- **Styling:** Tailwind CSS (for rapid UI development and utility-first styling)
- **State Management:** Zustand (lightweight, performant, and easy to integrate)
- **AST Parsing:** Libraries like `esprima`, `acorn`, or language-specific parsers depending on the initial language support (e.g., `typescript` for TS/JS).
- **Graph Visualization (Optional but Recommended):** `react-flow` or `vis-network` for AST visualization.
- **Monaco Editor (Optional):** For code input/display if not using a simple textarea.
- **React Router:** For potential future routing needs (though for SPA, can be minimal).
- **Utility Libraries:** Lodash (for utility functions), Axios (for potential API calls later).
**3. CORE FEATURES:**
- **Code Input and AST Display:**
- **User Flow:** A primary input area (e.g., a Monaco Editor instance or a styled `textarea`) where the user pastes or writes code. Upon input, the code is parsed, and its corresponding AST is displayed in a hierarchical, interactive tree structure in a separate panel.
- **Details:** Support for at least one major language initially (e.g., JavaScript). Real-time parsing and AST updates as the user types. The AST panel should be collapsible/resizable.
- **Multiple Cursors/Selections:**
- **User Flow:** Users can add multiple cursors or selections within the code editor. These cursors allow for simultaneous editing or selection operations across different parts of the code. In the AST view, corresponding nodes should be highlighted or selectable in parallel.
- **Details:** Implementing multi-cursor functionality similar to advanced editors. Selections should also correspond to AST nodes. Actions performed via multiple cursors (e.g., typing, deleting) should trigger AST updates.
- **AST Node Manipulation:**
- **User Flow:** Users can directly interact with nodes in the AST visualization. This includes selecting nodes, and performing actions like 'copy', 'paste', 'delete', 'move up/down', 'rename' (for relevant nodes like variables, functions). These actions directly modify the underlying code.
- **Details:** Context menus on AST nodes to perform actions. Drag-and-drop functionality within the AST tree to reorder elements (e.g., function order in a file). The changes must reflect in the code editor and vice-versa.
- **Standardized Selection Modes:**
- **User Flow:** Users can activate different selection modes (e.g., 'Word', 'Line', 'Syntax Node'). Selecting text in the editor automatically selects the corresponding AST node(s) based on the active mode. Similarly, selecting an AST node highlights the corresponding code.
- **Details:** A UI toggle or command palette to switch between selection modes. The 'Syntax Node' mode is the default and most powerful, allowing selection of entire AST elements (e.g., an `IfStatement`, a `FunctionDeclaration`).
**4. UI/UX DESIGN:**
- **Layout:** A two-column layout is recommended for the MVP. The left column contains the code editor (e.g., Monaco Editor). The right column contains the AST visualization tree. Both columns should have resizable panels. A top bar for file management (load/save - future feature), language selection, and mode toggles. A bottom status bar for line/column numbers, parsing status, and error messages.
- **Color Palette:** A dark theme suitable for developers. Primary colors: Dark grey/black background (`#1a1a1a`), White/Light grey text (`#ffffff`, `#cccccc`), Accent color (e.g., a vibrant blue or green like `#007bff` or `#4caf50`) for selections, active states, and interactive elements. Secondary colors for nodes: Different shades of grey, blues, and purples for different AST node types.
- **Typography:** A clean, monospace font for code (e.g., 'Fira Code', 'JetBrains Mono'). A readable sans-serif font for UI elements (e.g., 'Inter', 'Roboto'). Font sizes should be adjustable.
- **Responsive Design:** While primarily a desktop tool, the layout should adapt gracefully to different screen sizes. On smaller screens, panels might stack vertically or become collapsible overlays.
- **Interactivity:** AST nodes should have hover effects indicating they are interactive. Clicks should provide visual feedback. Loading states should be clear.
**5. DATA MODEL:**
- **State Management (Zustand):**
- `code`: string - The current code in the editor.
- `ast`: object | null - The parsed AST object.
- `selectedNodes`: string[] - Array of IDs or paths of currently selected AST nodes.
- `cursors`: Array<{ line: number, column: number }> - Positions of multiple cursors.
- `selectionMode`: 'word' | 'line' | 'node' - Current selection mode.
- `parseError`: string | null - Any parsing error message.
- `isLoading`: boolean - Indicates if parsing or an operation is in progress.
- **AST Structure:** Will depend on the parser used (e.g., ESTree specification for JavaScript). Each node has a `type`, `loc` (location), and potentially other properties based on its type.
- **Mock Data Format:** Sample AST JSON structure (e.g., for `function add(a, b) { return a + b; }`):
```json
{
"type": "Program",
"body": [
{
"type": "FunctionDeclaration",
"id": {"type": "Identifier", "name": "add"},
"params": [
{"type": "Identifier", "name": "a"},
{"type": "Identifier", "name": "b"}
],
"body": {
"type": "BlockStatement",
"body": [
{
"type": "ReturnStatement",
"argument": {
"type": "BinaryExpression",
"operator": "+",
"left": {"type": "Identifier", "name": "a"},
"right": {"type": "Identifier", "name": "b"}
}
}
]
}
}
]
}
```
**6. COMPONENT BREAKDOWN:**
- **`App.tsx`:** Main application component, sets up layout, initializes Zustand store.
- **`EditorPanel.tsx`:** Wrapper for the code editor (e.g., Monaco Editor). Handles code input, cursor management, and communicates changes to the store.
- Props: `code`, `onCodeChange`, `cursors`, `selectionMode`.
- **`AstPanel.tsx`:** Container for the AST visualization. Fetches AST from the store and renders the tree.
- Props: `ast`, `selectedNodes`, `onNodeSelect`.
- **`AstNode.tsx`:** Recursive component to render individual AST nodes in the tree. Handles expansion/collapse, selection highlighting, and context menus.
- Props: `node`, `isSelected`, `level`, `onNodeAction`.
- **`SelectionModeToggle.tsx`:** UI component to switch between different selection modes.
- Props: `currentMode`, `onModeChange`.
- **`StatusBar.tsx`:** Displays status information like line/column, errors, loading state.
- **`ContextMenu.tsx`:** Renders context menus for AST nodes.
**7. ANIMATIONS & INTERACTIONS:**
- **Hover Effects:** Subtle background color changes or slight scaling on AST nodes when hovered.
- **Transitions:** Smooth transitions for panel resizing, expanding/collapsing AST nodes, and loading states (e.g., fade-in/out).
- **Loading States:** A subtle animation (e.g., pulsing or shimmering) within the AST panel or a global loading indicator when parsing or performing heavy operations.
- **Micro-interactions:** Visual feedback when nodes are copied, pasted, or moved. Smooth scrolling between selected code and AST nodes.
**8. EDGE CASES:**
- **Empty Code:** Handle empty input gracefully. Display a placeholder message and an empty AST or a default program node.
- **Parse Errors:** Display clear error messages in the status bar and potentially highlight the problematic code section. Prevent interaction with an invalid AST.
- **Invalid AST Operations:** Prevent actions that would lead to syntactically incorrect code (e.g., deleting a required closing brace if not handled by the parser/formatter).
- **Large ASTs:** Implement virtualization or lazy loading for the AST tree to handle very large codebases without performance degradation.
- **Accessibility (a11y):** Ensure keyboard navigation is possible for all interactive elements. Use ARIA attributes appropriately. Ensure sufficient color contrast.
- **Undo/Redo:** Implement undo/redo functionality, likely leveraging the state management or a dedicated history stack.
**9. SAMPLE DATA:**
Here are a few sample AST snippets based on ESTree specification:
1. **Variable Declaration:** `let count = 0;`
```json
{
"type": "VariableDeclaration",
"kind": "let",
"declarations": [
{
"type": "VariableDeclarator",
"id": {"type": "Identifier", "name": "count"},
"init": {"type": "Literal", "value": 0, "raw": "0"}
}
]
}
```
2. **Arrow Function:** `const greet = (name) => console.log(name);`
```json
{
"type": "VariableDeclaration",
"kind": "const",
"declarations": [
{
"type": "VariableDeclarator",
"id": {"type": "Identifier", "name": "greet"},
"init": {
"type": "ArrowFunctionExpression",
"params": [{"type": "Identifier", "name": "name"}],
"body": {
"type": "CallExpression",
"callee": {
"type": "MemberExpression",
"object": {"type": "Identifier", "name": "console"},
"property": {"type": "Identifier", "name": "log"}
},
"arguments": [{"type": "Identifier", "name": "name"}]
}
}
}
]
}
```
3. **If Statement:** `if (x > 5) { y = 10; }`
```json
{
"type": "IfStatement",
"test": {
"type": "BinaryExpression",
"operator": ">",
"left": {"type": "Identifier", "name": "x"},
"right": {"type": "Literal", "value": 5, "raw": "5"}
},
"consequent": {
"type": "BlockStatement",
"body": [
{
"type": "ExpressionStatement",
"expression": {
"type": "AssignmentExpression",
"operator": "=",
"left": {"type": "Identifier", "name": "y"},
"right": {"type": "Literal", "value": 10, "raw": "10"}
}
}
]
},
"alternate": null
}
```
4. **Import Statement:** `import React from 'react';`
```json
{
"type": "ImportDeclaration",
"specifiers": [
{
"type": "ImportDefaultSpecifier",
"local": {"type": "Identifier", "name": "React"}
}
],
"source": {"type": "Literal", "value": "react", "raw": "'react'"}
}
```
5. **Class Declaration:** `class MyClass {}`
```json
{
"type": "ClassDeclaration",
"id": {"type": "Identifier", "name": "MyClass"},
"superClass": null,
"body": {"type": "ClassBody", "body": []}
}
```
**10. DEPLOYMENT NOTES:**
- **Build Tool:** Vite is recommended for its speed. Run `npm run build` (or `yarn build`).
- **Environment Variables:** Use `.env` files for configuration (e.g., API keys if external services are integrated later). Ensure sensitive variables are not committed to version control.
- **Performance Optimizations:**
- Code Splitting: Although an SPA, consider dynamic imports for heavier components (like the AST visualizer if it uses a large library).
- Memoization: Use `React.memo` and `useMemo`/`useCallback` to prevent unnecessary re-renders, especially in the `AstNode` component.
- Tree Virtualization: Crucial for the AST panel if dealing with large codebases. Libraries like `react-window` or `react-virtualized` can be integrated.
- **Hosting:** Can be deployed on static hosting platforms like Vercel, Netlify, or GitHub Pages.