npm package: @rhushya/calculator-component
Description: A secure React calculator component that requires API token authentication and communicates with a backend service for all calculations
Author: rhushya
Latest version: 2.0.0

# 🔒 @rhushya/calculator-component

A secure React calculator component that requires API token authentication and communicates with a backend service for all calculations. This component provides enterprise-level security and full mathematical functionality without client-side calculation exposure.

[![npm version](https://badge.fury.io/js/%40rhushya%2Fcalculator-component.svg)](https://badge.fury.io/js/%40rhushya%2Fcalculator-component)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## ✨ Features

- 🔐 **Token-based Authentication** - Requires valid API token to function
- 🌐 **Backend Service Communication** - All calculations performed server-side
- 🧮 **Full Calculator Functionality** - Not simplified math, includes scientific functions
- 📊 **Scientific Operations** - sin, cos, tan, sqrt, log, power functions
- 📝 **Calculation History** - Tracks recent calculations
- ⚡ **Real-time Error Handling** - Comprehensive error reporting
- 🎨 **Modern UI** - Beautiful interface with loading states
- 🔒 **Enterprise Security** - No client-side mathematical exposure

## 🚀 Quick Start

### 1. Installation

```bash
npm install @rhushya/calculator-component
```

### 2. Setup Backend Service

The calculator component requires a running backend service for authentication and calculations.

```bash
# Clone or setup the backend service
cd your-project
mkdir calculator-backend
cd calculator-backend

# Create package.json
npm init -y

# Install dependencies
npm install express cors jsonwebtoken express-rate-limit

# Create server.js (see backend-example folder for complete code)
# Start the service
npm start
```

### 3. Basic Usage

```jsx
import React from 'react';
import { Calculator } from '@rhushya/calculator-component';

function App() {
  const handleError = (error) => {
    console.error('Calculator Error:', error);
    // Handle error (show notification, etc.)
  };

  const handleAuthFailure = (error) => {
    console.error('Authentication Failed:', error);
    // Handle authentication failure
  };

  return (
    <div>
      <Calculator
        apiToken="your-jwt-token-here"
        apiUrl="https://your-api-domain.com/api"
        onError={handleError}
        onAuthFailure={handleAuthFailure}
      />
    </div>
  );
}
```

## 📖 API Reference

### Props

| Prop | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `apiToken` | `string` | ✅ | - | JWT token for API authentication |
| `apiUrl` | `string` | ❌ | `'https://api.rhushya.com/calculator'` | Backend service URL |
| `initialValue` | `number` | ❌ | `0` | Initial display value |
| `className` | `string` | ❌ | `''` | Additional CSS classes |
| `style` | `React.CSSProperties` | ❌ | `{}` | Inline styles |
| `onError` | `(error: string) => void` | ❌ | - | Error callback function |
| `onAuthFailure` | `(error: string) => void` | ❌ | - | Authentication failure callback |

### Backend API Endpoints

Your backend service must implement these endpoints:

#### Authentication
```
POST /api/auth/verify
Headers: Authorization: Bearer <token>
Body: { "token": "your-jwt-token" }
Response: { "success": true, "message": "Token is valid" }
```

#### Calculation
```
POST /api/calculate
Headers: Authorization: Bearer <token>
Body: {
  "operation": "add|subtract|multiply|divide|power|sqrt|sin|cos|tan|log",
  "operand1": number,
  "operand2": number (optional for single-operand functions)
}
Response: {
  "success": true,
  "result": number,
  "operation": string,
  "operands": number[]
}
```

## 🔧 Backend Service Setup

### Example Backend Implementation

See the `backend-example` folder for a complete Node.js/Express implementation.

```bash
cd backend-example
npm install
npm start
```

The example service includes:
- JWT token validation
- Rate limiting
- CORS configuration
- Mathematical operations
- Error handling
- Logging

### Test Tokens

For development, use these test tokens:

```
Token 1: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Token 2: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIwOTg3NjU0MzIxIiwibmFtZSI6IkphbmUgU21pdGgiLCJpYXQiOjE1MTYyMzkwMjJ9.4pcPyMD09olPSyXnrXCjTwXyr4BsezdI1AVTmud2fU4
```

## 🧮 Supported Operations

### Basic Arithmetic
- ➕ Addition
- ➖ Subtraction  
- ✖️ Multiplication
- ➗ Division

### Scientific Functions
- 🔢 **Power (x^y)** - Exponentiation
- √ **Square Root** - √x
- 📐 **Trigonometric** - sin, cos, tan
- 📊 **Logarithm** - log₁₀(x)

## 🔒 Security Features

### Token Authentication
- Component validates token format before API calls
- All requests include Bearer token authentication
- Backend verifies token on every operation

### Server-Side Calculations
- No mathematical operations performed client-side
- Prevents calculation logic exposure
- Secure API communication

### Error Handling
- Authentication failures are properly handled
- Network errors are caught and reported
- Invalid operations return meaningful errors

## 🎨 Customization

### Styling

```jsx
<Calculator
  apiToken="your-token"
  className="my-calculator"
  style={{
    backgroundColor: '#f8f9fa',
    border: '2px solid #007bff',
    borderRadius: '12px',
    boxShadow: '0 4px 12px rgba(0,0,0,0.15)'
  }}
/>
```

### Error Handling

```jsx
const [errors, setErrors] = useState([]);

const handleError = (error) => {
  setErrors(prev => [...prev, { message: error, timestamp: Date.now() }]);
  // Show toast notification
  toast.error(error);
};

const handleAuthFailure = (error) => {
  // Redirect to login or show auth modal
  redirectToLogin();
};
```

## 📱 Responsive Design

The calculator automatically adapts to different screen sizes and provides a mobile-friendly interface.

## 🔧 Development

### Local Development

1. Clone the repository
2. Install dependencies: `npm install`
3. Start development server: `npm run dev`
4. Start backend service: `cd backend-example && npm start`
5. Open example: `http://localhost:3000`

### Building

```bash
npm run build
```

### Testing

Start the backend service and run the example app to test all functionality:

```bash
# Terminal 1: Start backend
cd backend-example
npm install && npm start

# Terminal 2: Start example app
npm install && npm run dev
```

## 🤝 Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🆘 Support

For support, please:
1. Check the [backend-example](./backend-example) for implementation reference
2. Review the error handling in the example app
3. Ensure your backend service is properly configured
4. Verify your API token is valid and properly formatted

## 🔗 Links

- [npm Package](https://www.npmjs.com/package/@rhushya/calculator-component)
- [GitHub Repository](https://github.com/rhushya/calculator-component)
- [Issue Tracker](https://github.com/rhushya/calculator-component/issues)

---

**⚠️ Important:** This calculator component requires a running backend service with proper authentication. It will not function without a valid API token and accessible backend endpoint.

![Calculator Component](https://img.shields.io/badge/npm-v1.4.0-blue) ![License](https://img.shields.io/badge/license-MIT-green)

A modern, customizable React calculator component using @rhushya math libraries. This component provides a clean user interface for performing basic arithmetic operations (addition, subtraction, multiplication, and division) with a dedicated compute button.

## Features

- ✨ Clean, modern UI with customizable styling
- 🔢 Supports all basic arithmetic operations
- 🧮 Built with @rhushya math libraries for accurate calculations
- 🔘 Dedicated "Compute" button with visual operation selection
- 📱 Responsive design that works on all screen sizes
- 🔄 Clear All and New Calculation functionality
- 🔧 TypeScript support with type definitions
- 🎨 Customizable through props

## Installation

```bash
npm install @rhushya/calculator-component
```

All required dependencies (@rhushya/add, @rhushya/subtract, @rhushya/multiply, @rhushya/divide) will be automatically installed.

## Usage

```jsx
import React from 'react';
import { Calculator } from '@rhushya/calculator-component';

function App() {
  return (
    <div>
      <h1>My Calculator App</h1>
      <Calculator 
        className="my-calculator"
        style={{ backgroundColor: '#f0f0f0' }}
      />
    </div>
  );
}

export default App;
```

### With TypeScript

```tsx
import React from 'react';
import { Calculator } from '@rhushya/calculator-component';

const App: React.FC = () => {
  return (
    <div>
      <h1>My Calculator App</h1>
      <Calculator 
        className="my-calculator"
        style={{ backgroundColor: '#f0f0f0' }}
      />
    </div>
  );
};

export default App;
```

## Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `className` | string | `''` | Additional CSS class name for styling |
| `style` | React.CSSProperties | `{}` | Inline styles for the calculator container |

## How It Works

The calculator follows a simple and intuitive workflow:

1. Enter the first number in the top input field
2. Enter the second number in the second input field
3. Select an operation (+, -, ×, ÷) by clicking on the respective button
   - The selected operation button will be highlighted
4. Click the "Compute" button to perform the calculation
5. The result will be displayed below with the complete calculation shown
6. Use "Clear All" to reset everything or "New Calculation" to perform another calculation

## UI Components

The calculator consists of the following UI elements:

- **Input Fields**: Two number input fields for entering the operands
- **Operation Buttons**: Four buttons for selecting the arithmetic operation
- **Compute Button**: A button that performs the calculation when clicked
- **Result Display**: Shows the complete calculation and the result
- **Control Buttons**: "Clear All" and "New Calculation" buttons

## Customization Examples

### Custom Colors

```jsx
<Calculator 
  style={{ 
    backgroundColor: '#f8f9fa',
    borderRadius: '12px',
    boxShadow: '0 8px 16px rgba(0,0,0,0.1)'
  }}
/>
```

### Custom Classes with CSS

```jsx
<Calculator className="my-custom-calculator" />
```

```css
/* In your CSS file */
.my-custom-calculator {
  border: 2px solid #6c5ce7;
  padding: 24px;
  font-family: 'Roboto', sans-serif;
}

.my-custom-calculator input {
  border: 1px solid #6c5ce7;
}

.my-custom-calculator button:hover {
  transform: translateY(-2px);
  transition: all 0.2s ease;
}
```

## Dependencies

This component automatically installs and uses the following @rhushya libraries:

- **@rhushya/add**: Handles addition operations
- **@rhushya/subtract**: Handles subtraction operations
- **@rhushya/multiply**: Handles multiplication operations
- **@rhushya/divide**: Handles division operations

## Browser Support

- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Edge (latest)
- IE11+ (with appropriate polyfills)

## Accessibility

The component is designed with accessibility in mind:
- All interactive elements are keyboard navigable
- Proper ARIA attributes are used where necessary
- High contrast colors for better readability

## Version History

| Version | Changes |
|---------|---------|
| 1.4.0   | Fixed import issues with math libraries, improved error handling |
| 1.3.0   | Added proper TypeScript type declarations |
| 1.2.0   | Added Compute button and visual feedback for selected operations |
| 1.1.0   | Initial public release |

## Development

### Prerequisites

- Node.js (v14 or higher)
- npm or yarn

### Setup

1. Clone the repository
2. Install dependencies:
   ```bash
   npm install
   ```

### Development Commands

```bash
# Run development build with watch mode
npm run dev

# Build the component for production
npm run build
```

### Publishing

To build and publish a new version of the component:

1. Update the version in package.json
2. Update the README.md with the new version number
3. Run the following commands:

```bash
# Build the component
npm run build

# Publish to npm registry
npm publish --access public
```

## License

MIT © [Rhushya](https://github.com/rhushya)

## Author

Created by [Rhushya](https://github.com/rhushya)

## Contributing

Contributions, issues, and feature requests are welcome! Feel free to check the [issues page](https://github.com/rhushya/calculator-component/issues).

## Support

If you encounter any problems or have questions, please [open an issue](https://github.com/rhushya/calculator-component/issues/new).