# Product Requirements Document: Simple Calculator

## 1. Overview

A single-page web-based calculator application that provides basic arithmetic operations for general-purpose calculations. The calculator offers a clean, intuitive interface allowing users to perform addition, subtraction, multiplication, and division operations with real-time display of inputs and results. This is a client-side application requiring no user authentication or data persistence.

## 2. User Roles

### Anonymous User (Default Role)
- Access the calculator interface without authentication
- Perform arithmetic calculations (addition, subtraction, multiplication, division)
- View calculation history within the current session
- Clear current input or reset the calculator
- Copy results to clipboard

## 3. Core Entities

### Calculation
**Description:** Represents a single arithmetic operation performed by the user.

**Attributes:**
- `id` (string): Unique identifier for the calculation
- `operand1` (number): First number in the operation
- `operator` (string): Arithmetic operator (+, -, ×, ÷)
- `operand2` (number): Second number in the operation
- `result` (number): Calculated result
- `timestamp` (datetime): When the calculation was performed
- `expression` (string): Full expression as displayed (e.g., "5 + 3 = 8")

### CalculatorState
**Description:** Represents the current state of the calculator interface.

**Attributes:**
- `currentDisplay` (string): Current value shown on the display
- `previousValue` (number|null): Previously entered value
- `currentOperator` (string|null): Currently selected operator
- `awaitingOperand` (boolean): Whether calculator is waiting for next operand input
- `isResultDisplayed` (boolean): Whether the display shows a result
- `memory` (number): Value stored in memory (for M+, M-, MR, MC functions)

### SessionHistory
**Description:** Collection of calculations performed in the current session.

**Attributes:**
- `sessionId` (string): Unique identifier for the browser session
- `calculations` (array): Array of Calculation objects
- `startTime` (datetime): When the session began
- `lastActivityTime` (datetime): Last interaction timestamp

## 4. Entity Relationships

### CalculatorState ↔ Calculation
- **Relationship:** One-to-One (current)
- **Description:** CalculatorState generates one Calculation when equals is pressed

### SessionHistory ↔ Calculation
- **Relationship:** One-to-Many
- **Description:** One SessionHistory contains many Calculations (0 to unlimited)

### CalculatorState ↔ SessionHistory
- **Relationship:** One-to-One
- **Description:** Each CalculatorState is associated with one SessionHistory for the current session

## 5. Key Workflows

### Workflow 1: Basic Calculation
1. User opens the calculator application
2. System initializes CalculatorState with default values (display: "0")
3. User clicks/taps number buttons to enter first operand
4. System updates `currentDisplay` with each digit entered
5. User selects an operator (+, -, ×, ÷)
6. System stores the first operand in `previousValue` and operator in `currentOperator`
7. System sets `awaitingOperand` to true
8. User enters second operand
9. System updates `currentDisplay` with second operand
10. User presses equals (=) button
11. System performs calculation based on operator
12. System creates a Calculation entity with all values
13. System adds Calculation to SessionHistory
14. System displays result in `currentDisplay`
15. System sets `isResultDisplayed` to true

### Workflow 2: Chained Calculations
1. User completes a basic calculation (result is displayed)
2. User presses an operator button without entering a new number
3. System uses the current result as `previousValue`
4. System stores the new operator in `currentOperator`
5. User enters next operand
6. User presses equals or another operator
7. System calculates result using previous result and new operand
8. System creates new Calculation entity
9. System updates display with new result
10. Process can repeat indefinitely

### Workflow 3: Clear Operations
**Clear Entry (CE):**
1. User presses CE button
2. System resets `currentDisplay` to "0"
3. System maintains `previousValue` and `currentOperator`
4. User can continue current calculation

**All Clear (AC):**
1. User presses AC button
2. System resets all CalculatorState values to defaults
3. System clears `currentDisplay`, `previousValue`, `currentOperator`
4. System maintains SessionHistory
5. Calculator returns to initial state

### Workflow 4: View History
1. User clicks history icon/button
2. System displays SessionHistory panel
3. System shows list of calculations in reverse chronological order
4. User can click on a historical calculation
5. System loads that result into `currentDisplay`
6. User can continue calculating from that value

### Workflow 5: Error Handling
1. User attempts invalid operation (e.g., division by zero)
2. System detects error condition
3. System displays error message ("Error" or "Cannot divide by zero")
4. System sets error state
5. User must press AC to clear error and continue
6. System does not create Calculation entity for error operations

## 6. Features & Requirements

### 6.1 Display Module

**FR-1.1:** Display area shows current input or result
- Minimum display: 10 digits
- Maximum display: 15 digits
- Font size adjusts for longer numbers
- Right-aligned text

**FR-1.2:** Display shows "0" on initial load

**FR-1.3:** Display updates in real-time as user inputs numbers

**FR-1.4:** Display shows error messages when applicable

**FR-1.5:** Display shows current expression above main display (e.g., "5 + 3")

### 6.2 Number Input Module

**FR-2.1:** Number buttons 0-9 for digit entry

**FR-2.2:** Decimal point button for floating-point numbers

**FR-2.3:** Only one decimal point allowed per number

**FR-2.4:** Leading zeros are automatically removed (except "0.")

**FR-2.5:** Support for negative numbers via +/- toggle button

**FR-2.6:** Maximum input length of 15 digits

### 6.3 Operator Module

**FR-3.1:** Addition (+) button

**FR-3.2:** Subtraction (-) button

**FR-3.3:** Multiplication (×) button

**FR-3.4:** Division (÷) button

**FR-3.5:** Equals (=) button to execute calculation

**FR-3.6:** Visual feedback when operator is selected (highlighted state)

**FR-3.7:** Pressing operator immediately after equals chains calculations

### 6.4 Control Module

**FR-4.1:** Clear Entry (CE) button - clears current input only

**FR-4.2:** All Clear (AC) button - resets calculator completely

**FR-4.3:** Backspace/Delete button - removes last digit entered

**FR-4.4:** Percentage (%) button - converts current number to percentage

### 6.5 Memory Module

**FR-5.1:** Memory Clear (MC) - clears memory value

**FR-5.2:** Memory Recall (MR) - displays memory value

**FR-5.3:** Memory Add (M+) - adds current display to memory

**FR-5.4:** Memory Subtract (M-) - subtracts current display from memory

**FR-5.5:** Visual indicator when memory contains a value

### 6.6 History Module

**FR-6.1:** History panel toggleable via button

**FR-6.2:** Display last 50 calculations in session

**FR-6.3:** Each history entry shows full expression and result

**FR-6.4:** Click history entry to load result into calculator

**FR-6.5:** Clear history button to remove all session history

**FR-6.6:** History persists during session but clears on page refresh

### 6.7 Keyboard Support Module

**FR-7.1:** Number keys (0-9) map to number buttons

**FR-7.2:** Operator keys (+, -, *, /) map to operator buttons

**FR-7.3:** Enter/Return key maps to equals button

**FR-7.4:** Escape key maps to AC button

**FR-7.5:** Backspace key maps to delete button

**FR-7.6:** Decimal/period key maps to decimal point button

### 6.8 Copy/Paste Module

**FR-8.1:** Copy button to copy current result to clipboard

**FR-8.2:** Visual confirmation when value is copied

**FR-8.3:** Paste support to input numbers from clipboard

**FR-8.4:** Pasted values validated as numbers

## 7. Business Rules

### BR-1: Calculation Rules

**BR-1.1:** Division by zero displays "Cannot divide by zero" error

**BR-1.2:** Results exceeding 15 digits display in scientific notation

**BR-1.3:** Calculations follow standard order of operations (left to right for same precedence)

**BR-1.4:** Floating-point results rounded to 10 decimal places maximum

**BR-1.5:** Negative zero (-0) displayed as positive zero (0)

### BR-2: Input Validation Rules

**BR-2.1:** Only numeric input (0-9) and decimal point allowed

**BR-2.2:** Cannot enter multiple decimal points in single number

**BR-2.3:** Cannot enter operators without a number first (except minus for negative numbers)

**BR-2.4:** Leading zeros automatically removed except for "0.x" format

**BR-2.5:** Empty input treated as zero

### BR-3: State Management Rules

**BR-3.1:** Pressing equals multiple times repeats last operation

**BR-3.2:** Entering number after result clears result and starts new calculation

**BR-3.3:** Entering operator after result uses result as first operand

**BR-3.4:** Error state must be cleared before new calculation

**BR-3.5:** Memory operations do not affect current calculation state

### BR-4: Display Rules

**BR-4.1:** Display never shows more than 15 characters (excluding error messages)

**BR-4.2:** Very large/small numbers automatically convert to scientific notation

**BR-4.3:** Trailing zeros after decimal point removed (except one zero for .0)

**BR-4.4:** Thousand separators not displayed during input, only in results

### BR-5: History Rules

**BR-5.1:** Only successful calculations added to history

**BR-5.2:** Error operations not recorded in history

**BR-5.3:** History limited to 50 most recent calculations

**BR-5.4:** History cleared when browser session ends

**BR-5.5:** Duplicate calculations are recorded separately with timestamps

### BR-6: Memory Rules

**BR-6.1:** Memory initialized to zero

**BR-6.2:** Memory persists across calculations within session

**BR-6.3:** Memory cleared on page refresh

**BR-6.4:** Memory operations work with current display value

**BR-6.5:** Memory can store negative values

## 8. Non-Functional Requirements

### NFR-1: Performance

**NFR-1.1:** Calculation results displayed within 50ms of user action

**NFR-1.2:** Button press feedback (visual) within 16ms (60fps)

**NFR-1.3:** Application loads completely within 2 seconds on 3G connection

**NFR-1.4:** History panel opens/closes within 300ms with smooth animation

**NFR-1.5:** Support for 1000+ calculations in session without performance degradation

### NFR-2: Usability

**NFR-2.1:** Touch targets minimum 44x44 pixels for mobile devices

**NFR-2.2:** Keyboard navigation support for all functions

**NFR-2.3:** Clear visual distinction between number, operator, and control buttons

**NFR-2.4:** Responsive design supporting screen sizes from 320px to 4K

**NFR-2.5:** Color contrast ratio minimum 4.5:1 for WCAG AA compliance

### NFR-3: Compatibility

**NFR-3.1:** Support for Chrome, Firefox, Safari, Edge (latest 2 versions)

**NFR-3.2:** Support for iOS Safari and Chrome on Android

**NFR-3.3:** Functional without JavaScript (graceful degradation message)

**NFR-3.4:** Works offline after initial load (PWA capability)

**NFR-3.5:** No external dependencies required after initial load

### NFR-4: Accessibility

**NFR-4.1:** WCAG 2.1 Level AA compliance

**NFR-4.2:** Screen reader support with ARIA labels for all buttons

**NFR-4.3:** Keyboard-only operation fully supported

**NFR-4.4:** Focus indicators clearly visible

**NFR-4.5:** Semantic HTML structure for assistive technologies

**NFR-4.6:** Announced calculation results for screen readers

### NFR-5: Security

**NFR-5.1:** No data transmitted to servers (fully client-side)

**NFR-5.2:** No cookies or tracking mechanisms

**NFR-5.3:** Content Security Policy (CSP) headers implemented

**NFR-5.4:** Input sanitization to prevent XSS (even though client-side only)

**NFR-5.5:** No external script dependencies from CDNs

### NFR-6: Maintainability

**NFR-6.1:** Modular code structure with separation of concerns

**NFR-6.2:** Comprehensive unit test coverage (minimum 80%)

**NFR-6.3:** Clear code documentation and inline comments

**NFR-6.4:** Consistent code style following industry standards

**NFR-6.5:** Version control with semantic versioning

### NFR-7: Scalability

**NFR-7.1:** Architecture supports adding scientific calculator functions

**NFR-7.2:** History storage mechanism can be extended to persistent storage

**NFR-7.3:** Theme system supports multiple color schemes

**NFR-7.4:** Localization-ready for multiple languages

**NFR-7.5:** Plugin architecture for custom functions

### NFR-8: Browser Storage

**NFR-8.1:** Session storage used for temporary history (max 5MB)

**NFR-8.2:** Local storage optional for user preferences

**NFR-8.3:** Graceful handling of storage quota exceeded errors

**NFR-8.4:** No sensitive data stored in browser storage

### NFR-9: Error Handling

**NFR-9.1:** All errors display user-friendly messages

**NFR-9.2:** Application never crashes or becomes unresponsive

**NFR-9.3:** Automatic recovery from error states

**NFR-9.4:** Console logging for debugging (disabled in production)

**NFR-9.5:** Error boundaries prevent complete application failure

### NFR-10: Visual Design

**NFR-10.1:** Clean, minimalist interface design

**NFR-10.2:** Consistent spacing and alignment (8px grid system)

**NFR-10.3:** Smooth transitions and animations (max 300ms)

**NFR-10.4:** Support for light and dark themes

**NFR-10.5:** Professional color palette with good contrast

---

**Document Version:** 1.0  
**Last Updated:** 2025  
**Status:** Ready for Development