@plotinus/matrix-package-calculator
Version:
Calculator components for the Matrix framework - basic arithmetic operations with UI
266 lines (201 loc) • 7.48 kB
Markdown
# @matrix/package-calculator
Calculator components for the Matrix framework - basic arithmetic operations with a beautiful UI.
## Package Overview
This package provides a complete calculator implementation for the Matrix framework:
- **calculator**: A full-featured calculator component with basic arithmetic operations (add, subtract, multiply, divide)
- **Digital Display**: Classic calculator LCD-style display with green text
- **Interactive UI**: Responsive button layout with hover effects and proper styling
- **State Management**: Maintains calculation history and current state
- **Error Handling**: Handles division by zero and other edge cases
## Development Workflow
### Working on this Package
1. **Source Location**: `/packages/package-calculator` (this directory)
2. **Production Location**: `/packages/matrix-repl-chat/packages/package-calculator` (after deployment)
3. **Deployment**: Use `npm run deploy:package-calculator` from the demo-9 root
### Development Commands
```bash
# Build this package locally
npm run build
# Run tests (if any)
npm test
# Generate code dump
npm run codedump
# Clean build artifacts
npm run clean
```
### Deployment Process
**IMPORTANT**: When you make changes to this package, you must deploy them to the production location where the Matrix REPL loads them from:
```bash
# From the demo-9 root directory
npm run deploy:package-calculator
# Then build the deployed package
cd packages/matrix-repl-chat/packages/package-calculator
npm run build
```
## Calculator Features
### Arithmetic Operations
- **Addition** (`+`): Add two numbers
- **Subtraction** (`−`): Subtract second number from first
- **Multiplication** (`×`): Multiply two numbers
- **Division** (`÷`): Divide first number by second (with zero-division protection)
### UI Features
- **Digital Display**: Black background with green LCD-style text
- **Responsive Buttons**: Grid layout with hover and active states
- **Operation Feedback**: Visual feedback for button presses
- **Clear Function**: Reset calculator to initial state
- **Equals Processing**: Complete pending operations
### Event System
- **CalculatorReady**: Emitted when calculator initializes
- **DisplayUpdated**: Emitted when display value changes
- **OperationSet**: Emitted when an operation is selected
- **EqualsComplete**: Emitted when equals button completes calculation
- **CalculatorCleared**: Emitted when calculator is reset
- **CalculationError**: Emitted on errors (e.g., division by zero)
## Installation
### Using Matrix CLI (Recommended)
```bash
# Install from npm registry (when published)
matrix install --registry @matrix/package-calculator
matrix up package-calculator
# Install from local monorepo
matrix install --monorepo package-calculator
matrix up package-calculator
# Run directly from source (development)
matrix up --monorepo package-calculator
```
### Traditional npm
```bash
npm install @matrix/package-calculator
```
## Browser Usage
### ES Module from CDN (Future)
```javascript
// Load from unpkg or other CDN
await window.MatrixPackageRegistry.install({
source: 'cdn',
name: '@matrix/package-calculator',
version: '1.0.0'
});
```
### Current: Bundle Integration
```html
<!-- Include the bundled package -->
<script src="/packages/package-calculator.bundle.js"></script>
<script type="module">
// Package auto-registers when loaded
// Or manually register components
window.MatrixPackageCalculator.registerCalculatorComponents(window.Matrix);
</script>
```
### Direct Import (Build Tools)
```javascript
import { registerCalculatorComponents, componentSources } from '@matrix/package-calculator/browser';
// Register all components with Matrix
registerCalculatorComponents(window.Matrix);
```
## Server Usage
```javascript
import {
CalculatorComponent
} from '@matrix/package-calculator';
// Components are automatically registered with matrix-cli
```
## DSL Example
```xml
<calculator id="myCalculator"
onCalculatorReady="handleCalculatorReady"
onDisplayUpdated="handleDisplayUpdate"
onCalculationComplete="handleCalculationComplete"
onCalculationError="handleCalculationError"
emits="CalculatorReady,DisplayUpdated,CalculationComplete,OperationSet,EqualsComplete,CalculatorCleared,CalculationError">
</calculator>
```
## Component Communication
The calculator uses event-driven communication:
### Commands (Input)
- `onNumberInput`: Input a digit (0-9)
- `onOperation`: Set operation (add, subtract, multiply, divide)
- `onEquals`: Complete current calculation
- `onClear`: Reset calculator state
- `onCalculate`: Direct calculation with operation object
### Events (Output)
- `CalculatorReady`: Calculator is initialized and ready
- `DisplayUpdated`: Display value has changed
- `OperationSet`: An operation has been selected
- `EqualsComplete`: Equals operation completed
- `CalculatorCleared`: Calculator was reset
- `CalculationError`: An error occurred (e.g., division by zero)
## Architecture
The calculator follows Matrix framework patterns:
### Component Structure
```
CalculatorComponent (Communication)
├── State Management
├── Arithmetic Operations
├── Error Handling
└── Event Emission
CalculatorPresentationElement (UI)
├── Digital Display
├── Button Grid
├── User Interaction
└── Visual Feedback
```
### State Management
- **display**: Current display value (string)
- **currentValue**: Current numeric value
- **previousValue**: Previous value for operations
- **pendingOperation**: Operation waiting to be completed
- **waitingForNewValue**: Flag for input state management
- **history**: Array of all calculations performed
## Building
```bash
# Install dependencies
npm install
# Build the package
npm run build
```
This will:
1. Convert HTML definitions to ESM modules
2. Compile TypeScript sources
3. Create browser bundle at `dist/browser-bundle.js`
4. Generate type definitions and component manifest
### Publishing to npm
```bash
# Using npm directly
npm publish --access public
# Or using Matrix CLI
matrix publish package-calculator
```
## Testing the Calculator
Once deployed and loaded in the Matrix REPL:
1. **Load Package**: Click "package-calculator" in the packages list
2. **Use Calculator**: Click "Use: Calculator" to instantiate
3. **Test Operations**:
- Click numbers (0-9) to input values
- Click operations (+, −, ×, ÷) to set operations
- Click = to complete calculations
- Click C to clear and reset
4. **Verify State**: Check that display updates correctly and operations work as expected
## Example Usage
```javascript
// Create calculator instance
const calc = new CalculatorComponent('calc1', eventBus);
// Handle calculator events
calc.on('DisplayUpdated', (data) => {
console.log('Display:', data.display);
});
calc.on('CalculationComplete', (data) => {
console.log('Result:', data.result);
});
// Input numbers and operations
calc.numberInputHandler({ digit: 5 });
calc.operationHandler({ operation: 'add' });
calc.numberInputHandler({ digit: 3 });
calc.equalsHandler(); // Result: 8
```
## Related Documentation
- [Matrix CLI Documentation](../../packages/matrix-cli/README.md) - Complete CLI usage guide
- [Package Deployment Guide](../../PackageDeployment.md) - How to create and deploy Matrix packages
- [Package Coordinator](../package-coordinator/README.md) - Example of multi-component package
## License
MIT