npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@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

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.

npm version License: 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

npm install @rhushya/calculator-component

2. 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 start

3. 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 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

<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

  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

npm run build

Testing

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

  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 file for details.

🆘 Support

For support, please:

  1. Check the 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


⚠️ 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 License

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-component

All 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:

  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

<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

  1. Clone the repository
  2. Install dependencies:
    npm install

Development Commands

# 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:
# Build the component
npm run build

# Publish to npm registry
npm publish --access public

License

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.