@rhushya/calculator-component
v2.0.0
Published
A secure React calculator component that requires API token authentication and communicates with a backend service for all calculations
Downloads
42
Maintainers
Readme
🔒 @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.
✨ 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
npm install @rhushya/calculator-component2. Setup Backend Service
The calculator component requires a running backend service for authentication and calculations.
# 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 start3. Basic Usage
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.
cd backend-example
npm install
npm startThe 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
<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
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
- Clone the repository
- Install dependencies:
npm install - Start development server:
npm run dev - Start backend service:
cd backend-example && npm start - Open example:
http://localhost:3000
Building
npm run buildTesting
Start the backend service and run the example app to test all functionality:
# Terminal 1: Start backend
cd backend-example
npm install && npm start
# Terminal 2: Start example app
npm install && npm run dev🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🆘 Support
For support, please:
- Check the backend-example for implementation reference
- Review the error handling in the example app
- Ensure your backend service is properly configured
- Verify your API token is valid and properly formatted
🔗 Links
⚠️ 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.
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
npm install @rhushya/calculator-componentAll required dependencies (@rhushya/add, @rhushya/subtract, @rhushya/multiply, @rhushya/divide) will be automatically installed.
Usage
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
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:
- Enter the first number in the top input field
- Enter the second number in the second input field
- Select an operation (+, -, ×, ÷) by clicking on the respective button
- The selected operation button will be highlighted
- Click the "Compute" button to perform the calculation
- The result will be displayed below with the complete calculation shown
- 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
<Calculator
style={{
backgroundColor: '#f8f9fa',
borderRadius: '12px',
boxShadow: '0 8px 16px rgba(0,0,0,0.1)'
}}
/>Custom Classes with CSS
<Calculator className="my-custom-calculator" />/* 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
- Clone the repository
- Install dependencies:
npm install
Development Commands
# Run development build with watch mode
npm run dev
# Build the component for production
npm run buildPublishing
To build and publish a new version of the component:
- Update the version in package.json
- Update the README.md with the new version number
- Run the following commands:
# Build the component
npm run build
# Publish to npm registry
npm publish --access publicLicense
MIT © Rhushya
Author
Created by Rhushya
Contributing
Contributions, issues, and feature requests are welcome! Feel free to check the issues page.
Support
If you encounter any problems or have questions, please open an issue.
