# Vanilla JavaScript Integration

Add **analytics to your Figma plugin** with the `TodeClient` class. This framework-agnostic guide works with vanilla JavaScript, TypeScript, or any framework not covered by our specific adapters.

Starting from zero? `npm create @tode-sdk@latest my-plugin -- --framework vanilla` gives you all of this already in place; see [Start from a template](https://docs.usetode.dev/template).

## Installation

Install the core SDK and vanilla adapter:

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

## 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 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"
]
}
}
```

### Use TodeClient in Your UI

Create a `TodeClient` instance in your UI code:

`ui.ts`:

```typescript
import { TodeClient } from '@tode-sdk/figma-vanilla';

const client = new TodeClient();

client.on('ready', (isReady: boolean) => {
  if (isReady) {
    console.log('Tode ready for tracking!');
  }
});

// Track button clicks
document.querySelector('#exportBtn')?.addEventListener('click', () => {
  if (client.isReady) {
    client.trackAction('export_clicked');
  }
});
```

## Client Reference

### Constructor

```typescript
const client = new TodeClient({ debug: false, pingInterval: 5000, autoStart: true });
```

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `debug` | `boolean` | `false` | Log adapter activity to the console |
| `pingInterval` | `number` | `5000` | Keepalive ping interval in ms |
| `autoStart` | `boolean` | `true` | Start listening one microtask after construction, so listeners you add with `on()` right away get the first events. Set `false` and call `start()` yourself |

The session connection is shared: however many components use Tode, the plugin UI opens one WebSocket and counts as one session. It closes when the last of them is gone.

### Properties

| Property | Type | Description |
|----------|------|-------------|
| `isReady` | `boolean` | Whether Tode is initialized ([`tode.isReady`](https://docs.usetode.dev/api#todeisready)) |
| `wsState` | `WebSocketState` | Session connection state: `disconnected`, `connecting`, `connected` or `error` |
| `tode` | `Tode` | Direct access to Tode instance |

### Methods

| Method | Description |
|--------|-------------|
| `on(event, callback)` | Add event listener |
| `off(event, callback)` | Remove event listener |
| `trackAction(name, options?)` | Track a simple action ([API](https://docs.usetode.dev/api#todetrackactionactionname)) |
| `trackActionWithMetric(name, value, options?)` | Track action with numeric value ([API](https://docs.usetode.dev/api#todetrackactionwithmetricactionname-value)) |
| `start()` | Start listening; only needed with `autoStart: false` |
| `destroy()` | Clean up all resources |

### Events

| Event | Payload | Description |
|-------|---------|-------------|
| `ready` | `boolean` | Fired once, when Tode becomes ready (also if it already was when the client started) |
| `wsStateChange` | `WebSocketState` | Fired on every change of the session connection state |

## Examples

### Basic Tracking

```typescript title="ui.ts"
import { TodeClient } from '@tode-sdk/figma-vanilla';

const client = new TodeClient();

// Track tool selection
document.querySelectorAll('.tool-btn').forEach(btn => {
  btn.addEventListener('click', () => {
    const tool = btn.dataset.tool;
    if (client.isReady) {
      client.trackAction(`tool_selected_${tool}`);
    }
  });
});
```

### Track with Metrics

`export.ts`:

```typescript
import { TodeClient } from '@tode-sdk/figma-vanilla';

const client = new TodeClient();

async function exportItems(items: any[]): Promise<void> {
  // Perform export logic...

  // Track export with item count for Figma widget analytics
  if (client.isReady) {
    client.trackActionWithMetric('items_exported', items.length);
  }
}
```

### Event Listeners

```typescript title="ui.ts"
import { TodeClient } from '@tode-sdk/figma-vanilla';

const client = new TodeClient();

// Listen for ready state
client.on('ready', (isReady) => {
  console.log('Ready:', isReady);
  updateUI(isReady);
});

function updateUI(ready) {
  document.querySelector('#status').textContent =
    ready ? 'Connected' : 'Connecting...';
}
```

### Cleanup on Unload

```typescript title="ui.ts"
import { TodeClient } from '@tode-sdk/figma-vanilla';

const client = new TodeClient();

// Clean up when window closes
window.addEventListener('beforeunload', () => {
  client.destroy();
});
```

### With HTML

```html title="index.html"
<!DOCTYPE html>
<html>
<head>
  <title>My Figma Plugin</title>
</head>
<body>
  <div id="status">Connecting...</div>
  <button id="exportBtn" disabled>Export</button>
  <button id="trackBtn" disabled>Track Action</button>

  <script type="module">
    import { TodeClient } from '@tode-sdk/figma-vanilla';

    const client = new TodeClient();
    const exportBtn = document.getElementById('exportBtn');
    const trackBtn = document.getElementById('trackBtn');
    const status = document.getElementById('status');

    client.on('ready', (isReady) => {
      exportBtn.disabled = !isReady;
      trackBtn.disabled = !isReady;
      status.textContent = isReady ? 'Ready' : 'Connecting...';
    });

    exportBtn.addEventListener('click', () => {
      client.trackAction('export_clicked');
    });

    trackBtn.addEventListener('click', () => {
      client.trackActionWithMetric('custom_metric', 42);
    });
  </script>
</body>
</html>
```

### Remove Event Listeners

```typescript title="ui.ts"
import { TodeClient } from '@tode-sdk/figma-vanilla';

const client = new TodeClient();

const readyHandler = (isReady) => {
  console.log('Ready:', isReady);
};

// Add listener
client.on('ready', readyHandler);

// Remove listener later
client.off('ready', readyHandler);
```

## Best Practices

### 1. Always Clean Up

Call `destroy()` when your plugin closes:

```typescript
// Good - clean up resources
window.addEventListener('beforeunload', () => {
  client.destroy();
});
```

### 2. Track Without Waiting for `isReady`

```typescript
// Held until the client is ready, then sent
client.trackAction('action');

// isReady is for UI state
exportBtn.disabled = !client.isReady;
```

### 3. Use Event Listeners for UI Updates

```typescript
// Good - reactive UI updates
client.on('ready', updateUI);

// Bad - polling
setInterval(() => {
  updateUI(client.isReady);
}, 100);
```

### 4. Use Descriptive Action Names

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

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

### 5. Direct Tode Access When Needed

```typescript
// Use client methods
client.trackAction('action');

// Or access tode directly for advanced usage
client.tode.trackAction('action');
```

## Integration with Other Libraries

### With jQuery

```javascript title="app.js"
import { TodeClient } from '@tode-sdk/figma-vanilla';

const client = new TodeClient();

$(document).ready(() => {
  client.on('ready', (isReady) => {
    $('.track-btn').prop('disabled', !isReady);
  });

  $('.track-btn').on('click', function() {
    const action = $(this).data('action');
    client.trackAction(action);
  });
});
```

### With Lit

`my-element.ts`:

```typescript
import { LitElement, html } from 'lit';
import { TodeClient } from '@tode-sdk/figma-vanilla';

class MyElement extends LitElement {
  private client = new TodeClient();
  private isReady = false;

  connectedCallback(): void {
    super.connectedCallback();
    this.client.on('ready', (ready: boolean) => {
      this.isReady = ready;
      this.requestUpdate();
    });
  }

  disconnectedCallback(): void {
    super.disconnectedCallback();
    this.client.destroy();
  }

  render() {
    return html`
      <button
        ?disabled=${!this.isReady}
        @click=${() => this.client.trackAction('click')}>
        Track
      </button>
    `;
  }
}
```

## Next Steps

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

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