# Svelte Integration

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

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

## Installation

Install the core SDK and Svelte adapter:

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

## 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 Svelte 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 the Store in Your Svelte UI

Use `createTodeStore` in your Svelte components:

```svelte title="App.svelte"
<script>
import { createTodeStore } from '@tode-sdk/figma-svelte';
import { onDestroy } from 'svelte';

const todeStore = createTodeStore();

// Clean up on component destroy
onDestroy(() => todeStore.destroy());

const handleExport = () => {
if ($todeStore.isReady) {
  todeStore.trackAction('export_clicked');
}
};
</script>

<button on:click={handleExport} disabled={!$todeStore.isReady}>
Export Design
</button>
<p>Analytics: {$todeStore.isReady ? 'Connected' : 'Connecting...'}</p>
```

## Store Reference

### createTodeStore()

Creates a new Tode store instance. Takes an optional object:

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `debug` | `boolean` | `false` | Log adapter activity to the console |
| `pingInterval` | `number` | `5000` | Keepalive ping interval in ms |

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.

### Store Value ($todeStore)

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

### Store Methods

| Method | Description |
|--------|-------------|
| `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)) |
| `destroy()` | Clean up resources (call on unmount) |

## Examples

### Basic Tracking

```svelte title="ToolButton.svelte"
<script>
  import { createTodeStore } from '@tode-sdk/figma-svelte';
  import { onDestroy } from 'svelte';

  export let tool;

  const todeStore = createTodeStore();
  onDestroy(() => todeStore.destroy());

  const handleClick = () => {
    // Track which tool was selected in your Figma plugin
    if ($todeStore.isReady) {
      todeStore.trackAction(`tool_selected_${tool}`);
    }
  };
</script>

<button on:click={handleClick}>{tool}</button>
```

### Track with Metrics

```svelte title="ExportPanel.svelte"
<script>
  import { createTodeStore } from '@tode-sdk/figma-svelte';
  import { onDestroy } from 'svelte';

  const todeStore = createTodeStore();
  onDestroy(() => todeStore.destroy());

  let selectedItems = [];

  const handleExport = async () => {
    // Perform export logic...

    // Track export with item count for Figma widget analytics
    if ($todeStore.isReady) {
      todeStore.trackActionWithMetric('items_exported', selectedItems.length);
    }
  };
</script>

<button on:click={handleExport}>
  Export {selectedItems.length} Items
</button>
```

### Track Feature Views

```svelte title="FeatureView.svelte"
<script>
  import { createTodeStore } from '@tode-sdk/figma-svelte';
  import { onDestroy } from 'svelte';

  const todeStore = createTodeStore();
  let hasTrackedView = false;

  onDestroy(() => todeStore.destroy());

  // Track feature view once when component mounts and Tode is ready
  $: if ($todeStore.isReady && !hasTrackedView) {
    todeStore.trackAction('feature_viewed');
    hasTrackedView = true;
  }
</script>

<div>Feature Content</div>
```

### Using the Default Store

For simpler use cases, you can use the pre-created store:

```svelte title="SimpleTracker.svelte"
<script>
  import { todeStore } from '@tode-sdk/figma-svelte';

  // Note: Don't call destroy() on the default store
  // as it's shared across components
</script>

<button
  on:click={() => $todeStore.isReady && $todeStore.tode.trackAction('click')}
  disabled={!$todeStore.isReady}
>
  Track Click
</button>
```

### Multiple Components with Context

```svelte title="App.svelte"
<script>
  import { createTodeStore } from '@tode-sdk/figma-svelte';
  import { setContext, onDestroy } from 'svelte';
  import ChildComponent from './ChildComponent.svelte';

  const todeStore = createTodeStore();

  // Share store via context
  setContext('tode', todeStore);

  onDestroy(() => todeStore.destroy());
</script>

<ChildComponent />
```

```svelte title="ChildComponent.svelte"
<script>
  import { getContext } from 'svelte';

  const todeStore = getContext('tode');

  const track = () => {
    if ($todeStore.isReady) {
      todeStore.trackAction('child_action');
    }
  };
</script>

<button on:click={track}>Track from Child</button>
```

## Best Practices

### 1. Always Call destroy()

Clean up resources when the component unmounts:

```svelte
<script>
  import { onDestroy } from 'svelte';

  const todeStore = createTodeStore();

  // Always clean up!
  onDestroy(() => todeStore.destroy());
</script>
```

### 2. Use Reactive Statements

Leverage Svelte's reactivity for Figma plugin analytics:

```svelte
<script>
  // Good - reactive
  $: canTrack = $todeStore.isReady && !isLoading;

  $: if (canTrack) {
    todeStore.trackAction('ready_to_track');
  }
</script>
```

### 3. Use Descriptive Action Names

```svelte
<script>
  // Good - clear and descriptive
  todeStore.trackAction('export_to_png');
  todeStore.trackAction('layer_renamed');

  // Bad - too vague
  todeStore.trackAction('click');
</script>
```

### 4. Consider Using Context for Deep Components

Share the store via context instead of prop drilling:

```svelte
<script>
  import { setContext } from 'svelte';
  const todeStore = createTodeStore();
  setContext('tode', todeStore);
</script>
```

## 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), [Angular](https://docs.usetode.dev/angular)

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