npm package: @raphab3/hermes-notifier
Description: JavaScript/React plugin for Hermes notifications system with SSE and push notification support
Author: Rafael Batista
Latest version: 1.1.0

# Hermes Notifier - JavaScript/React Plugin

A JavaScript library for integrating real-time notifications from the Hermes notification system into web applications using Server-Sent Events (SSE).

## Features

- 🔄 **Real-time notifications** via Server-Sent Events (SSE)
- ⚛️ **React hooks** for easy integration
- 🎨 **Pre-built components** with customizable styling
- 🔐 **Token-based authentication**
- 🔄 **Automatic reconnection** with exponential backoff
- 📱 **Responsive design** with mobile support
- 🌙 **Dark mode** support
- 📊 **Connection status** monitoring
- 🎯 **TypeScript** support

## Installation

```bash
npm install hermes-notifier
```

Or with Yarn:

```bash
yarn add hermes-notifier
```

## Quick Start

### Basic JavaScript Usage

```javascript
import HermesNotifier from 'hermes-notifier';

const notifier = new HermesNotifier({
  baseUrl: 'http://localhost:8000',
  token: 'your-api-token',
  userId: 'user-123',
});

// Subscribe to notifications
notifier.onNotification((notification) => {
  console.log('New notification:', notification);
  // Display notification to user
});

// Connect to the notification stream
await notifier.connect();
```

### React Hook Usage

```jsx
import React, { useEffect } from 'react';
import { useHermesNotifications } from 'hermes-notifier/react-hooks';
import 'hermes-notifier/styles.css';

function App() {
  const {
    notifications,
    connectionStatus,
    unreadCount,
    connect,
    disconnect,
    markAsRead,
  } = useHermesNotifications({
    baseUrl: 'http://localhost:8000',
    token: 'your-api-token',
    userId: 'user-123',
  });

  useEffect(() => {
    connect();
    return () => disconnect();
  }, []);

  return (
    <div>
      <h1>My App</h1>
      <div>
        Connection: {connectionStatus.connected ? 'Connected' : 'Disconnected'}
        | Unread: {unreadCount}
      </div>
      
      <div>
        {notifications.map((notification) => (
          <div key={notification.id}>
            <h3>{notification.title}</h3>
            <p>{notification.body}</p>
            {!notification.is_read && (
              <button onClick={() => markAsRead(notification.id)}>
                Mark as Read
              </button>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}
```

### Using Pre-built Components

```jsx
import React, { useEffect } from 'react';
import { useHermesNotifications } from 'hermes-notifier/react-hooks';
import { NotificationList, ConnectionStatus } from 'hermes-notifier/react-components';
import 'hermes-notifier/styles.css';

function NotificationCenter() {
  const {
    notifications,
    connectionStatus,
    connect,
    disconnect,
    markAsRead,
  } = useHermesNotifications({
    baseUrl: 'http://localhost:8000',
    token: 'your-api-token',
    userId: 'user-123',
  });

  useEffect(() => {
    connect();
    return () => disconnect();
  }, []);

  return (
    <div>
      <ConnectionStatus {...connectionStatus} />
      <NotificationList
        notifications={notifications}
        onMarkAsRead={markAsRead}
        maxItems={10}
      />
    </div>
  );
}
```

## API Reference

### HermesNotifier Class

#### Constructor

```typescript
new HermesNotifier(config: HermesConfig)
```

**HermesConfig:**
- `baseUrl` (string): Base URL of the Hermes API
- `token` (string): Authentication token
- `userId` (string): User ID to receive notifications for
- `reconnectDelay` (number, optional): Delay between reconnection attempts (default: 5000ms)
- `maxReconnectAttempts` (number, optional): Maximum reconnection attempts (default: 10)

#### Methods

- `connect()`: Connect to the notification stream
- `disconnect()`: Disconnect from the stream
- `isConnected()`: Check connection status
- `onNotification(handler)`: Subscribe to notification events
- `onConnectionChange(handler)`: Subscribe to connection status changes
- `onError(handler)`: Subscribe to error events
- `markAsRead(notificationId)`: Mark a notification as read
- `getUnreadCount()`: Get unread notification count
- `sendTestNotification(title, body)`: Send a test notification

### React Hooks

#### useHermesNotifications

Main hook for managing notifications in React components.

```typescript
const {
  notifications,
  connectionStatus,
  unreadCount,
  connect,
  disconnect,
  markAsRead,
  clearNotifications,
  sendTestNotification,
  isConnected,
} = useHermesNotifications(config);
```

#### useLatestNotification

Simplified hook that only tracks the latest notification.

```typescript
const {
  latestNotification,
  connectionStatus,
  connect,
  disconnect,
  clearLatest,
  isConnected,
} = useLatestNotification(config);
```

### React Components

#### NotificationItem

Display a single notification.

```jsx
<NotificationItem
  notification={notification}
  onMarkAsRead={handleMarkAsRead}
  onClose={handleClose}
  autoClose={true}
  autoCloseDelay={5000}
/>
```

#### NotificationList

Display a list of notifications.

```jsx
<NotificationList
  notifications={notifications}
  onMarkAsRead={handleMarkAsRead}
  onClose={handleClose}
  maxItems={10}
/>
```

#### NotificationToast

Display notifications as toast messages.

```jsx
<NotificationToast
  notification={notification}
  position="top-right"
  autoClose={true}
  onClose={handleClose}
/>
```

#### ConnectionStatus

Display connection status indicator.

```jsx
<ConnectionStatus
  connected={connectionStatus.connected}
  reconnecting={connectionStatus.reconnecting}
  error={connectionStatus.error}
/>
```

## Authentication

The plugin uses token-based authentication. You need to obtain a token from the Hermes API:

```javascript
// Get a token from your Hermes backend
const response = await fetch('http://localhost:8000/api/v1/tokens/', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    name: 'My App Token',
    permissions: {
      can_send_notifications: true,
      can_read_notifications: true,
    },
    expires_in_days: 30,
  }),
});

const { token } = await response.json();
```

## Styling

The plugin includes default CSS styles that you can import:

```javascript
import 'hermes-notifier/styles.css';
```

### Custom Styling

You can override the default styles by targeting the CSS classes:

```css
.hermes-notification {
  /* Custom notification styling */
}

.hermes-notification-critical {
  /* Custom critical priority styling */
}

.hermes-toast {
  /* Custom toast styling */
}
```

## Configuration Examples

### Basic Configuration

```javascript
const config = {
  baseUrl: 'http://localhost:8000',
  token: 'your-token-here',
  userId: 'user-123',
};
```

### Production Configuration

```javascript
const config = {
  baseUrl: 'https://notifications.yourapp.com',
  token: process.env.REACT_APP_HERMES_TOKEN,
  userId: getCurrentUserId(),
  reconnectDelay: 3000,
  maxReconnectAttempts: 15,
};
```

## Error Handling

```javascript
const notifier = new HermesNotifier(config);

notifier.onError((error) => {
  console.error('Notification error:', error);
  // Handle error (show user message, retry, etc.)
});

notifier.onConnectionChange((status) => {
  if (status.error) {
    console.error('Connection error:', status.error);
  }
});
```

## Browser Support

- Chrome 60+
- Firefox 55+
- Safari 11+
- Edge 79+

Server-Sent Events are supported in all modern browsers. For older browsers, consider using a polyfill.

## Development

To build the plugin locally:

```bash
npm install
npm run build
```

To run tests:

```bash
npm test
```

## License

MIT License - see LICENSE file for details.

## Support

For issues and questions, please visit the [GitHub repository](https://github.com/raphab3/hermes-notifier).