npm package: @sartecheasy/common-components
Description: Common React components for Sartech Easy projects
Author: Sartech Easy Solutions
Latest version: 1.1.10

# @sartecheasySolutions/common-components

A comprehensive collection of reusable React components for Sartech Easy projects.

## 🚀 Installation

```bash
npm install @sartecheasySolutions/common-components
```

## 📦 Dependencies

This package requires the following peer dependencies to be installed in your project:

```json
{
  "react": "^17.0.0 || ^18.0.0",
  "react-dom": "^17.0.0 || ^18.0.0",
  "react-bootstrap": "^2.8.0",
  "react-icons": "^4.10.0",
  "react-lazyload": "^3.1.0",
  "react-meta-tags": "^0.7.4",
  "react-router-dom": "^6.8.0"
}
```

**Important:** These dependencies are marked as peer dependencies to avoid bundling them with the package. This means you need to install them separately in your project:

```bash
npm install react react-dom react-bootstrap react-icons react-lazyload react-meta-tags react-router-dom
```

### Why Peer Dependencies?

This approach provides several benefits:

- **Smaller package size**: The package doesn't include large dependencies like React Bootstrap
- **Version flexibility**: You can use the versions of dependencies that work best with your project
- **No duplicate dependencies**: Prevents multiple versions of the same library in your node_modules
- **Better tree shaking**: Allows bundlers to optimize your final bundle more effectively

The package only includes these internal dependencies:

```json
{
  "js-cookie": "^3.0.5",
  "prop-types": "^15.8.1"
}
```

## 🎯 Available Components

### 1. SearchBanner

A customizable search banner component with icon and form handling.

```jsx
import { SearchBanner } from '@sartecheasy/common-components';

<SearchBanner
  title="Search Products"
  placeholder="Enter product name..."
  onSearch={(term) => console.log('Searching for:', term)}
  showIcon={true}
/>;
```

**Props:**

- `title` (string): Banner title
- `placeholder` (string): Input placeholder text
- `onSearch` (function): Search callback function
- `className` (string): Additional CSS classes
- `showIcon` (boolean): Show/hide search icon

### 2. UploadImage

A drag-and-drop image upload component with preview and validation.

```jsx
import { UploadImage } from '@sartecheasy/common-components';

<UploadImage
  onImageUpload={(files) => console.log('Uploaded:', files)}
  multiple={true}
  maxSize={5 * 1024 * 1024} // 5MB
  accept="image/*"
  maxFiles={5}
  showPreview={true}
/>;
```

**Props:**

- `onImageUpload` (function): Upload callback
- `multiple` (boolean): Allow multiple files
- `maxSize` (number): Maximum file size in bytes
- `accept` (string): Accepted file types
- `maxFiles` (number): Maximum number of files
- `showPreview` (boolean): Show file previews

### 3. ImageUpload (FileUpload)

A comprehensive file upload component with image compression and validation.

```jsx
import { ImageUpload } from '@sartecheasy/common-components';

<ImageUpload
  id="fileInput"
  cid="fileInput"
  label="Upload Image"
  fileType=".png,.jpg,.jpeg,.bmp,.pdf"
  imgName="profile_"
  typ="profile"
  uploading={(status) => console.log('Uploading:', status)}
  responseUrl={(url) => console.log('Upload URL:', url)}
  image="https://example.com/image.jpg"
  hide={false}
  imgValidation={false}
/>;
```

**Props:**

- `id` (string): Input element ID
- `cid` (string): Control ID
- `label` (string): Form label
- `fileType` (string): Accepted file extensions
- `imgName` (string): File name prefix
- `typ` (string): Upload type
- `uploading` (function): Upload status callback
- `responseUrl` (function): Upload URL callback
- `image` (string): Current image URL
- `hide` (boolean): Hide component
- `imgValidation` (boolean): Enable validation

### 4. FormValidations

A comprehensive set of form validation utilities.

```jsx
import {
  validateEmail,
  validatePassword,
  validateForm,
} from '@sartecheasy/common-components';

// Email validation
const isValidEmail = validateEmail('user@example.com');

// Password validation
const passwordResult = validatePassword('MyPassword123!', {
  minLength: 8,
  requireUppercase: true,
  requireLowercase: true,
  requireNumbers: true,
  requireSpecialChars: true,
});

// Form validation
const formData = {
  email: 'user@example.com',
  password: 'MyPassword123!',
};

const validationRules = {
  email: [validateEmail],
  password: [(value) => validatePassword(value, { minLength: 8 })],
};

const result = validateForm(formData, validationRules);
```

**Available Functions:**

- `validateEmail(email)`
- `validatePassword(password, options)`
- `validatePhone(phone, country)`
- `validateURL(url)`
- `validateRequired(value, fieldName)`
- `validateMinLength(value, minLength, fieldName)`
- `validateMaxLength(value, maxLength, fieldName)`
- `validateNumber(value, options)`
- `validateDate(date, options)`
- `validateCreditCard(cardNumber)`
- `validateForm(formData, validationRules)`
- `validateField(value, validators, fieldName)`

### 5. DataLoader

A flexible loading component with customizable states and styling.

```jsx
import { DataLoader } from '@sartecheasy/common-components';

<DataLoader
  loading={isLoading}
  noData={!hasData}
  loadingText="Loading products..."
  noDataText="No products found"
  variant="primary"
  size="md"
>
  {/* Your content when not loading */}
  <div>Your data content here</div>
</DataLoader>;
```

**Props:**

- `loading` (boolean): Loading state
- `noData` (boolean): No data state
- `loadingText` (string): Loading message
- `noDataText` (string): No data message
- `variant` (string): Spinner variant
- `size` (string): Spinner size
- `className` (string): Additional CSS classes
- `children` (ReactNode): Content when not loading

### 6. Page404

A customizable 404 error page component.

```jsx
import { Page404 } from '@sartecheasy/common-components';

<Page404
  title="Page Not Found"
  description="The page you are looking for doesn't exist"
  showBackButton={true}
  showHomeButton={true}
  backButtonText="Go Back"
  homeButtonText="Go Home"
  customHeight="100vh"
/>;
```

**Props:**

- `title` (string): Page title
- `description` (string): Error description
- `showBackButton` (boolean): Show back button
- `showHomeButton` (boolean): Show home button
- `backButtonText` (string): Back button text
- `homeButtonText` (string): Home button text
- `customHeight` (string): Custom height

### 7. CurrencySymbol

A flexible currency symbol component supporting multiple currencies.

```jsx
import { CurrencySymbol } from '@sartecheasy/common-components';

<CurrencySymbol currency="USD" size="lg" showCode={true} />
<CurrencySymbol currency="EUR" size="md" />
<CurrencySymbol currency="INR" size="sm" />
```

**Props:**

- `currency` (string): Currency code (INR, USD, EUR, GBP, etc.)
- `size` (string): Size variant ('sm', 'md', 'lg')
- `showCode` (boolean): Show currency code
- `className` (string): Additional CSS classes

### 8. Popup Components

#### ImagePopup

```jsx
import { ImagePopup } from '@sartecheasy/common-components';

<ImagePopup
  show={showPopup}
  imgUrl="https://example.com/image.jpg"
  close={() => setShowPopup(false)}
/>;
```

#### AlertPopup

```jsx
import { AlertPopup } from '@sartecheasy/common-components';

<AlertPopup
  show={showAlert}
  title="Warning"
  description="This action cannot be undone."
/>;
```

#### ConfirmPopup

```jsx
import { ConfirmPopup } from '@sartecheasy/common-components';

<ConfirmPopup
  show={showConfirm}
  title="Confirm Action"
  status="success"
  buttonTxt="Cancel"
  buttonTxt2="Confirm"
  close={() => setShowConfirm(false)}
  yes={() => handleConfirm()}
/>;
```

#### DeletePopup

```jsx
import { DeletePopup } from '@sartecheasy/common-components';

<DeletePopup
  show={showDelete}
  typ="promo"
  close={() => setShowDelete(false)}
  yes={() => handleDelete()}
/>;
```

#### ErrorFallback

```jsx
import { ErrorFallback } from '@sartecheasy/common-components';

<ErrorFallback error={error} resetErrorBoundary={resetError} />;
```

## 🎨 Styling

The components use React Bootstrap for styling. Make sure to include Bootstrap CSS in your project:

```html
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
/>
```

Or install via npm:

```bash
npm install bootstrap
```

And import in your main file:

```jsx
import 'bootstrap/dist/css/bootstrap.min.css';
```

## 🔧 Development

### Building the Package

```bash
npm run build
```

### Development Mode

```bash
npm run dev
```

### Clean Build

```bash
npm run clean
```

## 📝 Usage Examples

### Complete Form with Validation

```jsx
import React, { useState } from 'react';
import {
  UploadImage,
  FormValidations,
  AlertPopup,
} from '@sartecheasy/common-components';

const MyForm = () => {
  const [formData, setFormData] = useState({
    email: '',
    password: '',
    image: null,
  });
  const [errors, setErrors] = useState({});
  const [showAlert, setShowAlert] = useState(false);

  const handleSubmit = () => {
    const validationRules = {
      email: [FormValidations.validateEmail],
      password: [
        (value) => FormValidations.validatePassword(value, { minLength: 8 }),
      ],
    };

    const result = FormValidations.validateForm(formData, validationRules);

    if (result.isFormValid) {
      // Submit form
      console.log('Form is valid:', formData);
    } else {
      setErrors(result.errors);
      setShowAlert(true);
    }
  };

  return (
    <div>
      <UploadImage
        onImageUpload={(file) => setFormData({ ...formData, image: file })}
        multiple={false}
        maxSize={2 * 1024 * 1024} // 2MB
      />

      <AlertPopup
        show={showAlert}
        title="Validation Error"
        description="Please check your input and try again."
      />

      <button onClick={handleSubmit}>Submit</button>
    </div>
  );
};
```

## 🤝 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, email support@sartecheasy.com or create an issue in the GitHub repository.