Pan Product Analytics

repository·main·Indexed 23 days ago

https://github.com/panphp/pan

A lightweight, privacy-focused PHP product analytics library for Laravel 11.0+ and PHP 8.3+. Pan tracks user interactions—clicks, hovers, and impressions—via the `data-pan` HTML attribute without collecting personally identifiable information. It features a client-side JavaScript library that batches events using navigator.sendBeacon and integrates with Inertia.js and Livewire. Includes Artisan commands for visualizing, filtering, and managing analytics data, as well as configuration options for whitelisting events and setting record limits.

Tokens
2.1K
Snippets
8
Records
18
Agent score
78%

What's inside panphp/pan

  1. How Pan works

    main

    Pan operates using a two-part system:

    1. Client-side: A lightweight JavaScript library is injected into your HTML via middleware. It listens for viewed, clicked, or hovered events on elements with data-pan attributes. Events are batched to minimize server requests and do not collect personal information (no IP addresses or user agents).
    2. Server-side: The library sends data to your Laravel application. Pan only stores the analytic name and a counter for each event type. It does not track user identity.
  2. Track events using the `data-pan` attribute

    main

    Pan tracks impressions, hovers, and clicks automatically by listening for the data-pan attribute on HTML elements.

    Important: Event names must only contain letters, numbers, dashes (-), and underscores (_).

    Example of tracking different tabs or buttons:

    <div>
        <button data-pan="tab-1">Tab 1</button>
        <button data-pan="tab-2">Tab 2</button>
    </div>
    <button data-pan="tab-1">Tab 1</button>
  3. Integrate Pan with Filament

    main

    You can track Filament actions by passing the data-pan attribute through the extraAttributes method.

    Track a specific action:

    Action::make('subscribe')
        ->extraAttributes(['data-pan' => 'subscribe-button'])

    Track all actions globally: Add this to a service provider's boot method to automatically track every action using its label as the analytic name:

    use Filament\Actions\Action;
    
    public function boot(): void
    {
        Action::configureUsing(function (Action $action): void {
            $action->extraAttributes(fn () => ['data-pan' => $action->getLabel()]);
        });
    }
  4. Install Pan in a Laravel project

    main

    To use Pan, you must first require the package via Composer and then run the installation command to set up the necessary Laravel components.

    Requirements:

    • PHP 8.3+
    • Laravel 11.0+

    Steps:

    1. Install the package:
      composer require panphp/pan
    2. Run the Pan installer:
      php artisan install:pan
    composer require panphp/pan
    php artisan install:pan
  5. Configure the Pan route prefix

    main

    The default route for tracking events is /pan. You can change this using PanConfiguration::routePrefix. If you set the prefix to internal-analytics, the tracking endpoint will be /internal-analytics/events.

    PanConfiguration::routePrefix('internal-analytics');
  6. Whitelist or limit analytics via PanConfiguration

    main

    By default, Pan limits the number of analytics records to 50 to prevent unwanted data from bad actors. You can manage this using PanConfiguration in your application (e.g., in a Service Provider).

    Whitelist specific analytics: Only the names provided in the array will be stored.

    use Pan\PanConfiguration;
    
    PanConfiguration::allowedAnalytics([
        'tab-profile',
        'tab-settings',
    ]);

    Set a custom maximum limit:

    PanConfiguration::maxAnalytics(10000);

    Allow unlimited analytics:

    PanConfiguration::unlimitedAnalytics();
  7. Track product analytics using data-pan attributes

    main

    The Pan client-side library automatically tracks user interactions (clicks, hovers, and impressions) for any HTML element that has a data-pan attribute.

    How to use

    To track an element, simply add the data-pan attribute to the HTML tag. The value of the attribute will be used as the name of the event sent to your analytics backend.

    • Clicks: Triggered when a user clicks an element with data-pan.
    • Hovers: Triggered when a user moves their mouse over an element with data-pan.
    • Impressions: Triggered when an element with data-pan becomes visible in the DOM.

    Example

    <!-- Track a button click -->
    <button data-pan="signup-button">Sign Up</button>
    
    <!-- Track a product card hover and impression -->
    <div data-pan="product-card-123">
        <h3>Premium Widget</h3>
    </div>

    Important Notes

    • Uniqueness: If you use the same data-pan name for multiple elements on a page, the library will log a warning in the console: PAN: Multiple (X) elements with the same name 'name' found. It is best practice to use unique names for specific elements.
    • Visibility: Impressions are only recorded if the element is visible (using checkVisibility()).
    • Batching: Events are queued and sent in batches via navigator.sendBeacon to minimize network overhead, typically with a 1-second delay between commits.
  8. Track product analytics using the `data-pan` attribute

    main

    Pan provides automatic client-side event tracking by observing elements with the data-pan attribute. You do not need to call JavaScript functions manually to track standard interactions; simply add the attribute to your HTML elements.

    Supported Event Types

    • Impression: Automatically tracked when an element with data-pan becomes visible in the DOM.
    • Click: Tracked when a user clicks an element containing the data-pan attribute.
    • Hover: Tracked when a user performs a mouseover event on an element with the attribute.

    Implementation Details

    • Events are queued and sent to the server via navigator.sendBeacon to ensure delivery even during page unloads.
    • Events are batched and sent every 1000ms to optimize network usage.
    • The library automatically handles DOM changes via a MutationObserver and integrates with Inertia.js (inertia:start) and Livewire (livewire:navigated) to reset tracking state during single-page application navigations.
  9. Configure the Pan client via `window.__pan`

    main

    The Pan client initializes using a global __pan object on the window. This object holds configuration injected by the server-side implementation.

    Configuration Keys

    • csrfToken: The CSRF token used for authenticating event submissions.
    • routePrefix: The URL prefix used for the analytics endpoint (e.g., if prefix is api/pan, events are sent to /api/pan/events).

    Internal State

    The __pan object also maintains references to active listeners and observers, which are cleaned up automatically if the script is re-initialized.

  10. Flush or delete analytics via Artisan commands

    main

    Use these commands to manage your stored analytics data.

    Flush all analytics: Clears all analytics records.

    php artisan pan:flush

    Delete a specific analytic: Delete a record by its unique ID.

    php artisan pan:delete <id>
  11. Visualize product analytics

    main

    Use the pan Artisan command to view a table of the analytics you have been tracking in your terminal.

    View all analytics:

    php artisan pan

    Filter analytics by name:

    php artisan pan --filter=tab-profile