npm package: @metadiv-studio/alert
Description: A minimal, theme-agnostic React alert component
Latest version: 0.2.2

# @metadiv-studio/alert

A modern, theme-aware React alert/toast notification system built on top of Sonner. This package provides a clean API for displaying various types of notifications with support for actions, descriptions, and internationalization through React Context.

## 🚀 Installation

```bash
npm i @metadiv-studio/alert
```

## 📋 Prerequisites

This package requires the following peer dependencies:
- React 18+
- React DOM 18+

## 🎯 Quick Start

### 1. Wrap Your App with AlertProvider

**Important**: You must wrap your application with the `AlertProvider` component to enable the alert context throughout your app.

```tsx
import { AlertProvider } from '@metadiv-studio/alert';

function App() {
  return (
    <AlertProvider>
      {/* Your app content goes here */}
      <div>Your app content</div>
    </AlertProvider>
  );
}
```

### 2. Use the Alert Context in Your Components

```tsx
import { useAlertContext } from '@metadiv-studio/alert';

function MyComponent() {
  const { success, error, info, notify } = useAlertContext();

  const handleSuccess = () => {
    success('Operation completed successfully!');
  };

  const handleError = () => {
    error('Something went wrong!');
  };

  const handleInfo = () => {
    info('New update available!');
  };

  const handleNotify = () => {
    notify('You have a new message!');
  };

  return (
    <div>
      <button onClick={handleSuccess}>Show Success</button>
      <button onClick={handleError}>Show Error</button>
      <button onClick={handleInfo}>Show Info</button>
      <button onClick={handleNotify}>Show Notify</button>
    </div>
  );
}
```

## 🎨 Alert Types

### Basic Alerts

```tsx
import { useAlertContext } from '@metadiv-studio/alert';

function MyComponent() {
  const { success, error, info, notify } = useAlertContext();

  // Success alert
  success('File uploaded successfully!');

  // Error alert
  error('Upload failed!');

  // Info alert
  info('System maintenance scheduled');

  // General notification
  notify('New message received');
}
```

### Alerts with Descriptions

```tsx
function MyComponent() {
  const { success, error, info, notify } = useAlertContext();

  // Success with description
  success('File uploaded!', 'Your file has been successfully uploaded to the cloud.');

  // Error with description
  error('Upload failed!', 'The file size exceeds the maximum limit of 10MB.');

  // Info with description
  info('Maintenance scheduled!', 'System will be unavailable from 2-4 AM tomorrow.');

  // Notify with description
  notify('Backup completed!', 'Your data has been backed up successfully.');
}
```

### Alerts with Actions

```tsx
function MyComponent() {
  const { success, error, info, notify } = useAlertContext();

  // Success with action button
  success('Action completed successfully!', 'Click to view details', {
    label: 'View Details',
    onClick: () => {
      console.log('View details clicked!');
      // Navigate to details page or perform action
    }
  });

  // Error with retry action
  error('Something went wrong!', 'Click to retry the operation', {
    label: 'Retry',
    onClick: () => {
      console.log('Retry clicked!');
      // Retry the failed operation
    }
  });

  // Info with download action
  info('New update available!', 'Click to download now', {
    label: 'Download',
    onClick: () => {
      console.log('Download clicked!');
      // Trigger download
    }
  });
}
```

### Predefined Success Messages

```tsx
function MyComponent() {
  const { successSave, successDelete } = useAlertContext();

  // Success save message (with internationalization)
  const handleSave = async () => {
    await successSave();
  };

  // Success save with custom action
  const handleSaveWithAction = async () => {
    await successSave({
      label: 'View Changes',
      onClick: () => navigate('/changes')
    });
  };

  // Success delete message
  const handleDelete = async () => {
    await successDelete();
  };

  // Success delete with undo action
  const handleDeleteWithUndo = async () => {
    await successDelete({
      label: 'Undo',
      onClick: () => undoDelete()
    });
  };
}
```

## 🌍 Internationalization

The package supports internationalization through `@metadiv-studio/translation`. For the predefined success messages (`successSave` and `successDelete`), the locale is automatically detected from the translation context.

### Setup for i18n

```tsx
import { TranslationProvider } from '@metadiv-studio/translation';

function App() {
  return (
    <TranslationProvider>
      <AlertProvider>
        {/* Your app content */}
      </AlertProvider>
    </TranslationProvider>
  );
}
```

## 🎨 Theming

The alert system automatically detects and applies your application's theme using `next-themes`. It supports:
- Light theme
- Dark theme
- System theme (follows OS preference)

### Theme Setup

```tsx
import { ThemeProvider } from 'next-themes';
import { AlertProvider } from '@metadiv-studio/alert';

function App() {
  return (
    <ThemeProvider>
      <AlertProvider>
        {/* Your app content */}
      </AlertProvider>
    </ThemeProvider>
  );
}
```

## 📱 Positioning and Styling

- **Position**: All alerts appear in the top-right corner by default (except `notify` which appears in top-center)
- **Duration**: 5 seconds by default
- **Rich Colors**: Enabled by default for better visual hierarchy
- **Responsive**: Automatically adapts to different screen sizes

## 🔧 Advanced Usage

### Multiple Alerts

```tsx
function MyComponent() {
  const { success, info, notify } = useAlertContext();

  const triggerMultipleAlerts = () => {
    // Trigger multiple alerts in sequence
    success('First alert!');
    setTimeout(() => info('Second alert!'), 500);
    setTimeout(() => notify('Third alert!'), 1000);
  };

  const triggerAllTypes = () => {
    // Trigger all types at once
    success('Success alert!');
    error('Error alert!');
    info('Info alert!');
    notify('Notify alert!');
  };
}
```

### Custom Content

```tsx
function MyComponent() {
  const { info, notify } = useAlertContext();

  const showLongMessage = () => {
    info('This is a very long message that demonstrates how the alert system handles extended text content.');
  };

  const showHtmlContent = () => {
    info('Form validation error', 
      <span>Please check the following fields: <strong>Email</strong> and <em>Password</em></span>
    );
  };

  const showEmojis = () => {
    notify('Emojis work! 🎉 🚀 ✨ 🎯 💡');
  };
}
```

### Action Callbacks

```tsx
function MyComponent() {
  const { success, info } = useAlertContext();

  const handleActionWithNavigation = () => {
    success('Action completed!', 'Click to view details', {
      label: 'View Details',
      onClick: () => {
        // Navigate to details
        navigate('/details');
        
        // Show another alert
        info('Navigating to details page...');
      }
    });
  };
}
```

## 📦 Package Structure

```
@metadiv-studio/alert/
├── AlertProvider    # React context provider for alerts
├── useAlertContext # React hook to access alert functions
└── Context Methods:
    ├── success()   # Success notifications
    ├── error()     # Error notifications
    ├── info()      # Information notifications
    ├── notify()    # General notifications
    ├── successSave()    # Predefined save success
    └── successDelete()  # Predefined delete success
```

## 🚨 Important Notes

1. **AlertProvider Placement**: Always wrap your app with `<AlertProvider>`
2. **Context Usage**: Use `useAlertContext()` hook in components to access alert functions
3. **Theme Context**: Ensure `AlertProvider` is wrapped in your theme provider
4. **Translation Setup**: Wrap with `TranslationProvider` for i18n support
5. **Peer Dependencies**: Make sure React 18+ is installed

## 🔍 Troubleshooting

### Alerts not showing?
- Ensure your app is wrapped with `<AlertProvider>`
- Check that you're using `useAlertContext()` hook correctly
- Verify React 18+ is installed

### Theme not working?
- Wrap your app with `ThemeProvider` from `next-themes`
- Ensure `AlertProvider` is inside the theme context

### Internationalization not working?
- Wrap with `TranslationProvider` from `@metadiv-studio/translation`
- Ensure the translation context is properly configured

### Context not available?
- Make sure `useAlertContext()` is called inside a component that's wrapped by `AlertProvider`
- Check that the hook is not called outside of React components

## 📚 Examples

See the [testing page](pages/index.tsx) for comprehensive examples of all alert types and configurations.

## 🤝 Contributing

This package is part of the Metadiv Studio ecosystem. For issues, feature requests, or contributions, please refer to the project repository.

## 📄 License

MIT License - see LICENSE file for details.