npm package: @orionarm/at
Description: Modern and performant automatic web analytics tracking library
Author: OrionArm
Latest version: 0.0.3

# @orionarm/at

[![npm version](https://badge.fury.io/js/@orionarm/at.svg)](https://badge.fury.io/js/@orionarm/at)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)

Modern and performant **a**uto-**t**racking library for web analytics. Easily track user interactions and viewport visibility with simple HTML attributes.

## Features

- 🎯 **Zero Dependencies** - Lightweight and self-contained
- 🚀 **High Performance** - Uses IntersectionObserver and event delegation
- 📱 **Modern Browser Support** - Built with ES2020+ features with graceful fallbacks
- 🔧 **TypeScript Ready** - Full type definitions included
- 🎨 **Simple API** - Just add HTML attributes to track events
- 🔄 **Dynamic Content Support** - Automatically handles dynamically added elements
- 🧪 **Well Tested** - Comprehensive test suite included

## Installation

Install via npm:

```bash
npm install @orionarm/at
```

Or with yarn:

```bash
yarn add @orionarm/at
```

Or with pnpm:

```bash
pnpm add @orionarm/at
```

**Package Information:**
- 📦 Package: [@orionarm/at](https://www.npmjs.com/package/@orionarm/at)
- 🏷️ Latest Version: ![npm version](https://img.shields.io/npm/v/@orionarm/at)

## Quick Start

```typescript
import { install } from '@orionarm/at';

// Install with a simple tracker function
const uninstall = install((eventName, params) => {
  console.log('Event:', eventName, 'Params:', params);
  // Send to your analytics service
});

// Or with configuration options
const uninstall = install({
  tracker: (eventName, params) => {
    // Your tracking logic here
    analytics.track(eventName, params);
  },
  debug: true, // Enable debug logging
});

// Clean up when needed
uninstall();
```

## Usage

### Click Tracking

Add the `at-click` attribute to any element to track clicks:

```html
<!-- Basic click tracking -->
<button at-click="button_clicked">Click me</button>

<!-- With additional parameters -->
<button 
  at-click="cta_clicked" 
  at-click-json='{"category": "hero", "value": 100}'>
  Get Started
</button>

<!-- One-time tracking (removes attributes after first click) -->
<button 
  at-click="signup_started" 
  at-click-once="true">
  Sign Up
</button>
```

### Viewport Visibility Tracking

Track when elements become visible in the viewport:

```html
<!-- Basic visibility tracking -->
<div at-visit="section_viewed">Important content</div>

<!-- With custom visibility threshold (50% visible) -->
<div 
  at-visit="hero_viewed" 
  at-visit-threshold="50%">
  Hero Section
</div>

<!-- One-time tracking with parameters -->
<div 
  at-visit="feature_seen" 
  at-visit-once="true"
  at-visit-json='{"section": "features", "priority": "high"}'>
  Feature showcase
</div>
```

### Shorthand Attributes

For convenience, you can use shortened attribute names:

```html
<!-- These are equivalent to the longer versions -->
<button 
  at-click="click_event" 
  at-once="true" 
  at-json='{"type": "primary"}'>
  Click me
</button>

<div 
  at-visit="view_event" 
  at-threshold="25%" 
  at-once="true">
  Content
</div>
```

## API Reference

### `install(config)`

Installs the automatic tracking system and returns an uninstall function.

**Parameters:**

- `config` - Can be either:
  - `Tracker` function: `(eventName: string, params?: TrackingParams) => void`
  - `AutoTrackingConfig` object with properties:
    - `tracker`: The tracking function
    - `debug?`: Enable debug logging (default: false)

**Returns:**

- `() => void` - Uninstall function to clean up tracking (same as `uninstall`)
- `undefined` - Only in SSR environments or when DOM is not ready

**Example:**

```typescript
// Simple function
const uninstall = install((eventName, params) => {
  // Your tracking logic
});

// Full configuration
const uninstall = install({
  tracker: (eventName, params) => {
    // Your tracking logic
  },
  debug: true
});

// Clean up when component unmounts or page changes
useEffect(() => {
  const uninstall = install(tracker);
  return uninstall; // React cleanup
}, []);
```

### `uninstall()`

Removes all tracking functionality and cleans up event listeners. This is the same function returned by `install()`.

```typescript
// Method 1: Use the returned function (recommended)
const uninstall = install(tracker);
uninstall();

// Method 2: Call directly (legacy)
uninstall();
```

### Supported Attributes

#### Click Tracking

- `at-click`: Event name to track
- `at-click-once` / `at-once`: Track only once (removes attributes after first trigger)
- `at-click-json` / `at-json`: JSON string with additional parameters

#### Visibility Tracking

- `at-visit`: Event name to track when element becomes visible
- `at-visit-once` / `at-once`: Track only once
- `at-visit-json` / `at-json`: JSON string with additional parameters
- `at-visit-threshold` / `at-threshold`: Visibility threshold (default: 10%)
  - Percentage: `"50%"` (50% of element visible)
  - Decimal: `"0.5"` (50% of element visible)
  - Pixel values are not supported

## Browser Support

- **Modern browsers**: Full support with all features
- **Older browsers**: Graceful degradation
  - Click tracking works everywhere
  - Viewport tracking requires `IntersectionObserver` (polyfill available)
  - Performance optimizations require `requestIdleCallback` (automatic fallback)

## Performance

This library is designed for optimal performance:

- **Event Delegation**: Uses a single click listener for all tracked elements
- **Intersection Observer**: Efficient viewport tracking without scroll events
- **Lazy Processing**: Uses `requestIdleCallback` for non-critical work
- **Memory Efficient**: Uses `WeakMap` and `WeakSet` for element tracking
- **Batch Processing**: Handles multiple DOM mutations efficiently

## Examples

### E-commerce Tracking

```html
<!-- Product views -->
<div 
  at-visit="product_viewed" 
  at-visit-json='{"product_id": "123", "category": "electronics"}'>
  Product details
</div>

<!-- Add to cart -->
<button 
  at-click="add_to_cart" 
  at-click-json='{"product_id": "123", "price": 99.99}'>
  Add to Cart
</button>

<!-- Checkout steps -->
<div 
  at-visit="checkout_step_viewed" 
  at-visit-once="true"
  at-visit-json='{"step": "shipping"}'>
  Shipping information
</div>
```

### Content Engagement

```html
<!-- Article sections -->
<section 
  at-visit="article_section_read" 
  at-visit-threshold="75%"
  at-visit-json='{"section": "introduction"}'>
  Article introduction
</section>

<!-- Social sharing -->
<button 
  at-click="social_share" 
  at-click-json='{"platform": "twitter", "content_type": "article"}'>
  Share on Twitter
</button>

<!-- Newsletter signup -->
<form 
  at-visit="newsletter_form_viewed"
  at-visit-threshold="50%">
  <button 
    at-click="newsletter_signup_attempted"
    type="submit">
    Subscribe
  </button>
</form>
```

## License

MIT License - see LICENSE file for details.

## Contributing

Contributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.

## Changelog

See [CHANGELOG.md](CHANGELOG.md) for a list of changes and versions.

## Development & Collaboration

This project was developed through a collaboration between the author and [Claude Code](https://claude.ai/code), an AI-powered development assistant. Claude Code contributed to:

- Code architecture and implementation
- TypeScript type definitions and best practices
- Test suite development and coverage
- Documentation and API design
- Performance optimizations and modern web standards

The combination of human creativity and AI assistance enabled rapid development while maintaining high code quality and comprehensive testing.