You are an AI assistant tasked with generating a Single Page Application (SPA) for a novel concept called 'Geometri Hesaplama Aracı' (Geometric Calculation Tool). This application aims to bring the theoretical underpinnings of 'CasNum' – implementing arbitrary precision arithmetic using compass and straightedge constructions and integrating this with a functional, albeit simplified, Game Boy emulator where arithmetic logic unit (ALU) opcodes are realized through geometric constructions – into a user-friendly web interface. The goal is to make these complex theoretical concepts accessible and demonstrable. The application should be built as a responsive SPA using React and Tailwind CSS.
**1. PROJECT OVERVIEW**
* **Objective:** To create a web application that visually and functionally demonstrates arbitrary precision arithmetic through geometric constructions (compass and straightedge) and integrates this novel approach into a simplified Game Boy emulator. The application serves as an educational tool, a proof-of-concept for a unique computational paradigm, and a platform for exploring theoretical computer science and mathematics.
* **Problem Solved:** Traditional arbitrary precision arithmetic libraries are purely algorithmic. This project explores a radical, geometrically-based approach. The application makes this abstract concept tangible, allowing users to see how geometric principles can underpin arithmetic operations, and how this can even extend to simulating computational logic (like a Game Boy ALU).
* **Value Proposition:** Offers a unique, visually engaging way to understand fundamental mathematical and computational principles. It bridges theoretical geometry, advanced arithmetic, and retro computing emulation, providing a distinct educational and exploratory experience not found elsewhere.
**2. TECH STACK**
* **Frontend Framework:** React (using functional components and hooks)
* **Styling:** Tailwind CSS for utility-first styling and rapid UI development.
* **State Management:** React Context API for managing global state (e.g., current tool, selected points, calculation history) and `useState`/`useReducer` for local component state.
* **Routing (if needed for potential future expansion):** React Router DOM (though for an initial SPA, it might be minimal or unnecessary).
* **Graphics/Canvas:** HTML5 Canvas API for rendering geometric constructions and the emulator screen.
* **Build Tool:** Vite (for fast development server and optimized builds).
* **Language:** JavaScript (ES6+) / TypeScript (Recommended for robustness).
**3. CORE FEATURES & USER FLOWS**
* **A. Geometric Construction Canvas:**
* **Description:** The primary interactive area where users can perform geometric constructions. It starts with two predefined points (Origin: (0,0) and Unit: (1,0)). Users can select tools (Point, Line, Circle) to create new geometric entities.
* **Tools:**
* **Select/Move:** Allows dragging existing points.
* **Create Point (from intersections):** User clicks on two intersecting lines, a line and a circle, or two circles to define a new point.
* **Create Line:** User clicks on two existing points.
* **Create Circle:** User clicks on the center point and then another point to define the radius.
* **User Flow:** User selects a tool (e.g., 'Line'). Clicks on two existing points (e.g., Origin and Unit). A line is rendered. User selects 'Circle' tool. Clicks on Origin (center), then Unit (radius). A unit circle is rendered. User selects 'Intersection' tool. Clicks on the Line and the Circle. New intersection points are calculated and displayed.
* **Display:** Rendered points, lines, and circles on an HTML5 Canvas. Display coordinates of selected points. Highlight currently active tool and selected entities.
* **B. Arbitrary Precision Arithmetic Module:**
* **Description:** This module leverages the geometric constructions to perform arithmetic. For example, addition of two numbers `a` and `b` could be represented by constructing points on a number line, and `a+b` is found by translation. Multiplication might involve similar triangles or other geometric theorems.
* **User Flow:** User inputs two numbers (or selects geometrically constructed values). Selects an operation (Add, Subtract, Multiply, Divide). The application performs the operation using geometric principles (simulated or actual constructions if feasible within the canvas) and displays the result with arbitrary precision.
* **Interface:** Input fields for numbers, operation selection buttons, and a display area for the result. This could be integrated with the canvas, perhaps by constructing the numbers on the number line first.
* **C. Simplified Game Boy Emulator (ALU Focus):**
* **Description:** A highly simplified emulator focusing on the Arithmetic Logic Unit. Instead of standard binary operations, the ALU opcodes (e.g., ADD A, B) are implemented by performing the equivalent geometric construction. The screen displays the result, and perhaps a representation of the geometric process.
* **User Flow:** User loads a very simple ROM or directly inputs ALU commands (e.g., 'ADD RegisterA, RegisterB'). The emulator interprets the command, triggers the corresponding geometric construction sequence (potentially visualized), updates internal registers (represented geometrically), and displays the outcome on the emulator screen.
* **Interface:** A basic emulator screen (e.g., a 160x144 pixel black and white display), register display (simplified), command input, and a button to execute the next instruction.
* **D. Educational Content & Examples:**
* **Description:** Sections explaining the core geometric constructions (Euclid's postulates), the mathematical basis for the arithmetic module, and how the emulator utilizes these principles.
* **User Flow:** Users navigate through different pages or sections. They can view interactive tutorials, step-by-step examples of calculations (e.g., 'Constructing 3 + 5'), and demonstrations of specific emulator opcodes.
* **Content:** Text explanations, diagrams, possibly short video clips, and interactive demos.
**4. UI/UX DESIGN**
* **Layout:** A clean, modern, and responsive single-page layout. A possible structure:
* **Header:** Application title, navigation (if needed), and perhaps a global tool selection.
* **Main Content Area:** This could be split or tabbed:
* **Canvas View:** Dominant area for geometric constructions and emulator display.
* **Controls Panel:** Sidebar or bottom panel for tool selection, input fields, operation buttons, register display, command input, and result display.
* **Information/Examples Panel:** Collapsible section or separate tab for educational content and running examples.
* **Footer:** Copyright, links (e.g., GitHub repo, FAQ).
* **Color Palette:** A minimalist and focused palette. Consider:
* **Background:** Dark grey or off-white (e.g., `#f8f9fa` or `#212529` for dark mode).
* **Canvas Background:** White or very light grey for clarity (`#ffffff`).
* **Primary/Accent:** A tech-oriented color like a vibrant blue (`#007bff`), teal (`#20c997`), or purple (`#6f42c1`) for active tools, buttons, and important highlights.
* **Geometric Elements:** Black/Grey for lines/points, distinct colors for points generated by specific operations or used in calculations (e.g., red for origins, blue for constructed points).
* **Emulator Screen:** Grayscale shades.
* **Typography:** Clean, readable sans-serif fonts. Use a combination for hierarchy (e.g., Inter, Poppins, or Lato). Ensure good contrast ratios.
* **Responsive Design:** Mobile-first approach. Ensure usability on various screen sizes. On smaller screens, panels might become collapsible drawers or stacked sections. Canvas might need zooming/panning controls.
**5. COMPONENT BREAKDOWN**
* **`App.js` (or `App.tsx`):** Main application component. Sets up layout, context providers, and potentially routing.
* **`Header.js`:** Contains the app title and main navigation/tool switching.
* **`CanvasComponent.js`:**
* **Responsibilities:** Renders the HTML5 Canvas, manages drawing of geometric shapes and the emulator screen, handles user input events (mouse clicks, drags) on the canvas.
* **Props:** `shapes` (array of geometric objects), `emulatorScreenData` (pixel data), `activeTool`, `onShapeCreate`, `onPointSelect`, `onIntersectionSelect`.
* **`Toolbox.js`:**
* **Responsibilities:** Displays available tools (Point, Line, Circle, Intersection, Select) and allows the user to select the active tool.
* **Props:** `activeTool`, `onToolSelect`.
* **`ControlsPanel.js`:**
* **Responsibilities:** Container for input fields, operation buttons, and result display.
* **Components:** `NumberInput.js`, `OperationSelector.js`, `ResultDisplay.js`.
* **`NumberInput.js`:**
* **Responsibilities:** Input field for numbers, possibly with labels indicating geometric origin (e.g., 'Input a:', 'Input b:').
* **Props:** `label`, `value`, `onChange`, `isGeometricallyDerived` (boolean).
* **`OperationSelector.js`:**
* **Responsibilities:** Buttons or dropdown for selecting arithmetic operations (Add, Subtract, Multiply, Divide).
* **Props:** `selectedOperation`, `onOperationSelect`.
* **`ResultDisplay.js`:**
* **Responsibilities:** Shows the calculated result with arbitrary precision.
* **Props:** `result`, `precisionLabel`.
* **`EmulatorView.js`:**
* **Responsibilities:** Contains the emulator screen and potentially register display.
* **Components:** `EmulatorScreen.js`, `RegisterDisplay.js`.
* **`EmulatorScreen.js`:**
* **Responsibilities:** Renders the emulator's output using a Canvas element, taking pixel data as input.
* **Props:** `pixels` (array or typed array representing screen buffer).
* **`RegisterDisplay.js`:**
* **Responsibilities:** Shows the current state of key emulator registers (e.g., A, B, PC).
* **Props:** `registers` (object).
* **`InstructionInput.js`:**
* **Responsibilities:** Input field for emulator instructions/opcodes.
* **Props:** `instruction`, `onInstructionChange`.
* **`ExecuteButton.js`:**
* **Responsibilities:** Button to execute the current instruction.
* **Props:** `onClick`.
* **`EducationalContent.js`:**
* **Responsibilities:** Displays articles, tutorials, and example walkthroughs.
* **Components:** `Article.js`, `ExampleStep.js`.
* **`ContextMenu.js` (Advanced):**
* **Responsibilities:** Displays context-specific options when right-clicking on canvas elements (e.g., 'Delete', 'Show Coordinates', 'Use in Calculation').
* **Props:** `position`, `options`, `onSelect`.
**6. DATA MODEL & STATE MANAGEMENT**
* **Geometric Shapes:** An array of objects, each representing a shape.
```javascript
// Example shape object
{
id: 'unique_shape_id',
type: 'line' | 'circle' | 'point',
color: string, // e.g., '#000000'
data: {
// Specific data based on type
// Point: { x: number, y: number }
// Line: { p1: Point, p2: Point } or { slope: number, intercept: number }
// Circle: { center: Point, radius: number }
},
constructionSteps: string[] // Optional: history of how it was made
}
```
* **Canvas State:** `activeTool`, `selectedShapes` (array of IDs), `currentMousePosition`, `points` (array of constructed points, potentially linked to shapes).
* **Arithmetic State:** `inputA`, `inputB`, `selectedOperation`, `result`, `calculationHistory` (array of past calculations).
* **Emulator State:** `registers` (object: `{ A: string, B: string, PC: string, ... }`), `emulatorScreenPixels` (Uint8ClampedArray or similar for pixel data), `currentInstruction`, `instructionLog`.
* **State Management Strategy:**
* Local state (`useState`, `useReducer`) within components for UI-specific states (e.g., input field value).
* Global state (`Context API`) for application-wide states like `activeTool`, `allShapes`, `emulatorState`, potentially `arithmeticInputs`.
* Pass necessary state and dispatch functions down via props or consume via context.
* **Mock Data Examples:**
```javascript
// Sample initial shapes
const initialShapes = [
{ id: 'p0', type: 'point', color: '#FF0000', data: { x: 0, y: 0 } }, // Origin
{ id: 'p1', type: 'point', color: '#0000FF', data: { x: 1, y: 0 } } // Unit
];
// Sample emulator registers
const initialRegisters = {
A: '0x00', // Represents a geometrically derived value, e.g., '0'
B: '0x00',
PC: '0x0000'
};
// Sample arithmetic calculation log entry
const calcLogEntry = {
timestamp: Date.now(),
inputA: '5.345', // Could be a string representing arbitrary precision
inputB: '2.123',
operation: 'add',
result: '7.468'
};
```
**7. ANIMATIONS & INTERACTIONS**
* **Tool Selection:** Subtle highlight or border change on the active tool icon. Smooth transition when switching tools.
* **Shape Creation:** Animate the drawing of lines and circles (e.g., drawing stroke). Points could subtly pulse when created.
* **Hover Effects:** Hovering over points, lines, or circles on the canvas could slightly enlarge them or change their color/opacity to indicate interactivity. Hovering over buttons should provide visual feedback (slight scale, background change).
* **Loading States:** If any calculations or constructions take time (especially complex ones), display a subtle loading indicator (e.g., a spinning icon, a progress bar on the canvas, or disabling controls with a loading overlay).
* **Transitions:** Smooth transitions for collapsing/expanding panels, showing/hiding tooltips, and updating display values (e.g., animating number changes in the result display).
* **Micro-interactions:** Feedback on successful actions (e.g., a small confirmation animation when a point is successfully created from intersections). Error states should be clearly indicated (e.g., red border around input, toast notification).
**8. EDGE CASES & ACCESSIBILITY (a11y)**
* **Empty Canvas State:** When no shapes are present (except initial points), provide guidance text (e.g., "Select the 'Line' tool and click two points to start.").
* **No Intersections:** If line/circle intersections are requested but none exist mathematically, display a clear message (e.g., "No intersection found."). Handle parallel lines gracefully.
* **Invalid Input:** Validate all user inputs (numbers, instructions). Provide clear error messages and styling (e.g., red border, helper text). For geometric inputs, ensure users click valid entities.
* **Zero Division:** Explicitly handle division by zero in the arithmetic module and emulator.
* **Precision Limits:** While aiming for arbitrary precision, consider practical limits or display controls for the level of precision shown to avoid overwhelming the user or causing performance issues.
* **Accessibility (a11y):**
* Use semantic HTML elements.
* Ensure sufficient color contrast for text and UI elements.
* Provide `aria-labels` and `alt` text where appropriate.
* Keyboard navigation: Ensure all interactive elements (buttons, inputs, canvas tools) are focusable and operable via keyboard.
* Canvas Accessibility: This is challenging. Consider providing textual descriptions or alternative ways to input/output data for users who cannot interact with the canvas directly. For example, listing constructed points with coordinates and allowing selection/manipulation via text.
* **Undo/Redo:** Implement undo/redo functionality for geometric constructions and potentially arithmetic operations.
**9. SAMPLE DATA**
* **Initial Canvas State:**
```json
{
"points": [
{"id": "origin", "type": "point", "color": "#FF0000", "data": {"x": 0, "y": 0}, "label": "Origin"},
{"id": "unit", "type": "point", "color": "#0000FF", "data": {"x": 1, "y": 0}, "label": "Unit"}
],
"lines": [],
"circles": []
}
```
* **Example User Interaction - Constructing Line `y=x`:**
* User selects `Line` tool.
* User clicks `Origin` (p0).
* User clicks `Unit` (p1).
* **New Line:** `{"id": "l1", "type": "line", "color": "#000000", "data": {"p1": "origin", "p2": "unit"}, "equation": "y=0"}` (Oops, this is the x-axis. Let's assume we want `y=x`. Need a way to construct perpendicular bisectors or use angles. For simplicity, let's assume we *can* construct a line through origin with slope 1).
* **Corrected Example:** Let's assume we have a way to construct a standard unit (1,1) point, perhaps via angle bisection or other constructions not explicitly listed but implied.
* **Assume:** A point `p_diag` exists at (1,1).
* **Construct Line `y=x`:** `{"id": "l_diag", "type": "line", "color": "#800080", "data": {"p1": "origin", "p2": "p_diag"}, "label": "y=x"}`
* **Example Arithmetic Operation (5.5 + 2.25):**
* Input A: `"5.5"`
* Input B: `"2.25"`
* Operation: `"add"`
* **Result:** `"7.75"` (represented as a string for arbitrary precision)
* **Emulator State Example:**
```json
{
"registers": {"A": "7.75", "B": "0.0", "PC": "0x0001"},
"screen": Array(160*144).fill(0) // Array of pixel values (0 or 1 for B/W)
}
```
* **Educational Content Snippet:**
```json
{
"title": "Constructing a Perpendicular Bisector",
"steps": [
{"instruction": "Given a line segment AB, place the compass point on A...", "image": "/images/perp_bisector_step1.png"},
{"instruction": "...draw an arc above and below the segment.", "image": "/images/perp_bisector_step2.png"},
// ... more steps
]
}
```
**10. DEPLOYMENT NOTES**
* **Build Command:** Use Vite's build command (`npm run build` or `yarn build`). This will generate optimized static assets in a `dist` folder.
* **Environment Variables:** Use `.env` files for environment-specific configurations (e.g., API keys if external services were used, though unlikely for MVP). Vite uses `VITE_` prefix for exposing variables to the client-side build.
* **Hosting:** Deploy the static build output to any static hosting provider (e.g., Netlify, Vercel, GitHub Pages, AWS S3). Ensure the hosting is configured to serve the `index.html` file for all routes to support the SPA routing (if React Router is used).
* **Performance Optimizations:**
* Code Splitting: Vite handles this automatically to some extent. Ensure large components or unused features are lazy-loaded.
* Memoization: Use `React.memo`, `useMemo`, `useCallback` judiciously to prevent unnecessary re-renders, especially in the `CanvasComponent` and areas with frequent state updates.
* Canvas Optimization: For the canvas, avoid re-rendering the entire scene if only one element changes. Optimize drawing operations. Consider using libraries like `Konva.js` or `Fabric.js` if managing complex canvas interactions becomes too difficult with the native API, but stick to native Canvas first as per the prompt.
* Image Optimization: If any static images are used, ensure they are optimized (e.g., using WebP format, appropriate compression).