### Installing the UI Library Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/ui.md Install the necessary packages for the UI component library. ```APIDOC ## Installing the UI Library To install the UI library and Preact, run the following command: ```sh $ npm install @create-figma-plugin/ui preact ``` ``` -------------------------------- ### Install UI Dependencies Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/ui.md Install the required UI library and Preact framework via npm. ```shell npm install @create-figma-plugin/ui preact ``` -------------------------------- ### Install @create-figma-plugin/utilities Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/utilities.md Command to install the @create-figma-plugin/utilities library using npm. This library provides utility functions for Figma/FigJam plugins and widgets. ```sh npm install @create-figma-plugin/utilities ``` -------------------------------- ### Widget Development with Create Figma Plugin Utilities Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt Demonstrates how to create interactive Figma widgets using the Create Figma Plugin utilities. It includes state management with `useSyncedState`, defining property menus with `usePropertyMenu`, and handling user interactions to update widget state. The example features a counter widget with increment and reset functionalities, and an option to edit in the UI. Dependencies include '@create-figma-plugin/utilities'. ```tsx /** @jsx figma.widget.h */ import { once, showUI } from '@create-figma-plugin/utilities' const { widget } = figma const { AutoLayout, Text, useSyncedState, usePropertyMenu } = widget export default function () { widget.register(Counter) } function Counter() { const [count, setCount] = useSyncedState('count', 0) const menuItems: WidgetPropertyMenuItem[] = [ { itemType: 'action', propertyName: 'increment', tooltip: 'Add 1' }, { itemType: 'action', propertyName: 'reset', tooltip: 'Reset' }, { itemType: 'separator' }, { itemType: 'action', propertyName: 'edit', tooltip: 'Edit in UI' } ] async function handlePropertyMenu({ propertyName }: WidgetPropertyEvent) { if (propertyName === 'increment') { setCount(count + 1) } else if (propertyName === 'reset') { setCount(0) } else if (propertyName === 'edit') { await new Promise((resolve) => { showUI({ width: 240, height: 120 }, { count }) once('SET_COUNT', (newCount: number) => { setCount(newCount) resolve() }) }) } } usePropertyMenu(menuItems, handlePropertyMenu) return ( Counter Widget {count} ) } ``` -------------------------------- ### Manage Figma Plugin Projects with CLI Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt Use the CLI to scaffold new projects from templates and manage the build lifecycle. These commands support interactive setup, minified production builds, and development watch modes. ```bash # Create a new plugin project interactively npx create-figma-plugin # Build the plugin (minified with type checking) npm run build # or: build-figma-plugin --typecheck --minify # Watch mode for development npm run watch # or: build-figma-plugin --typecheck --watch ``` -------------------------------- ### Creating the UI Component Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/ui.md Example of a Preact functional component for the UI, receiving data passed from the main plugin context. ```APIDOC ## Creating the UI Component Create a file for your UI (e.g., `src/ui.tsx`) using Preact components. The `Plugin` component receives props from the `data` object passed to `showUI`. ### Request Example ```tsx // src/ui.tsx import { render, Container, Text, VerticalSpace } from '@create-figma-plugin/ui' import { h } from 'preact' function Plugin (props: { greeting: string }) { return ( {props.greeting} ) } export default render(Plugin) ``` ``` -------------------------------- ### Build Layouts with Containers and Spacing Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt Provides examples of using layout components like Container, Stack, Columns, and Inline to organize UI elements. These components ensure consistent spacing and alignment across the plugin interface. ```tsx import { Container, Stack, Columns, VerticalSpace, Inline, MiddleAlign, Divider, Text, Button } from '@create-figma-plugin/ui' import { h } from 'preact' function Plugin() { return ( Item 1 Item 2 Item 3 Centered content ) } ``` -------------------------------- ### Configure a Figma plugin in package.json Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/quick-start.md Define the plugin configuration within the figma-plugin key in package.json. This example specifies the main entry point and UI file for a Figma-based plugin. ```json { "figma-plugin": { "editorType": [ "figma" ], "name": "Rectangles", "main": "src/main.ts", "ui": "src/ui.tsx" } } ``` -------------------------------- ### Configure Tailwind CSS for Figma Plugins Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/ui.md Setup Tailwind CSS by installing dependencies, creating configuration files, and updating package.json scripts to handle CSS generation and watching. The configuration includes specific dark mode settings for Figma environments. ```bash npm install --save-dev tailwindcss preact concurrently ``` ```javascript /** @type {import('tailwindcss').Config} */ export default { content: ['./src/**/*.{ts,tsx}'], theme: { extend: {}, }, plugins: [], darkMode: ['class', '.figma-dark'] } ``` ```css @tailwind base; @tailwind components; @tailwind utilities; ``` ```json { "scripts": { "build": "npm run build:css && npm run build:js", "build:css": "tailwindcss --input ./src/input.css --output ./src/output.css", "build:js": "build-figma-plugin --typecheck --minify", "watch": "npm run build:css && concurrently npm:watch:css npm:watch:js", "watch:css": "tailwindcss --input ./src/input.css --output ./src/output.css --watch", "watch:js": "build-figma-plugin --typecheck --watch" } } ``` -------------------------------- ### Render Function for Plugin UI Entry Point Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt Defines the entry point for rendering the plugin's user interface using Preact. It utilizes the `render` function from '@create-figma-plugin/ui' to mount a React component. The component can receive initial props, such as `initialCount` in this example. Dependencies include '@create-figma-plugin/ui' and 'preact'. ```tsx // ui.tsx import { render, Container, Text } from '@create-figma-plugin/ui' import { h } from 'preact' function Plugin(props: { initialCount: number }) { return ( Initial count: {props.initialCount} ) } // Export the rendered component export default render(Plugin) // The render function is called automatically by the build system // with the root element and __SHOW_UI_DATA__ props ``` -------------------------------- ### VS Code Schema Validation Setup Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/configuration.md Instructions for setting up JSON schema validation for your Figma plugin configuration in Visual Studio Code. ```APIDOC ## JSON schema validation in VS Code Validate the plugin configuration in your `package.json` file using [Create Figma Plugin’s configuration JSON schema](https://yuanqing.github.io/create-figma-plugin/figma-plugin.json). If you’re using [Visual Studio Code](https://code.visualstudio.com), you can enable autocomplete and inline validation of your plugin configuration by creating a `.vscode/settings.json` file: ```json { "json.schemas": [ { "fileMatch": [ "package.json" ], "url": "https://yuanqing.github.io/create-figma-plugin/figma-plugin.json" } ] } ``` ``` -------------------------------- ### Configure a FigJam widget in package.json Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/quick-start.md Define the widget configuration within the figma-plugin key in package.json. This example sets the editorType to figjam and enables the containsWidget flag. ```json { "figma-plugin": { "editorType": [ "figjam" ], "containsWidget": true, "name": "Notepad", "main": "src/main.tsx", "ui": "src/ui.tsx" } } ``` -------------------------------- ### Initialize UI in Main Entry Point Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/ui.md Use the showUI utility to launch the plugin interface and pass initial data from the main process. ```typescript import { showUI } from '@create-figma-plugin/utilities' export default function () { const options = { width: 240, height: 120 } const data = { greeting: 'Hello, World!' } showUI(options, data) } ``` -------------------------------- ### Showing the UI Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/ui.md Demonstrates how to display the UI from your plugin's main entry point using the `showUI` utility. ```APIDOC ## Showing the UI Include a call to `showUI` in your plugin/widget's main entry point. The `data` argument can be used to pass initializing data to the UI. ### Request Example ```ts // src/main.ts import { showUI } from '@create-figma-plugin/utilities' export default function () { const options = { width: 240, height: 120 } const data = { greeting: 'Hello, World!' } showUI(options, data) } ``` ``` -------------------------------- ### Configure basic plugin in package.json Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/configuration.md Demonstrates the minimal configuration required to define a plugin's ID, name, and main entry point within the package.json file. ```json { "figma-plugin": { "id": "806532458729477508", "name": "Draw Mask Under Selection", "main": "src/main.ts" } } ``` -------------------------------- ### Bootstrap a new plugin or widget Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/quick-start.md Use the create-figma-plugin CLI tool to initialize a new project from a template. This command prompts the user to select from various plugin and widget templates. ```shell $ npx --yes create-figma-plugin ``` -------------------------------- ### Configure Plugin Menu and Relaunch Buttons Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/configuration.md This JSON configuration demonstrates how to define a plugin menu with nested commands and separators, as well as how to register relaunch buttons for specific plugin functionality. ```json { "figma-plugin": { "id": "786286754606650597", "name": "Organize Layers", "menu": [ { "name": "Organize Layers", "main": "src/organize-layers/main.ts", "ui": "src/organize-layers/ui.tsx" }, "-", { "name": "Reset Plugin", "main": "src/reset-plugin/main.ts" } ], "relaunchButtons": { "organizeLayers": { "name": "Organize Layers", "main": "src/organize-layers/main.ts", "ui": "src/organize-layers/ui.tsx" } } } } ``` -------------------------------- ### Configure plugin with UI in package.json Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/configuration.md Demonstrates how to include a user interface component alongside the main entry point for a Figma plugin. ```json { "figma-plugin": { "id": "767379335945775056", "name": "Draw Slice Over Selection", "main": "src/main.ts", "ui": "src/ui.tsx" } } ``` -------------------------------- ### Configure UI Path in package.json Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/ui.md Register the UI entry point file within the figma-plugin configuration in package.json. ```json { "figma-plugin": { "name": "Hello World", "main": "src/main.ts", "ui": "src/ui.tsx" } } ``` -------------------------------- ### Configuring the UI File Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/ui.md Specify the UI file path in the `package.json` under the `figma-plugin.ui` key. ```APIDOC ## Configuring the UI File In your `package.json`, point to your UI file using the `"ui"` key under the `"figma-plugin"` object. ### Request Example ```json { // ... "figma-plugin": { // ... "name": "Hello World", "main": "src/main.ts", "ui": "src/ui.tsx" } } ``` ``` -------------------------------- ### Build Figma Plugin/Widget Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/quick-start.md Command to initiate the build process for a Figma plugin or widget. This generates necessary files like `manifest.json` and JavaScript bundles in the `build/` directory. The `--output` flag can customize the output location. ```sh $ npm run build ``` -------------------------------- ### Plugin Configuration Options Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/configuration.md Details the available configuration options for the `package.json` file when creating a Figma plugin. ```APIDOC ## Plugin Configuration Options This section describes the various properties you can include in your `package.json` file to configure your Figma plugin. ### `codegenLanguages` (*`Array`*) *Required for codegen plugins only.* An array of code languages that your codegen plugin supports. Each language is an object with the following keys: - **`"label"`** (*`string`*) — *Required.* A label for the code language displayed in the Figma UI. - **`"value"`** (*`string`*) — *Required.* A specific code language. See the [example](https://figma.com/plugin-docs/manifest/#codegenlanguages). ### `codegenPreferences` (*`Array`*) *Optional.* Preferences for your codegen plugin. See the [example](https://figma.com/plugin-docs/manifest/#codegenpreferences). ### `enablePrivatePluginApi` (*`boolean`*) *Optional.* Set this to `true` to allow the use of plugin APIs that are only available to private plugins/widgets. ### `enableProposedApi` (*`boolean`*) *Optional.* Set this to `true` to allow the use of [Proposed APIs](https://figma.com/plugin-docs/proposed-api/) that are only available during development. ### `build` (*`string`*) *Optional.* A shell command that Figma will run before your plugin’s files are loaded. ``` -------------------------------- ### Configure Resize Behavior and Direction Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/recipes.md Demonstrates how to restrict resize direction and set double-click behavior for the UI window. ```ts useWindowResize(onWindowResize, { minWidth: 120, maxWidth: 320, resizeDirection: 'horizontal' }) useWindowResize(onWindowResize, { minWidth: 120, minHeight: 120, maxWidth: 320, maxHeight: 320, resizeBehaviorOnDoubleClick: 'minimize' }) ``` -------------------------------- ### Customize Build Configuration Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/recipes.md Shows how to override esbuild settings for plugin bundles and disable automatic React-to-Preact import swapping. ```js module.exports = function (buildOptions) { return { ...buildOptions, plugins: buildOptions.plugins.filter(function (plugin) { return plugin.name !== 'preact-compat' }) } } ``` -------------------------------- ### Load Plugin Settings Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/utilities.md Asynchronously loads plugin or widget settings stored locally using the provided settings key. If no settings are found, default settings are returned. Requires @create-figma-plugin/utilities. ```typescript import { loadSettingsAsync } from '@create-figma-plugin/utilities' async function loadSettingsAsync(defaultSettings: Settings, settingsKey?: string): Promise ``` -------------------------------- ### Configure Build and Watch Scripts for Figma Plugins Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/quick-start.md Defines the 'build' and 'watch' scripts in `package.json` to automate the compilation and bundling of Figma plugins or widgets using the `build-figma-plugin` CLI. These scripts leverage esbuild for fast builds and include TypeScript type-checking. ```json { "scripts": { "build": "build-figma-plugin --typecheck --minify", "watch": "build-figma-plugin --typecheck --watch" } } ``` -------------------------------- ### Plugin Manifest Configuration Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/configuration.md Overview of key manifest properties including menu structure, relaunch buttons, and security-related settings. ```APIDOC ## Plugin Manifest Configuration ### Description Defines the structure and capabilities of a Figma plugin via the manifest file. ### Properties - **menu** (array) - Optional - Defines sub-menu commands. - **relaunchButtons** (object) - Optional - Defines commands accessible via relaunch buttons. - **capabilities** (array) - Optional - Specifies required plugin capabilities (e.g., codegen, inspect). - **permissions** (array) - Optional - Specifies required user/file permissions. - **documentAccess** (string) - Optional - Configures dynamic page loading behavior. - **networkAccess** (object) - Required - Defines allowed domains for network requests. ### Example Configuration ```json { "figma-plugin": { "id": "837846252158418235", "menu": [ { "name": "Command", "main": "src/main.ts" } ], "networkAccess": { "allowedDomains": ["https://api.example.com"], "reasoning": "Fetching external data" } } } ``` ``` -------------------------------- ### UI Components: Dropdown for Menu Selection Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt Shows how to use the Dropdown component from '@create-figma-plugin/ui' to create selectable menus with headers, separators, and disabled options. Requires 'preact' and '@create-figma-plugin/ui'. ```tsx import { Dropdown, DropdownOption } from '@create-figma-plugin/ui' import { h } from 'preact' import { useState, useCallback } from 'preact/hooks' function Plugin() { const [alignment, setAlignment] = useState('left') const options: DropdownOption[] = [ { header: 'Horizontal' }, { value: 'left', text: 'Align Left' }, { value: 'center', text: 'Align Center' }, { value: 'right', text: 'Align Right' }, '-', // separator { header: 'Vertical' }, { value: 'top', text: 'Align Top' }, { value: 'middle', text: 'Align Middle' }, { value: 'bottom', text: 'Align Bottom' }, '-', { value: 'stretch', text: 'Stretch', disabled: true } ] const handleChange = useCallback((newValue: string) => { setAlignment(newValue) console.log('Selected:', newValue) }, []) return ( ) } ``` -------------------------------- ### Configure multiple plugin commands Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/recipes.md Shows how to define multiple commands and separators in the figma-plugin manifest configuration. This allows plugins to expose different features in the Figma sub-menu. ```json { "figma-plugin": { "id": "837846252158418235", "name": "Flatten Selection to Bitmap", "menu": [ { "name": "Flatten Selection to Bitmap", "main": "src/flatten-selection-to-bitmap/main.ts", "ui": "src/flatten-selection-to-bitmap/ui.ts" }, "-", { "name": "Settings", "main": "src/settings/main.ts", "parameters": [ { "key": "resolution", "description": "Enter a bitmap resolution" } ] } ] } } ``` -------------------------------- ### showUI Function Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt Renders the plugin UI in a modal window and passes initial data from the main plugin context to the UI layer. ```APIDOC ## showUI(options, data) ### Description Displays the plugin UI modal and injects initial state data into the UI context. ### Parameters - **options** (object) - Required - Configuration for the modal (width, height, title, visible). - **data** (object) - Optional - Initial data passed to the UI, accessible via the `__SHOW_UI_DATA__` global variable. ### Request Example ```typescript showUI({ width: 320, height: 240, title: 'My Plugin' }, { nodeCount: 5 }); ``` ### UI Access ```typescript declare const __SHOW_UI_DATA__: { nodeCount: number }; console.log(__SHOW_UI_DATA__.nodeCount); // 5 ``` ``` -------------------------------- ### Implement Resizable UI Window with useWindowResize Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/recipes.md Uses the useWindowResize hook in the UI component to emit resize events and handles them in the main thread using figma.ui.resize. ```tsx import { render, useWindowResize } from '@create-figma-plugin/ui' import { emit } from '@create-figma-plugin/utilities' import { h } from 'preact' function Plugin () { function onWindowResize(windowSize: { width: number; height: number }) { emit('RESIZE_WINDOW', windowSize) } useWindowResize(onWindowResize, { minWidth: 120, minHeight: 120, maxWidth: 320, maxHeight: 320 }) } ``` ```ts import { on, showUI } from '@create-figma-plugin/utilities' export default function () { on('RESIZE_WINDOW', function (windowSize: { width: number; height: number }) { const { width, height } = windowSize figma.ui.resize(width, height) }) showUI({ width: 240, height: 240 }) } ``` -------------------------------- ### Manage Plugin Settings with loadSettingsAsync and saveSettingsAsync Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt Demonstrates how to persist plugin configuration data to Figma's client storage. It supports default values and custom storage keys for managing multiple setting groups. ```typescript import { loadSettingsAsync, saveSettingsAsync } from '@create-figma-plugin/utilities' interface PluginSettings { defaultColor: string gridSize: number showGuides: boolean } const defaultSettings: PluginSettings = { defaultColor: 'FF5733', gridSize: 8, showGuides: true } export default async function () { const settings = await loadSettingsAsync(defaultSettings) console.log(settings.gridSize) settings.gridSize = 16 settings.defaultColor = '00FF00' await saveSettingsAsync(settings) await saveSettingsAsync(settings, 'my-plugin-v2-settings') } ``` -------------------------------- ### Communicate between Main and UI contexts Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/recipes.md Demonstrates using the @create-figma-plugin/utilities library to register event handlers in the main context and emit events from the UI context. This pattern allows for seamless data transfer between the plugin backend and the user interface. ```typescript // src/main.ts import { once } from '@create-figma-plugin/utilities'; export default function () { function handleSubmit (data) { console.log(data); //=> { greeting: 'Hello, World!' } } once('SUBMIT', handleSubmit); } ``` ```tsx // src/ui.tsx import { render, Button } from '@create-figma-plugin/ui'; import { emit } from '@create-figma-plugin/utilities'; import { h } from 'preact'; function Plugin () { function handleClick () { const data = { greeting: 'Hello, World!' }; emit('SUBMIT', data); } return ; } export default render(Plugin); ``` -------------------------------- ### Build and Watch Figma Plugin Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/create-figma-plugin/templates/plugin/preact-tailwindcss/README.md Commands to compile the plugin source code into a manifest and bundle, or to enable automatic rebuilding during development. ```bash npm run build ``` ```bash npm run watch ``` -------------------------------- ### Implement Custom UI Rendering Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/ui.md Shows how to implement a custom UI by exporting a function that receives the root HTMLElement and data, allowing for manual DOM manipulation. ```typescript export default function (rootNode: HTMLElement, data: { greeting: string }) { rootNode.innerHTML = `

${data.greeting}

` } ``` -------------------------------- ### UI Components: Button with Loading States Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt Illustrates the usage of the Button component from '@create-figma-plugin/ui', including primary, secondary, danger, and full-width variants, along with handling loading and disabled states. Requires 'preact' and '@create-figma-plugin/ui'. ```tsx import { Button, Container, VerticalSpace } from '@create-figma-plugin/ui' import { h } from 'preact' import { useState, useCallback } from 'preact/hooks' function Plugin() { const [loading, setLoading] = useState(false) const handleClick = useCallback(async () => { setLoading(true) await doSomething() setLoading(false) }, []) return ( ) } ``` -------------------------------- ### Image Utilities: Create Image Paints and Process Image Data Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt Demonstrates how to create image paints from byte data and manipulate images using canvas elements. It includes functions for creating image paints, converting bytes to a canvas for processing, and converting the canvas back to bytes. Dependencies include '@create-figma-plugin/utilities'. ```typescript import { createImagePaint, createCanvasElementFromBytesAsync, readBytesFromCanvasElementAsync } from '@create-figma-plugin/utilities' // Create image paint from bytes const imageBytes = await figma.getImageByHash('abc123')?.getBytesAsync() if (imageBytes) { const imagePaint = createImagePaint(imageBytes) const rect = figma.createRectangle() rect.fills = [imagePaint] } // In UI: Convert bytes to canvas for manipulation async function processImage(bytes: Uint8Array) { const canvas = await createCanvasElementFromBytesAsync(bytes) const ctx = canvas.getContext('2d')! // Apply grayscale filter const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height) // ... process pixels ... ctx.putImageData(imageData, 0, 0) // Convert back to bytes const processedBytes = await readBytesFromCanvasElementAsync(canvas, 'image/png') return processedBytes } ``` -------------------------------- ### Implement Boolean Inputs with Checkbox and Toggle Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt Demonstrates how to use Checkbox and Toggle components, including support for mixed states when handling multiple selections. It utilizes Preact state hooks to manage input values. ```tsx import { Checkbox, Toggle, MIXED_BOOLEAN } from '@create-figma-plugin/ui' import { h } from 'preact' import { useState } from 'preact/hooks' function Plugin() { const [checked, setChecked] = useState(false) const [mixed, setMixed] = useState(MIXED_BOOLEAN) const [enabled, setEnabled] = useState(true) return ( <> Include hidden layers Lock aspect ratio (mixed) Enable auto-layout ) } ``` -------------------------------- ### Create Modal Dialogs with Focus Trapping Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt Shows how to implement a Modal component that supports focus trapping, escape key handling, and overlay clicks. It requires managing the open state via hooks and defining callback functions for user interactions. ```tsx import { Modal, Button, Container, Text, VerticalSpace } from '@create-figma-plugin/ui' import { h } from 'preact' import { useState, useCallback } from 'preact/hooks' function Plugin() { const [isOpen, setIsOpen] = useState(false) const handleOpen = useCallback(() => setIsOpen(true), []) const handleClose = useCallback(() => setIsOpen(false), []) const handleConfirm = useCallback(() => { console.log('Confirmed!') setIsOpen(false) }, []) return ( <> Are you sure you want to proceed? ) } ``` -------------------------------- ### Import Tailwind CSS in Figma Plugin UI Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/ui.md Demonstrates how to import the generated CSS file into a Preact component using the '!' prefix to inline styles without hashing class names. ```tsx import { render } from '@create-figma-plugin/ui' import { h } from 'preact' import '!./output.css' function Plugin () { return (

Hello, World!

) } export default render(Plugin) ``` -------------------------------- ### Widget Development Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt Utilities for creating interactive Figma widgets with synced state and property menus. ```APIDOC ## Widget Development ### Description Provides hooks like `useSyncedState` and `usePropertyMenu` to build interactive widgets that persist data across Figma sessions. ### Parameters - **useSyncedState** (string, any) - Required - Key and initial value for persistent widget state. - **usePropertyMenu** (array, function) - Required - Configuration for the widget's right-click menu items and event handlers. ### Request Example const [count, setCount] = useSyncedState('count', 0); usePropertyMenu(menuItems, handlePropertyMenu); ``` -------------------------------- ### StatCounter Initialization (JavaScript) Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/templates/partials/analytics.html This JavaScript code initializes StatCounter tracking. It sets project ID, invisibility status, and security key for website analytics. ```javascript var sc_project = 12531644; var sc_invisible = 1; var sc_security = "95d0263e"; ``` -------------------------------- ### Inline Image Assets in Plugin UI Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/recipes.md Demonstrates how to import and use image files in a Preact UI component, which are automatically converted to Base64 data URLs. ```tsx import { render } from '@create-figma-plugin/ui'; import { h } from 'preact'; import image from './image.png'; function Plugin () { return ; } export default render(Plugin); ``` -------------------------------- ### Event System (emit, on, once) Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt The event system facilitates type-safe communication between the main plugin sandbox and the UI iframe using a standardized event handler pattern. ```APIDOC ## Event System Communication ### Description Provides type-safe message passing between the main plugin thread and the UI layer using defined event handlers. ### Methods - **emit(name, ...args)**: Dispatches an event to the other context. - **on(name, handler)**: Registers a persistent event listener. - **once(name, handler)**: Registers a one-time event listener. ### Parameters - **name** (string) - Required - The unique event identifier defined in the handler interface. - **handler** (function) - Required - The callback function executed when the event is received. ### Example ```typescript // Emit event from UI to Main emit('CREATE_RECTANGLES', 5, { r: 1, g: 0, b: 0 }); // Listen in Main once('CREATE_RECTANGLES', (count, color) => { ... }); ``` ``` -------------------------------- ### UI Components: Textbox and TextboxNumeric for Input Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt Demonstrates the Textbox and TextboxNumeric components from '@create-figma-plugin/ui' for handling text input and numeric input with validation, icons, and units. Requires 'preact' and '@create-figma-plugin/ui'. ```tsx import { Textbox, TextboxNumeric, Text, Muted, VerticalSpace, IconSearch16 } from '@create-figma-plugin/ui' import { h } from 'preact' import { useState } from 'preact/hooks' function Plugin() { const [name, setName] = useState('') const [width, setWidth] = useState(100) const [widthString, setWidthString] = useState('100') return ( <> Layer Name } /> Width ) } ``` -------------------------------- ### Render Plugin UI with showUI Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt Renders a modal UI within Figma and passes initial data to the UI layer. The utility handles theme colors and provides a global object for accessing initial state. ```typescript // main.ts import { showUI } from '@create-figma-plugin/utilities' export default function () { const selectedNodes = figma.currentPage.selection showUI( { width: 320, height: 240, title: 'My Plugin', visible: true }, { nodeCount: selectedNodes.length, pageId: figma.currentPage.id } ) } // ui.tsx - Access initial data declare const __SHOW_UI_DATA__: { nodeCount: number; pageId: string } function Plugin() { const { nodeCount, pageId } = __SHOW_UI_DATA__ return
Selected {nodeCount} nodes on page {pageId}
} ``` -------------------------------- ### Object Utilities Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/utilities.md Functions for deep cloning and comparing objects. ```APIDOC ## cloneObject(object) ### Description Creates a deep copy of the given object. ### Parameters - **object** (T) - Required ### Response - **T** - The deep copied object. ``` ```APIDOC ## compareObjects(a, b) ### Description Performs a deep equality comparison of two objects. ### Parameters - **a** (any) - Required - **b** (any) - Required ### Response - **boolean** - True if objects are equal. ``` -------------------------------- ### Event Handling Utilities (emit, on, once) Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/utilities.md Functions for managing event communication between the main Figma context and the UI context. Supports emitting events, listening for events, and listening for events that trigger only once. ```typescript import { emit, on, once } from '@create-figma-plugin/utilities' ``` ```typescript function emit(name: Handler['name'], ...args: Parameters): void // Emits an event by name, optionally passing arguments. Can be called from main context to UI or vice-versa. ``` ```typescript function on(name: Handler['name'], handler: Handler['handler']): () => void // Registers an event handler for a specific event name. Returns a function to deregister the handler. ``` ```typescript function once(name: Handler['name'], handler: Handler['handler']): () => void // Registers an event handler that will be executed at most once for the given event name. Returns a function to deregister the handler. ``` -------------------------------- ### Settings Persistence API Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt APIs for loading and saving plugin settings to Figma's client storage, ensuring persistence across sessions. ```APIDOC ## Settings Persistence - loadSettingsAsync, saveSettingsAsync ### Description Loads and saves plugin settings to Figma's client storage, persisted locally on the user's computer. ### Method `loadSettingsAsync(defaultSettings: T): Promise` `saveSettingsAsync(settings: T, key?: string): Promise` ### Endpoint N/A (Client-side storage) ### Parameters #### loadSettingsAsync - **defaultSettings** (T) - Required - Default settings object to use if no saved settings are found. #### saveSettingsAsync - **settings** (T) - Required - The settings object to save. - **key** (string) - Optional - A custom storage key to differentiate multiple settings groups. ### Request Example ```typescript import { loadSettingsAsync, saveSettingsAsync } from '@create-figma-plugin/utilities' interface PluginSettings { defaultColor: string gridSize: number showGuides: boolean } const defaultSettings: PluginSettings = { defaultColor: 'FF5733', gridSize: 8, showGuides: true } // Load settings with defaults const settings = await loadSettingsAsync(defaultSettings) // Update and save settings settings.gridSize = 16 settings.defaultColor = '00FF00' await saveSettingsAsync(settings) // Use custom storage key await saveSettingsAsync(settings, 'my-plugin-v2-settings') ``` ### Response #### Success Response (loadSettingsAsync) - **settings** (T) - The loaded settings object. #### Success Response (saveSettingsAsync) - **void** - Operation successful. #### Response Example (loadSettingsAsync) ```json { "defaultColor": "FF5733", "gridSize": 8, "showGuides": true } ``` ``` -------------------------------- ### Configure Relaunch Buttons Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt Manages the registration and removal of relaunch buttons that appear in the Figma UI for specific nodes. ```typescript import { setRelaunchButton, unsetRelaunchButton } from '@create-figma-plugin/utilities' for (const node of figma.currentPage.selection) { setRelaunchButton(node, 'editText', { description: 'Edit the text content of this layer' }) } unsetRelaunchButton(figma.currentPage.selection[0], 'editText') ``` -------------------------------- ### Set Relaunch Button (Figma API) Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/utilities.md Attaches a relaunch button to a Figma node for a specific command. Existing relaunch buttons are preserved. Configuration is managed via package.json. An optional description can be provided for display in the Figma UI. ```typescript function setRelaunchButton(node: BaseNode, relaunchButtonId: string, options?: { description?: string }): void; ``` -------------------------------- ### Show Figma UI Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/utilities.md Renders the plugin/widget UI in a modal window within the Figma interface. Allows specifying dimensions, title, and visibility, and can pass initial data to the UI. Requires @create-figma-plugin/utilities. ```typescript import { showUI } from '@create-figma-plugin/utilities' function showUI(options: ShowUIOptions, data?: Data): void ``` -------------------------------- ### Image and Canvas Element Creation Utilities Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/utilities.md Provides functions to create and manipulate image and canvas elements from various data formats like Blobs, Bytes, and existing ImageElements. Also includes a utility to create an image paint. ```typescript import { createCanvasElementFromBlobAsync, createCanvasElementFromBytesAsync, createCanvasElementFromImageElement, createImageElementFromBlobAsync, createImageElementFromBytesAsync, createImagePaint, readBytesFromCanvasElementAsync } from '@create-figma-plugin/utilities' ``` ```typescript function createCanvasElementFromBlobAsync(blob: Blob): Promise // Creates an HTMLCanvasElement from a Blob representing an image. ``` ```typescript function createCanvasElementFromBytesAsync(bytes: Uint8Array): Promise // Creates an HTMLCanvasElement from an array of bytes representing an image. ``` ```typescript function createCanvasElementFromImageElement(imageElement: HTMLImageElement): HTMLCanvasElement // Creates an HTMLCanvasElement from an existing HTMLImageElement. ``` ```typescript function createImageElementFromBlobAsync(blob: Blob): Promise // Creates an HTMLImageElement from a Blob representing an image. ``` ```typescript function createImageElementFromBytesAsync(bytes: Uint8Array): Promise // Creates an HTMLImageElement from an array of bytes representing an image. ``` ```typescript function createImagePaint(image: Uint8Array | Blob | string): ImagePaint // Creates an ImagePaint object that can be used for fills or strokes in Figma. ``` ```typescript function readBytesFromCanvasElementAsync(canvasElement: HTMLCanvasElement): Promise // Reads the image data from an HTMLCanvasElement as an array of bytes. ``` -------------------------------- ### Using Custom CSS without Hashing Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/ui.md Option to inline CSS files directly without hashing class names by prefixing the import path with `!`. ```APIDOC ## Using Custom CSS without Hashing To inline a CSS file without hashing its class names, add a `!` prefix to the import path. ### Request Example ```tsx // src/ui.tsx import { render } from '@create-figma-plugin/ui' import { h } from 'preact' import '!./styles.css' function Plugin () { // ... return (
{/* ... */}
) } export default render(Plugin) ``` ``` -------------------------------- ### Save Plugin Settings Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/utilities.md Asynchronously saves plugin or widget settings locally using the provided settings key. Settings are stored in figma.clientStorage. Requires @create-figma-plugin/utilities. ```typescript import { saveSettingsAsync } from '@create-figma-plugin/utilities' async function saveSettingsAsync(settings: Settings, settingsKey?: string): Promise ``` -------------------------------- ### Using Custom CSS with CSS Modules Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/ui.md Integrate custom CSS into your UI components using CSS Modules for scoped styling. ```APIDOC ## Using Custom CSS with CSS Modules Out of the box, the `build-figma-plugin` CLI supports CSS Modules. Import your CSS file and use the imported styles object to apply class names. ### Request Example ```css /* src/styles.css */ .container { background-color: var(--figma-color-bg-secondary); } ``` ```tsx // src/ui.tsx import { render } from '@create-figma-plugin/ui' import { h } from 'preact' import styles from './styles.css' function Plugin () { // ... return (
{/* ... */}
) } export default render(Plugin) ``` By default, class names are hashed to ensure uniqueness. Refer to the base CSS file in `@create-figma-plugin/ui` for available CSS variables. ``` -------------------------------- ### Layout Components Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt Utility components for structuring plugin UI, including containers, stacks, columns, and spacing helpers. ```APIDOC ## Layout Components ### Description A collection of layout primitives to manage spacing and alignment within the plugin UI. ### Components - **Container**: Wraps content with consistent padding. - **Stack**: Vertically stacks children with defined spacing. - **Columns**: Arranges children in a horizontal grid. - **VerticalSpace**: Adds vertical margin between elements. - **Inline**: Arranges children horizontally with wrapping. - **MiddleAlign**: Vertically centers content. ### Example ```tsx Item 1 Item 2 ``` ``` -------------------------------- ### Render Plugin and Widget Lists with EJS Source: https://github.com/yuanqing/create-figma-plugin/blob/main/packages/website/docs/reference-plugins-and-widgets.md Uses EJS templating to iterate over plugin or widget data arrays. It generates HTML list items containing metadata, author links, and conditional GitHub repository links. ```ejs <% for (const { authors, description, githubUrl, id, name } of plugins) { %>
  • <%- description %>

  • <% } %> ``` -------------------------------- ### render Function Source: https://context7.com/yuanqing/create-figma-plugin/llms.txt The render function is the standard entry point for mounting Preact components into the Figma plugin UI window. ```APIDOC ## render Function ### Description Mounts a Preact component to the plugin UI. The build system automatically injects necessary data into the component props. ### Parameters - **Component** (function) - Required - The Preact functional component to render. ### Request Example export default render(Plugin); ```