npm package: @numinstante/patience-engine-react
Description: [![NPM Version](https://img.shields.io/npm/v/@numinstante/patience-engine-react.svg)](https://www.npmjs.com/package/@numinstante/patience-engine-react) [![Build Status](https://img.shields.io/travis/com/numinstante/patience-engine-react.svg)](https://trav
Latest version: 0.1.6

# @numinstante/patience-engine-react

[![NPM Version](https://img.shields.io/npm/v/@numinstante/patience-engine-react.svg)](https://www.npmjs.com/package/@numinstante/patience-engine-react)
[![Build Status](https://img.shields.io/travis/com/numinstante/patience-engine-react.svg)](https://travis-ci.com/numinstante/patience-engine-react)
[![License](https://img.shields.io/npm/l/@numinstante/patience-engine-react.svg)](https://opensource.org/licenses/MIT)

`@numinstante/patience-engine-react` is the official tracking library for the **Patience Engine** for React applications. It provides a simple and idiomatic way to collect user behavior events, using FingerprintJS for anonymous identification.

## Table of Contents

1.  [Installation](#installation)
    - [Optional Dependencies](#optional-dependencies)
2.  [Quick Start](#quick-start)
3.  [Architecture & Concepts](#architecture--concepts)
4.  [API Reference](#api-reference)
    - [Page Tracking Components](#page-tracking-components)
    - [PatienceProvider](#patienceprovider)
    - [usePatience](#usepatience)
5.  [Publishing a Scoped Package](#publishing-a-scoped-package)
6.  [Contributing](#contributing)
7.  [License](#license)

## Installation

To install the library and its main dependency, FingerprintJS:

```bash
npm install @numinstante/patience-engine-react @fingerprintjs/fingerprintjs
```

### Optional Dependencies

Depending on your routing library, you may need to install additional dependencies for page tracking:

- For React Router applications:
  ```bash
  npm install react-router-dom
  ```

- For Next.js applications:
  ```bash
  npm install next
  ```

These dependencies are optional and only required if you plan to use the corresponding page tracking components. The library is designed to work with either routing system without requiring both dependencies to be installed.

> **Note**: The library will automatically detect which routing library is available in your project. If you're using Next.js without react-router-dom installed, the library will still work correctly and will not throw any errors related to missing dependencies.

## Quick Start

To start using the library, wrap your main application with the `PatienceProvider` and use the `usePatience` hook in any child component.

1. Set up the Provider in your `main.tsx` or `index.tsx`:

```js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { PatienceProvider } from '@numinstante/patience-engine-react';

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <PatienceProvider 
      apiKey="YOUR_PUBLIC_API_KEY" 
      endpoint="[https://api.patience-engine.com/events](https://api.patience-engine.com/events)"
    >
      <App />
    </PatienceProvider>
  </React.StrictMode>
);
```

2. Use the Hook in a Component:

```js
import { usePatience } from '@numinstante/patience-engine-react';

function MyAwesomeComponent() {
  const { track, visitorId, identify } = usePatience();

  const handleButtonClick = () => {
    // Sends a track event with a custom payload
    track('button_signup_clicked', { variant: 'primary', plan: 'free' });
  };

  return (
    <div>
      <p>Your anonymous visitor ID is: {visitorId || 'Loading...'}</p>
      <button onClick={handleButtonClick}>Sign Up</button>
    </div>
  );
}
```

## Architecture & Concepts
The library is designed to be efficient and easy to use, following the best practices of the React ecosystem. The architecture is based on three pillars: the Provider, the Context, and the Hook.

* `PatienceProvider`: This is the brain of the library. It wraps your application and is responsible for all the initialization logic (loading FingerprintJS, getting the visitorId, configuring the API) only once.
* `PatienceContext`: Acts as an internal transport channel, making the state and functions from the provider available to the entire component tree efficiently.
* `usePatience()`: This is the public interface and the correct way to access the library's functionality from within your components.

This structure ensures that the heavy initialization logic runs only once, while access to data and functions is lightweight and performant.

## API Reference

### Page Tracking Components

The library provides components for automatic page view tracking in different routing libraries:

#### `<ReactRouterPageTracker />`

This component automatically tracks page views in applications using React Router v6+.

**Installation:**

```bash
# React Router is an optional peer dependency
npm install react-router-dom
```

**Usage:**

```jsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { ReactRouterPageTracker } from '@numinstante/patience-engine-react';

function App() {
  return (
    <BrowserRouter>
      <ReactRouterPageTracker />
      <Routes>
        {/* Your routes */}
      </Routes>
    </BrowserRouter>
  );
}
```

**Fallback Behavior:**

If you import `ReactRouterPageTracker` in a project where `react-router-dom` is not installed, the library will provide a fallback component that logs a warning to the console but doesn't break your application. This is useful in environments where you might be using the library with Next.js instead of React Router.

#### `<NextJsPageTracker />`

This component automatically tracks page views in applications using Next.js 13+ App Router.

**Installation:**

```bash
# Next.js is an optional peer dependency
npm install next
```

**Usage:**

```jsx
// app/layout.tsx
import { NextJsPageTracker } from '@numinstante/patience-engine-react';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <NextJsPageTracker />
        {children}
      </body>
    </html>
  );
}
```

### `<PatienceProvider />`
Props that the component accepts:

| Prop     | Type      | Required | Description                                     |
|----------|-----------|----------|-------------------------------------------------|
| apiKey   | string    | Yes      | Your public API key from the Patience Engine.   |
| endpoint | string    | Yes      | The full URL of your event ingestion endpoint.  |
| children | ReactNode | Yes      | The child components of your React application. |
| options  | Object    | No       | Optional configuration options (see below).     |

#### Options Object

| Option   | Type    | Default        | Description                                     |
|----------|---------|----------------|-------------------------------------------------|
| disabled | boolean | false          | If true, tracking will be disabled.             |
| cookie   | Object  | (see below)    | Configuration for the visitorId cookie.         |

#### Cookie Object

| Option  | Type   | Default          | Description                             |
|---------|--------|------------------|-----------------------------------------|
| name    | string | "__patience_vid" | The name of the cookie.                 |
| expires | number | 365              | The cookie's expiration period in days. |
| domain  | string | undefined        | The domain to set the cookie on.        |

### `usePatience()`
Hook that returns an object with the following properties:

| Property  | Type     | Description                                                |
|-----------|----------|------------------------------------------------------------|
| visitorId | string   | The unique identifier for the anonymous visitor.           |
| disabled  | boolean  | Indicates whether tracking is disabled.                    |
| track     | function | Function to send custom events to the Patience Engine.     |
| identify  | function | Function to associate an anonymous visitor with a user ID. |
| reset     | function | Function to clear user identification (logout).            |

#### `track(eventName, payload)`
Sends a custom event to the Patience Engine.

| Parameter | Type   | Required | Description                                      |
|-----------|--------|----------|--------------------------------------------------|
| eventName | string | Yes      | A string that identifies the event.              |
| payload   | object | No       | A JSON-serializable object with custom data.     |

Example:
```js
const { track } = usePatience();

// Track a button click with additional data
track('button_clicked', { 
  buttonId: 'signup',
  variant: 'primary',
  position: 'header'
});
```

#### `identify(userId, traits)`
Associates the current anonymous visitor with a permanent user ID and records their traits.

| Parameter | Type   | Required | Description                                                |
|-----------|--------|----------|------------------------------------------------------------|
| userId    | string | Yes      | The permanent, unique identifier for the user.             |
| traits    | object | No       | A JSON-serializable object with user attributes.           |

Example:
```js
const { identify } = usePatience();

// After user login, associate the anonymous visitor with the authenticated user
identify('user_123', { 
  name: 'Jane Doe',
  email: 'jane.doe@example.com',
  plan: 'premium',
  signupDate: '2023-01-15'
});
```

#### `reset()`
Clears the currently identified user's session, reverting the library's tracking state back to being purely anonymous without losing the persistent anonymous `visitorId`.

This function takes no parameters and returns void.

Example:
```js
const { reset } = usePatience();

// When user logs out, clear their identification
function handleLogout() {
  // First, handle your application's logout logic
  await api.logout();

  // Then reset the Patience Engine identification
  reset();

  // Finally, redirect the user
  navigate('/login');
}
```


## Publishing a Scoped Package

This package is published under the `@numinstante` scope on NPM. To publish a new version, follow these steps:

1. Ensure you have permission to publish packages under the `@numinstante` organization/scope on NPM.
2. Authenticate with your NPM account using `npm login`.
3. Make sure your local `main` branch is up-to-date with the remote repository and all tests are passing:
   ```bash
   git pull origin main
   npm run lint
   ```

4. Determine the type of release based on the changes made since the last release:
   - **Patch**: Bug fixes and small changes that don't affect the API
   - **Minor**: New features that don't break backward compatibility
   - **Major**: Breaking changes

5. Run one of the following commands to increment the version number:
   ```bash
   # For bug fixes and small changes
   npm run release:patch

   # For new features that don't break backward compatibility
   npm run release:minor

   # For breaking changes
   npm run release:major
   ```
   This will update the version in package.json and create a Git tag.

6. Build the project:
   ```bash
   npm run build
   ```

7. Perform a dry run to verify which files will be included in the package:
   ```bash
   npm run publish:dry-run
   ```

8. If the files look correct, publish the package to NPM:
   ```bash
   npm run publish:public
   ```

9. Push the new commit and tag to the remote Git repository:
   ```bash
   git push
   git push --tags
   ```

If the files don't look correct during the dry run, you can revert the version change:
```bash
git reset --hard HEAD~1
git tag -d v<version>
```

The release process will:
- Increment the version number in `package.json` according to semantic versioning
- Create a Git tag for the new version
- Build the distributable files
- Publish the package to NPM with public access

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License
MIT