• Figma Embeds

    Chalk supports embedding Figma designs directly in your content. When you include a Figma URL in an embed block, the system automatically downloads the image from Figma’s API and processes it through the same optimization pipeline as regular images.

    Quick Start

    1. Set up your Figma API token (one-time setup):

      pnpm run setup-figma
      

      This interactive command will:

      • Open the Figma settings page in your browser
      • Guide you through creating a personal access token
      • Save the token to your .env file
      • Validate that the token works correctly
    2. Use in chalk files:

      !!!
      https://www.figma.com/design/SnCKjjGP0S5dFnjsmrpfp0/Chalk-Images?node-id=1-2&t=8pkkHhJwW1aZIrAk-11
      !!!
      
    3. Build your content:

      pnpm run build
      

    How It Works

    When you include a Figma URL in an embed block (!!!), the system:

    1. Parses the URL to extract file ID and node ID
    2. Converts node ID format from hyphen (1-2) to colon (1:2) for API compatibility
    3. Calls Figma API to get the image URL
    4. Downloads the image and caches it locally
    5. Optimizes the image using the same pipeline as regular images
    6. Generates responsive HTML with multiple formats and sizes

    Basic Usage

    To embed a Figma design, use the standard embed block syntax with a Figma URL:

    !!!
    https://www.figma.com/design/FILE_ID/DESIGN_NAME?node-id=NODE_ID
    !!!
    

    The URL must include:

    • A valid Figma file ID
    • A node-id parameter pointing to a specific node/frame in the design

    Note: You can paste Figma URLs directly from your browser - the system automatically handles the node ID format conversion.

    Supported URL Formats

    Chalk recognizes these Figma URL formats:

    • https://www.figma.com/design/FILE_ID/NAME?node-id=NODE_ID
    • https://www.figma.com/file/FILE_ID/NAME?node-id=NODE_ID
    • https://figma.com/design/FILE_ID/NAME?node-id=NODE_ID

    Additional URL parameters (like sharing tokens) are preserved but not required for processing.

    Setup Requirements

    Easy Setup (Recommended)

    Run the interactive setup command:

    pnpm run setup-figma
    

    This will guide you through the entire process and automatically save your token to the correct location.

    Manual Setup

    If you prefer to set up manually:

    Environment Variable

    You must set the FIGMA_ACCESS_TOKEN environment variable with a valid Figma access token. The system automatically loads this from a .env file in the packages/chalk/ directory:

    # In packages/chalk/.env
    FIGMA_ACCESS_TOKEN=your_figma_token_here
    

    Or set it as an environment variable:

    export FIGMA_ACCESS_TOKEN=your_figma_token_here
    

    Creating a Figma Access Token

    1. Go to your Figma account settings
    2. Navigate to “Personal access tokens”
    3. Click “Create new token”
    4. Give it a descriptive name (e.g., “Chalk System”)
    5. Copy the generated token and set it as your environment variable

    File Permissions

    The Figma file must be:

    • Publicly accessible, OR
    • Accessible to the account associated with your access token

    Features

    Automatic Image Optimization

    Figma images go through the same optimization pipeline as regular images:

    • Multiple format generation (WebP + PNG fallback)
    • Responsive image sizes (480w, 768w, 1024w, 1440w)
    • Automatic caching to avoid repeated downloads
    • Modern <picture> element markup with srcset

    Caching System

    Downloaded Figma images are cached locally in .chalk-cache/figma/:

    • Cache duration: 24 hours
    • Cache invalidation based on file content changes
    • Shared cache across builds for faster subsequent builds

    Rate Limiting

    Built-in rate limiting respects Figma’s API limits:

    • Maximum 30 requests per minute
    • Automatic throttling when limits are approached
    • Clear error messages when limits are exceeded

    Metadata Support

    You can include custom metadata using YAML frontmatter:

    !!!
    designer: Jane Doe
    project: Design System
    version: v2.1
    status: approved
    ---
    https://www.figma.com/design/FILE_ID/NAME?node-id=NODE_ID
    
    [Component specification]
    
    Final approved design for the button component.
    !!!
    

    Example Usage

    Basic Embed

    !!!
    https://www.figma.com/design/FILE_ID/NAME?node-id=NODE_ID
    !!!
    

    With Description and Caption

    !!!
    https://www.figma.com/design/FILE_ID/NAME?node-id=NODE_ID
    
    [Alt text for the design]
    
    Caption describing what this design shows.
    !!!
    

    With Metadata

    !!!
    designer: Jane Doe
    project: Design System
    status: approved
    ---
    https://www.figma.com/design/FILE_ID/NAME?node-id=NODE_ID
    
    [Component specification]
    
    Final approved design for the button component.
    !!!
    

    Complete Example

    !!!
    designer: UI Team
    project: Dashboard Redesign
    component: Navigation
    status: approved
    date: 2024-01-15
    ---
    https://www.figma.com/design/SnCKjjGP0S5dFnjsmrpfp0/Dashboard?node-id=1-2
    
    [Navigation component mockup]
    
    This shows the final approved design for the main navigation component, 
    including hover states and responsive behavior.
    
    Photo by UI Team for Dashboard Redesign project.
    !!!
    

    Implementation Details

    Files Modified

    New Files:

    • src/figma/client.js - Figma API client with caching and rate limiting
    • tests/figma/client.test.js - Comprehensive tests for Figma functionality

    Modified Files:

    • src/parser/blocks.js - Added Figma URL detection and parsing
    • src/renderer/images.js - Added Figma image processing
    • src/renderer/index.js - Updated to handle Figma embeds
    • src/renderer/blocks.js - Added Figma embed rendering
    • tests/parser/blocks.test.js - Added Figma embed tests
    • cli.js - Added dotenv support for environment variable loading
    • package.json - Added dotenv dependency

    Architecture

    • URL Parsing: Regex-based detection of Figma URLs with file ID and node ID extraction
    • Node ID Conversion: Automatic conversion from hyphen format (1-2) to colon format (1:2) for API compatibility
    • API Integration: REST API calls to Figma’s endpoints with proper authentication
    • Caching Strategy: Local file system cache with timestamp-based invalidation
    • Rate Limiting: In-memory tracking of API calls with configurable limits
    • Error Handling: Graceful degradation to placeholder when API calls fail
    • Environment Loading: Automatic loading of environment variables from .env files

    Cache Structure

    .chalk-cache/figma/
    ├── abc123-1-2.png              # Cached Figma image
    ├── abc123-1-2.json             # Metadata and timestamp
    └── def456-3-4.png              # Another cached image
    

    Rate Limiting Details

    • Limit: 30 requests per minute (configurable)
    • Window: 60 seconds
    • Behavior: Throws error when limit exceeded
    • Reset: Automatic after window expires

    Files Modified

    New Files:

    • src/figma/client.js - Figma API client with caching and rate limiting
    • tests/figma/client.test.js - Comprehensive tests for Figma functionality

    Modified Files:

    • src/parser/blocks.js - Added Figma URL detection and parsing
    • src/renderer/images.js - Added Figma image processing
    • src/renderer/index.js - Updated to handle Figma embeds
    • src/renderer/blocks.js - Added Figma embed rendering
    • tests/parser/blocks.test.js - Added Figma embed tests
    • cli.js - Added dotenv support for environment variable loading
    • package.json - Added dotenv dependency

    Error Handling

    If a Figma embed fails to load, the system will:

    1. Log a warning with the specific error
    2. Display the embed as a placeholder
    3. Continue processing other content

    Common error scenarios:

    • Invalid URL: Missing node-id or malformed URL
    • Access denied: File is private or token lacks permissions
    • Rate limiting: Too many API requests in a short time
    • Network issues: Temporary connectivity problems

    Development vs Production

    Development Mode

    In development mode with --watch, Figma embeds are processed on each rebuild. The caching system helps minimize API calls during active development.

    Production Builds

    For production builds, ensure:

    • FIGMA_ACCESS_TOKEN is set in your deployment environment
    • Your build process has internet access to reach Figma’s API
    • Cache directory .chalk-cache/ is preserved between builds when possible

    Testing

    The implementation includes comprehensive tests:

    pnpm test
    

    Tests cover:

    • URL parsing for various Figma URL formats
    • API integration with mocked responses
    • Error handling for various failure scenarios
    • Caching behavior
    • Block parsing integration
    • Automatic node ID format conversion

    Best Practices

    URL Management

    • Use descriptive frame names in Figma for easier identification
    • Keep URLs in a central location if reusing across multiple files
    • Consider using metadata to track design versions and approval status
    • Paste URLs directly from Figma - no need to manually convert node ID formats

    Performance

    • Limit the number of Figma embeds per page to avoid long build times
    • Use caching effectively by maintaining consistent URLs
    • Consider pre-downloading critical images during deployment

    Organization

    • Use consistent metadata fields across your project
    • Include designer attribution and project information
    • Track design approval status and version numbers

    Troubleshooting

    “FIGMA_ACCESS_TOKEN environment variable is required”

    Quick fix: Run the setup command to configure your token:

    pnpm run setup-figma
    

    Manual fix: Set your Figma access token as an environment variable before building:

    export FIGMA_ACCESS_TOKEN=your_figma_token_here
    

    “Access denied to Figma file”

    Check that:

    • The file is publicly accessible or you have access
    • Your access token has the correct permissions
    • The file URL is correct and still exists

    Tip: You can regenerate your token by running pnpm run setup-figma again.

    “Rate limit exceeded”

    Wait a minute before retrying, or reduce the number of Figma embeds being processed simultaneously.

    “Invalid Figma URL”

    Ensure your URL includes the node-id parameter and follows one of the supported formats.

    “Token validation failed”

    If the setup command fails to validate your token:

    1. Double-check that you copied the entire token correctly
    2. Make sure the token hasn’t expired
    3. Verify you have the necessary permissions in Figma
    4. Try regenerating a new token in Figma settings

    General Setup Issues

    If you’re having trouble with the setup process:

    1. Make sure you’re running the command from the packages/chalk/ directory
    2. Check that you have write permissions in the current directory
    3. Ensure your browser can open the Figma settings page
    4. Try the manual setup process described above

    API Reference

    The Figma embed feature uses the Figma REST API with these endpoints:

    • GET /v1/images/:file_key - Get image URLs for nodes
    • GET /v1/files/:file_key - Get file metadata (optional)

    Rate limits follow Figma’s standard API limits (typically 2000 requests per hour per token).

    Future Enhancements

    Potential future improvements:

    • Support for Figma prototypes and flows
    • Automatic frame detection without node-id
    • Integration with Figma webhooks for cache invalidation
    • Support for Figma variables and design tokens