# Angular Integration

Add **analytics to your Angular Figma plugin** with the `TodeService`. This guide shows you how to track user actions in Angular-based Figma plugins and widgets.

## Installation

Install the core SDK and Angular adapter:

```bash
npm install @tode-sdk/core @tode-sdk/figma-angular
```

## Setup

### Initialize in Plugin Controller

Set up Tode in your plugin's main code file:

`code.ts`:

```typescript
import { tode } from '@tode-sdk/core';

// Show your Angular UI
figma.showUI(__html__, { width: 400, height: 600 });

// Initialize Tode for Figma plugin analytics
await tode.init({ apiKey: 'your-api-key' });

// Optional: Track plugin open from controller
tode.trackAction('plugin_opened');
```

### Configure Network Access

Add Tode's URLs to your plugin's `manifest.json` to enable analytics requests, and the `currentuser` permission so the SDK can read `figma.currentUser.id`. Without that permission events still arrive, but they are anonymous and the dashboard cannot count unique users. [Learn more about network access](https://developers.figma.com/docs/plugins/making-network-requests/).

```json title="manifest.json"
{
"name": "Your Plugin",
"id": "your-plugin-id",
"api": "1.0.0",
"main": "code.js",
"ui": "index.html",
"permissions": ["currentuser"],
"networkAccess": {
"allowedDomains": [
  "https://processing.usetode.dev",
  "wss://processing.usetode.dev"
]
}
}
```

### No Provider Setup Needed

`TodeService` is provided in the root injector. Inject it where you need it; there is nothing to add to `providers`.

To turn on debug logs or change the ping interval, call `configure()` once, as early as possible:

```typescript title="app.component.ts"
export class AppComponent implements OnInit {
constructor(private todeService: TodeService) {}

ngOnInit(): void {
this.todeService.configure({ debug: true, pingInterval: 5000 });
}
}
```

### Use the Service in Your Components

Inject `TodeService` to track user actions:

`app.component.ts`:

```typescript
import { Component, OnDestroy } from '@angular/core';
import { TodeService } from '@tode-sdk/figma-angular';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-root',
  template: `
    <button (click)="handleExport()" [disabled]="!isReady">
      Export Design
    </button>
    <p>Analytics: {{ isReady ? 'Connected' : 'Connecting...' }}</p>
  `
})
export class AppComponent implements OnDestroy {
  isReady = false;
  private subscription: Subscription;

  constructor(private todeService: TodeService) {
    this.subscription = this.todeService.isReady$.subscribe(
      (ready: boolean) => this.isReady = ready
    );
  }

  handleExport(): void {
    if (this.isReady) {
      this.todeService.trackAction('export_clicked');
    }
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }
}
```

## Service Reference

### TodeService

| Property/Method | Type | Description |
|-----------------|------|-------------|
| `tode` | `Tode` | The Tode instance for direct access |
| `isReady$` | `Observable<boolean>` | Observable of ready state ([`tode.isReady`](https://docs.usetode.dev/api#todeisready)) |
| `isReady` | `boolean` | Current ready state, read synchronously |
| `wsState$` | `Observable<WebSocketState>` | Session connection state: `disconnected`, `connecting`, `connected` or `error` |
| `wsState` | `WebSocketState` | Current connection state, read synchronously |
| `configure(config)` | `method` | Set `debug` and `pingInterval`; call it before the first connection |
| `trackAction(name, options?)` | `method` | Track a simple action ([API](https://docs.usetode.dev/api#todetrackactionactionname)) |
| `trackActionWithMetric(name, value, options?)` | `method` | Track action with numeric value ([API](https://docs.usetode.dev/api#todetrackactionwithmetricactionname-value)) |

Angular cleans the service up itself; there is no `destroy()` to call.

## Examples

### Basic Tracking

`tool-button.component.ts`:

```typescript
import { Component, Input, OnDestroy } from '@angular/core';
import { TodeService } from '@tode-sdk/figma-angular';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-tool-button',
  template: `<button (click)="handleClick()">{{ tool }}</button>`
})
export class ToolButtonComponent implements OnDestroy {
  @Input() tool!: string;
  private isReady = false;
  private subscription: Subscription;

  constructor(private todeService: TodeService) {
    this.subscription = this.todeService.isReady$.subscribe(
      (ready: boolean) => this.isReady = ready
    );
  }

  handleClick(): void {
    // Track which tool was selected in your Figma plugin
    if (this.isReady) {
      this.todeService.trackAction(`tool_selected_${this.tool}`);
    }
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }
}
```

### Track with Metrics

`export-panel.component.ts`:

```typescript
import { Component, OnDestroy } from '@angular/core';
import { TodeService } from '@tode-sdk/figma-angular';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-export-panel',
  template: `
    <button (click)="handleExport()">
      Export {{ selectedItems.length }} Items
    </button>
  `
})
export class ExportPanelComponent implements OnDestroy {
  selectedItems: any[] = [];
  private isReady = false;
  private subscription: Subscription;

  constructor(private todeService: TodeService) {
    this.subscription = this.todeService.isReady$.subscribe(
      (ready: boolean) => this.isReady = ready
    );
  }

  async handleExport(): Promise<void> {
    // Perform export logic...

    // Track export with item count for Figma widget analytics
    if (this.isReady) {
      this.todeService.trackActionWithMetric('items_exported', this.selectedItems.length);
    }
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }
}
```

### Track Feature Views

`feature-view.component.ts`:

```typescript
import { Component, OnInit, OnDestroy } from '@angular/core';
import { TodeService } from '@tode-sdk/figma-angular';
import { Subscription, filter, take } from 'rxjs';

@Component({
  selector: 'app-feature-view',
  template: `<div>Feature Content</div>`
})
export class FeatureViewComponent implements OnInit, OnDestroy {
  private subscription?: Subscription;

  constructor(private todeService: TodeService) {}

  ngOnInit(): void {
    // Track feature view once when Tode is ready
    this.subscription = this.todeService.isReady$.pipe(
      filter((ready: boolean) => ready),
      take(1)
    ).subscribe(() => {
      this.todeService.trackAction('feature_viewed');
    });
  }

  ngOnDestroy(): void {
    this.subscription?.unsubscribe();
  }
}
```

### Using AsyncPipe

```typescript title="async-example.component.ts"
import { Component } from '@angular/core';
import { TodeService } from '@tode-sdk/figma-angular';
import { CommonModule, AsyncPipe } from '@angular/common';

@Component({
  selector: 'app-async-example',
  standalone: true,
  imports: [CommonModule, AsyncPipe],
  template: `
    <button
      (click)="track()"
      [disabled]="!(todeService.isReady$ | async)">
      Track Action
    </button>
    <p>Status: {{ (todeService.isReady$ | async) ? 'Ready' : 'Connecting...' }}</p>
  `
})
export class AsyncExampleComponent {
  constructor(public todeService: TodeService) {}

  track(): void {
    this.todeService.trackAction('button_clicked');
  }
}
```

### Standalone Components

```typescript title="standalone.component.ts"
import { Component, OnDestroy } from '@angular/core';
import { TodeService } from '@tode-sdk/figma-angular';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-standalone',
  standalone: true,
  template: `
    <button (click)="track()" [disabled]="!isReady">
      Track
    </button>
  `
})
export class StandaloneComponent implements OnDestroy {
  isReady = false;
  private subscription: Subscription;

  constructor(private todeService: TodeService) {
    this.subscription = this.todeService.isReady$.subscribe(
      ready => this.isReady = ready
    );
  }

  track(): void {
    if (this.isReady) {
      this.todeService.trackAction('standalone_action');
    }
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }
}
```

## Best Practices

### 1. Always Unsubscribe

```typescript
import { Subscription } from 'rxjs';

export class MyComponent implements OnDestroy {
  private subscription: Subscription;

  constructor(private todeService: TodeService) {
    this.subscription = this.todeService.isReady$.subscribe(...);
  }

  ngOnDestroy(): void {
    // Always clean up subscriptions
    this.subscription.unsubscribe();
  }
}
```

### 2. Use takeUntilDestroyed (Angular 16+)

```typescript
import { Component, DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';

@Component({...})
export class ModernComponent {
  private destroyRef = inject(DestroyRef);
  private todeService = inject(TodeService);
  isReady = false;

  constructor() {
    this.todeService.isReady$
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(ready => this.isReady = ready);
  }
}
```

### 3. Use Descriptive Action Names

```typescript
// Good - clear and descriptive
this.todeService.trackAction('export_to_png');
this.todeService.trackAction('layer_renamed');

// Bad - too vague
this.todeService.trackAction('click');
this.todeService.trackAction('action1');
```

### 4. Prefer AsyncPipe for Templates

```typescript
// Good - automatic subscription management
template: `<button [disabled]="!(todeService.isReady$ | async)">`

// Also good but requires manual unsubscribe
isReady = false;
this.todeService.isReady$.subscribe(r => this.isReady = r);
template: `<button [disabled]="!isReady">`
```

## Next Steps

- Learn about the [API Reference](https://docs.usetode.dev/api) for all available methods
- See other framework guides: [React](https://docs.usetode.dev/react), [Vue](https://docs.usetode.dev/vue), [Svelte](https://docs.usetode.dev/svelte)

Source: https://docs.usetode.dev/angular
