Tokens Studio for Figma Plugin Documentation

repository·main·Indexed 23 days ago

https://github.com/tokens-studio/figma-plugin

A design system management plugin for Figma that uses JSON as a single source of truth to define, sync, and apply design tokens. Includes documentation for the Token Transformer CLI and library for Style Dictionary compatibility, the figma-bridge tool for programmatic Figma Desktop control via CDP on macOS, and developer guides for the AsyncMessageChannel communication architecture between the Figma Sandbox, UI, and browser previews.

Tokens
22.6K
Snippets
51
Records
93
Agent score
81%

What's inside Tokens Studio for Figma

  1. Overview of Tokens Studio for Figma

    main

    Tokens Studio for Figma is a plugin that enables the definition and management of design tokens within Figma. It extends Figma's native capabilities by allowing you to:

    • Store tokens in JSON: Manage design decisions in a structured, portable format.
    • Sync with providers: Connect your tokens to external sources like GitHub.
    • Define unsupported properties: Create tokens for properties that Figma does not natively support as styles, such as borderRadius or spacing.
    • Granular Color and Typography: Extract atomic design decisions into individual tokens.
    • Use Aliases: Define aliases for every token to enable reuse and maintainability.
    • Automate Auto Layout: Define and apply spacing tokens to automatically set Auto Layout properties in Figma.
  2. Use figma-bridge for programmatic Figma control

    main

    The figma-bridge tool allows you to control Figma Desktop from the command line using the Chrome DevTools Protocol (CDP). It enables you to execute Plugin-API JavaScript (figma.*) directly in the Figma renderer to read documents, mutate nodes, manage variables, and export assets without using the Figma UI or a manual plugin installation.

    Requirements:

    • Platform: macOS only.
    • Runtime: Node.js 22+ (required for built-in WebSocket and fetch support).

    Core Workflow:

    1. Use node cli.mjs start to clone, patch, and launch a debug version of Figma.
    2. Use node cli.mjs eval to run Plugin-API commands.
    3. Use node cli.mjs export or node cli.mjs shot to capture visual output.

    Note: start will gracefully quit any currently running instance of Figma to avoid profile conflicts.

    # From tools/figma-bridge/
    node cli.mjs start
    node cli.mjs eval "return figma.currentPage.name"
  3. How token application and updates work

    main

    When you apply a token to a layer, the plugin stores hidden metadata on that layer specifying which token applies to which property.

    Update Lifecycle:

    • When tokens change, the plugin scans the document for layers containing this hidden metadata and updates them.
    • For Styles: The plugin checks for a local style with the same name as your color or typography token and updates it.
    • Limitation: If a style is remote (not local to the current document), the plugin cannot apply the style and will instead apply the raw hex value. For this reason, it is recommended to use Figma's native Style feature for color and text, using the plugin primarily as a manager to maintain a single source of truth.
  4. Follow the verification hierarchy for Figma bridge operations

    main

    When interacting with Figma via the CDP bridge, use the most efficient method based on your goal. Avoid using screenshots for data that can be retrieved via the API.

    1. Answering "What is the value?" $\rightarrow$ Use eval to read structured data via the Figma Plugin API. This is the most reliable method for colors, names, sizes, variables, fonts, and node hierarchies.
    2. Validating visual content $\rightarrow$ Use export to capture a specific node as a high-fidelity, tightly cropped PNG. This is independent of zoom, viewport, or UI panels.
    3. Inspecting Figma's UI $\rightarrow$ Use shot to capture the entire Figma window (toolbar, panels, etc.). Use this only for debugging the plugin's own UI or inspecting Figma panels that the API cannot expose.
  5. Understand the plugin startup architecture

    main

    The Tokens Studio Figma plugin operates using two distinct entry points that communicate via an asynchronous messaging channel. Understanding this separation is key to knowing where logic resides.

    Backend (controller.ts)

    The backend runs in the Figma environment and is responsible for interacting with the Figma API and managing the plugin lifecycle. Its core responsibilities include:

    • Figma API Communication: Instantiating the asynchronous messaging channel to communicate with the PluginInstance.
    • Event Registration: Registering handlers for Figma events such as close, selectionchange, and documentchange.
    • Dev Mode Compatibility: Registering support for Figma Dev Mode.
    • UI Rendering: Triggering the UI display (figma.showUI) and passing necessary local data (e.g., license keys, active themes) to the frontend.

    Frontend (index.tsx)

    The frontend is the React-based user interface. Once the backend has gathered initial information, the frontend takes over to:

    • Tool Initialization: Initializing tracking tools like Mixpanel and Sentry.
    • Messaging Setup: Instantiating the messaging channel to communicate with the ReactInstance (the backend).
    • Event Handling: Registering specific internal events:
      • GET_THEME_INFO: Retrieves the user's last active theme.
      • STARTUP: Locates the document container to render the React application root, wrapped in providers for Sentry, Redux, and tooltips.

    Once the AppContainer component is mounted, it has access to the gathered information and handlers required for user interaction.

  6. Understand how storage providers and credentials are stored

    main

    Tokens Studio for Figma splits storage configuration into two distinct parts to balance team synchronization with individual security:

    1. Storage Type (Shared): The current storage provider type for a document is saved on the figma.root node as shared plugin data. Because this is stored on the Figma document itself, it is externally accessible, ensuring that all team members working on the same file are prompted to use the same provider.
    2. API Credentials (Private): Sensitive API credentials for the chosen storage provider are stored locally on the client. This ensures that credentials remain private to the individual user and are not shared via the Figma document.

    Startup Lifecycle: When the plugin starts, it reads the shared storage provider from the document and then checks the local client storage for matching API credentials. If credentials are missing, the user will need to provide them.

  7. Choose a usage strategy for the plugin

    main

    There are two primary ways to use the plugin depending on your workflow:

    1. Style Management Only: Use the plugin to create or update Figma Styles (colors, typography) without applying tokens directly to layers. This allows you to leverage atomic decisions, aliases, and theme sets while still using native Figma Styles for application. This is highly effective when combined with Figma's 'Swap library' feature.

    2. Full Token Application: Use the plugin to apply tokens directly to properties like borderRadius or spacing. This provides style-like functionality for properties that Figma does not natively support as styles.

  8. Compare export vs shot for visual verification

    main

    When verifying your work visually, choose the command based on what you need to see:

    • export <nodeId> [file] [scale]: Calls node.exportAsync(). It returns only the pixels of the specific node, tightly cropped. This is independent of zoom, viewport, or UI panels. Use this to validate that a specific frame or component was built correctly.
    • shot [file]: Captures the entire Figma window, including the toolbar, side panels, and canvas chrome. Use this only when you need to see Figma's own UI (e.g., checking the state of a variables panel or an iframe).
  9. Configure Auto-layout sizing modes

    main

    When building Auto-layout frames, pay close attention to primaryAxisSizingMode and counterAxisSizingMode to avoid collapsed or invisible content.

    Vertical Stacks (Hug Contents)

    To make a vertical stack grow with its children, set primaryAxisSizingMode to "AUTO". If left as "FIXED", the frame will maintain its initial height and clip the children.

    Horizontal Wrap (Grid Pattern)

    To create a wrapping row (like a grid of cards), you must configure three specific properties:

    1. layoutWrap = "WRAP"
    2. primaryAxisSizingMode = "FIXED" (A fixed width is required to trigger the wrap).
    3. counterAxisSizingMode = "AUTO" (Allows the height to expand based on the number of rows).

    Use itemSpacing for column gaps and counterAxisSpacing for row gaps.

    node cli.mjs eval '
      const wrap = figma.createFrame();
      wrap.layoutMode = "HORIZONTAL";
      wrap.layoutWrap = "WRAP";
      wrap.primaryAxisSizingMode = "FIXED";     // fixed width → wrapping kicks in
      wrap.counterAxisSizingMode = "AUTO";      // height hugs the rows
      wrap.itemSpacing = 16;                    // column gap
      wrap.counterAxisSpacing = 16;              // row gap
      wrap.resize(768, 10);                     // width matters; height will hug
      figma.currentPage.appendChild(wrap);
      return { id: wrap.id };
    '
  10. Understand the FileKey identifier

    main

    The fileKey is a unique 24-character string generated via the generateId utility when the plugin is first used in a Figma file. It is stored as shared plugin data on the root node of the Figma document.

    This mechanism allows the plugin to:

    1. Associate client-side stored data with specific Figma files.
    2. Maintain file-specific settings and tokens across different devices.
    3. Ensure data consistency during multi-user collaboration on the same file.
  11. How the plugin manages clientStorage limits

    main

    Figma's clientStorage has a 5MB limit. To prevent exceeding this limit when handling large token sets, the plugin employs the following storage management strategy:

    1. Compression: All token and theme data is compressed using lz-string's compressToUTF16 before being saved.
    2. Automatic Cleanup: If adding new data would exceed a safe threshold of 4MB, the plugin automatically deletes data associated with other files.
    3. Prioritization: The data for the currently active file is always preserved, while data from older/other files is subject to removal to free up space.
  12. How AsyncMessageChannel works and its data flow

    main

    AsyncMessageChannel is a communication abstraction used to facilitate asynchronous messaging between different environments in the Tokens Studio Figma plugin. It manages the flow of data between the Figma Plugin Controller (Sandbox), the Figma Plugin UI, and an optional Web Browser Preview.

    Data Flow Architecture

    • Controller (Sandbox) $\leftrightarrow$ UI: Uses PluginInstance and ReactInstance to bridge the gap between the Figma sandbox and the UI iframe.
    • UI $\leftrightarrow$ Browser Preview: When in PREVIEW_MODE, the UI forwards messages via WebSockets to a browser environment to allow for external development/testing.

    Environments

    • Environment.PLUGIN: The controller entrypoint (Figma Sandbox).
    • Environment.UI: The ui entrypoint (Iframe). Has access to parent.postMessage to communicate with the controller.
    • Environment.BROWSER: The web preview environment. Communicates with the UI via WebSockets.