### Example Network Access Configuration Source: https://developers.figma.com/docs/plugins/manifest This snippet shows a complete example of the `networkAccess` object, including allowed domains for production and development. ```json { "networkAccess": { "allowedDomains": [ "figma.com", "*.google.com", "https://my-app.cdn.com", "wss://socket.io", "example.com/api/", "exact-path.com/content" ], "devAllowedDomains": [ "http://localhost:3000" ] } } ``` -------------------------------- ### Install Widget Typings Source: https://developers.figma.com/docs/plugins/api/properties/figma-createnodefromjsxasync Installs the necessary widget typings for your Figma plugin project. Run this command in your plugin's directory. ```bash npm i --save-dev @figma/widget-typings ``` -------------------------------- ### Install Project Dependencies with npm Source: https://developers.figma.com/docs/plugins/plugin-quickstart-guide Use this command to install all project dependencies listed in the package.json file. This is typically done after cloning a project or setting up a new development environment. ```bash npm install ``` -------------------------------- ### guides Source: https://developers.figma.com/docs/plugins/api/FrameNode Provides access to the array of `Guide` objects used within this FrameNode's frame. These guides are specific to the frame and separate from canvas-wide guides. ```APIDOC ## guides: ReadonlyArray ### Description Array of `Guide` used inside the frame. Note that each frame has its own guides, separate from the canvas-wide guides. For help on how to change this value, see Editing Properties. ``` -------------------------------- ### Check Node.js Installation Source: https://developers.figma.com/docs/plugins/plugin-quickstart-guide Verify that Node.js has been successfully installed by checking its version in the terminal. This command is run after Node.js installation. ```bash node ``` -------------------------------- ### Install Project Dependencies Source: https://developers.figma.com/docs/plugins/samples Installs project dependencies, including the Figma typings file, which is essential for developing typed Figma plugins. ```bash $ npm install ``` -------------------------------- ### Example tsconfig.json with JSX Options Source: https://developers.figma.com/docs/plugins/api/properties/figma-createnodefromjsxasync A complete example of a tsconfig.json file including the required JSX compiler options for Figma plugins. ```json { "compilerOptions": { "jsx": "react", "jsxFactory": "figma.widget.h", "jsxFragmentFactory": "figma.widget.Fragment", "target": "es6", "lib": [ "es6" ], "strict": true, "typeRoots": [ "./node_modules/@types", "./node_modules/@figma" ] } } ``` -------------------------------- ### Check TypeScript Installation Source: https://developers.figma.com/docs/plugins/plugin-quickstart-guide Verify that TypeScript has been successfully installed by checking its version in the terminal. This command is run after TypeScript installation. ```bash tsc -v ``` -------------------------------- ### Install Webpack and Webpack CLI Source: https://developers.figma.com/docs/plugins/libraries-and-bundling These commands install Webpack and the Webpack CLI as development dependencies for your project. Webpack is used for bundling modules, and the CLI provides tools to run Webpack from the command line. ```bash npm install webpack webpack-cli --save-dev ``` -------------------------------- ### TextPathStartData Source: https://developers.figma.com/docs/plugins/api/TextPathStartData Defines the starting point of a text path. ```APIDOC ## TextPathStartData ### Description Represents the starting point of a text path within a segment. ### Properties #### segment (number) - **segment**: The index of the segment where the text path begins. #### position (number) - **position**: The position along the segment (ranging from 0 to 1) where the text path starts. ``` -------------------------------- ### Add a New Guide to a PageNode Source: https://developers.figma.com/docs/plugins/api/properties/PageNode-guides Demonstrates how to add a new guide to a PageNode by creating a new array using `.concat()`. This method is necessary because the `guides` property is read-only. ```typescript function addNewGuide(page: PageNode, guide: Guide) { // .concat() creates a new array page.guides = page.guides.concat(guide) } ``` -------------------------------- ### Install TypeScript and ts-loader Source: https://developers.figma.com/docs/plugins/libraries-and-bundling Install the TypeScript compiler and loader as development dependencies. ```bash npm install --save-dev typescript ts-loader ``` -------------------------------- ### flowStartingPoints Source: https://developers.figma.com/docs/plugins/api/properties/PageNode-flowstartingpoints The sorted list of flow starting points used when accessing Presentation view. The default starting point is the first one in the list. ```APIDOC ## flowStartingPoints ### Description Returns a sorted list of flow starting points for Presentation view. This is supported on PageNode objects. ### Signature `flowStartingPoints: ReadonlyArray<{ nodeId: string; name: string }>` ### Remarks The default starting point is the first one in the list. This is used, for example, when no frames are selected and the user clicks the play icon in the toolbar to enter Presentation view. ``` -------------------------------- ### guides Source: https://developers.figma.com/docs/plugins/api/node-properties Array of Guide used inside the frame. Note that each frame has its own guides, separate from the canvas-wide guides. For help on how to change this value, see Editing Properties. ```APIDOC ## guides: ReadonlyArray ### Description Array of `Guide` used inside the frame. Note that each frame has its own guides, separate from the canvas-wide guides. For help on how to change this value, see Editing Properties. ### Supported on: * ComponentNode * ComponentSetNode * FrameNode * InstanceNode * SlideNode * SlotNode ``` -------------------------------- ### Install TypeScript Globally Source: https://developers.figma.com/docs/plugins/samples Installs the TypeScript compiler globally using npm. This is a prerequisite for compiling TypeScript code for Figma plugins. ```bash $ npm install -g typescript ``` -------------------------------- ### Codegen Plugin Example Source: https://developers.figma.com/docs/plugins/samples A basic example of a plugin designed for code generation tasks within Figma. ```typescript // Source code for Codegen plugin ``` -------------------------------- ### Example CSS Variables: Color Role Source: https://developers.figma.com/docs/plugins/css-variables Shows example CSS variables incorporating the 'brand' color role for background and the 'danger' color role for icons. ```css --figma-color-bg-brand --figma-color-icon-danger ``` -------------------------------- ### Text Path Start Data Source: https://developers.figma.com/docs/plugins/updates/2026/01/26/version-1-update-123 Gets and sets the starting position data for text on a path node. ```APIDOC ## textOnPathNode.textPathStartData ### Description Gets and sets the starting position data for text on a path node. ### Property Type `TextPathStartData` ``` -------------------------------- ### Check Payment Status and Initiate Checkout Source: https://developers.figma.com/docs/plugins/requiring-payment This example checks if a user has paid for the plugin or is within a free trial period. If the trial has ended (more than 3 days since first run), it initiates the checkout flow. Otherwise, it notifies the user about their trial status. ```typescript async function run() { if (figma.payments.status.type === "PAID") { figma.notify("USER HAS PAID"); } else { // figma.payments.status.type === "UNPAID" const ONE_DAY_IN_SECONDS = 60 * 60 * 24; const secondsSinceFirstRun = figma.payments.getUserFirstRanSecondsAgo(); const daysSinceFirstRun = secondsSinceFirstRun / ONE_DAY_IN_SECONDS; if (daysSinceFirstRun > 3) { await figma.payments.initiateCheckoutAsync({ interstitial: "TRIAL_ENDED", }); if (figma.payments.status.type === "UNPAID") { figma.notify("USER CANCELLED CHECKOUT"); } else { figma.notify("USER JUST PAID"); } } else { figma.notify("USER IS IN THREE DAY TRIAL PERIOD"); } } figma.closePlugin(); } run(); ``` -------------------------------- ### getStyledTextSegments(fields, start, end) Source: https://developers.figma.com/docs/plugins/api/node-properties Gets text segments along with specified text properties. Allows filtering by start and end character indices. ```APIDOC ## getStyledTextSegments)[]>(fields: StyledTextSegmentFields, start?: number, end?: number) ### Description Get text segments along with the desired text properties (font size, text case, etc...) ### Method GET (conceptual) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters - **fields** (Array>) - Required - An array of strings specifying which text segment properties to retrieve. - **start** (number) - Optional - The starting character index for the segments. - **end** (number) - Optional - The ending character index for the segments. ### Response #### Success Response - **Array>** - An array of styled text segments, each including the requested fields, characters, start, and end indices. ### Response Example ```json [ { "characters": "Hello", "start": 0, "end": 5, "fontSize": 16, "fontName": "Inter" } ] ``` ``` -------------------------------- ### Create a Styled 'Hello World!' Text Node Source: https://developers.figma.com/docs/plugins/api/properties/figma-createtext This snippet demonstrates how to create a text node, set its position, load a font, assign characters, and style it with a larger font size and red color. Ensure the font is loaded asynchronously before setting text content. ```typescript (async () => { const text = figma.createText() // Move to (50, 50) text.x = 50 text.y = 50 // Load the font in the text node before setting the characters await figma.loadFontAsync(text.fontName) text.characters = 'Hello world!' // Set bigger font size and red color text.fontSize = 18 text.fills = [{ type: 'SOLID', color: { r: 1, g: 0, b: 0 } }] })() ``` -------------------------------- ### figma.timer.remaining Source: https://developers.figma.com/docs/plugins/api/figma-timer Gets the time remaining on the timer in seconds. Returns 0 if the timer has not been started. ```APIDOC ## figma.timer.remaining ### Description Gets the time remaining on the timer in seconds. If the timer has not been started, returns 0. ### Property - **remaining** (number) - Readonly. Time remaining on timer, in seconds. ``` -------------------------------- ### Get Bound Variables from a Node Source: https://developers.figma.com/docs/plugins/working-with-variables This example shows how to retrieve all variables currently bound to a specific node using the `boundVariables` property. It also includes an example of the structure of the returned object. ```typescript const exampleNode = await figma.getNodeByIdAsync("1:4") const exampleNodeVariables = exampleNode.boundVariables /* Example boundVariables object: { "strokes": [ { "type": "VARIABLE_ALIAS", "id": "VariableID:1:7" } ] } */ ``` -------------------------------- ### Async/Await Fetch Example Source: https://developers.figma.com/docs/plugins/async-tasks Illustrates fetching data using async/await syntax with try...catch for error handling. The plugin is closed after the operation. ```javascript async function fetchData(){ try { const response = await fetch("https://httpbin.org/anything"); const text = await response.text(); console.log(`Response text is: ${text}`); } catch (error) { console.error(error); } figma.closePlugin(); } fetchData(); ``` -------------------------------- ### figma.timer.total Source: https://developers.figma.com/docs/plugins/api/figma-timer Gets the total time set for the timer in seconds. Returns 0 if the timer has not been started. ```APIDOC ## figma.timer.total ### Description Gets the total time set for the timer in seconds. If the timer has not been started, returns 0. The total time is defined as the time the timer was initially started at, plus or minus any time that may have been added or removed from the timer. ### Property - **total** (number) - Readonly. Total time on timer, in seconds. ``` -------------------------------- ### Instance Component Properties for Components Output Source: https://developers.figma.com/docs/plugins/api/properties/ComponentPropertiesMixin-componentpropertydefinitions Example output of `instance.componentProperties` for an instance of a main component, showing the current values for boolean and instance swap properties. ```json { ImageVisible#0:0: { type: 'BOOLEAN', value: true, }, Icon#0:1: { type: 'INSTANCE_SWAP', value: '1:24', }, } ``` -------------------------------- ### boundVariables Source: https://developers.figma.com/docs/plugins/api/LineNode Retrieves the variables bound to specific fields on this node. Refer to the Working with Variables guide for details on getting and setting variable bindings. ```APIDOC ## boundVariables ### Description The variables bound to a particular field on this node. Please see the Working with Variables guide for how to get and set variable bindings. ### Property Type { readonly [field in VariableBindableNodeField]?: VariableAlias} & { readonly [field in VariableBindableTextField]?: VariableAlias[]} & { fills?: VariableAlias[]; strokes?: VariableAlias[]; effects?: VariableAlias[]; layoutGrids?: VariableAlias[]; componentProperties?: { [propertyName: string]: VariableAlias }; textRangeFills?: VariableAlias[] } [readonly] ``` -------------------------------- ### gridColumnAnchorIndex Source: https://developers.figma.com/docs/plugins/api/EllipseNode Gets the read-only starting column index for a node within its parent grid, applicable only on direct children of grid auto-layout frames. ```APIDOC ## gridColumnAnchorIndex: number [readonly] Applicable only on direct children of grid auto-layout frames. Determines the starting column index for this node within the parent grid. ``` -------------------------------- ### Creating a New Plugma Project Source: https://developers.figma.com/docs/plugins/libraries-and-bundling Initializes a new Figma plugin project using the Plugma toolkit. Follow the prompts to configure your project. ```bash npm create plugma@latest ``` -------------------------------- ### gridRowAnchorIndex Source: https://developers.figma.com/docs/plugins/api/EllipseNode Gets the read-only starting row index for a node within its parent grid, applicable only on direct children of grid auto-layout frames. ```APIDOC ## gridRowAnchorIndex: number [readonly] Applicable only on direct children of grid auto-layout frames. Determines the starting row index for this node within the parent grid. ``` -------------------------------- ### Creating a New Project with Create Figma Plugin Source: https://developers.figma.com/docs/plugins/libraries-and-bundling Initializes a new Figma plugin project using the Create Figma Plugin toolkit. This toolkit comes with pre-configured bundling and UI components. ```bash npx --yes create-figma-plugin ``` -------------------------------- ### gridRowAnchorIndex Source: https://developers.figma.com/docs/plugins/api/properties/nodes-gridrowanchorindex Gets or sets the starting row index for a node within a parent grid. This property is applicable only to direct children of grid auto-layout frames. ```APIDOC ## gridRowAnchorIndex ### Description Gets or sets the starting row index for a node within a parent grid. This property is applicable only to direct children of grid auto-layout frames. The row index is 0-based, where 0 is the first row in the grid. This property works in conjunction with gridRowSpan to determine the node's row position and size in the grid. ### Signature `gridRowAnchorIndex: number` [readonly] ### Remarks If the index provided is greater than the number of rows in the grid, the setter will throw an error. If the index provided results in the node overlapping with another node in the grid, the setter will throw an error. ### Supported Nodes * BooleanOperationNode * ComponentNode * ComponentSetNode * EllipseNode * FrameNode * GroupNode * HighlightNode * InstanceNode * LineNode * PolygonNode * RectangleNode * SliceNode * SlideNode * SlotNode * StampNode * StarNode * TextNode * TextPathNode * TransformGroupNode * VectorNode * WashiTapeNode ``` -------------------------------- ### gridColumnAnchorIndex Source: https://developers.figma.com/docs/plugins/api/properties/nodes-gridcolumnanchorindex Gets or sets the starting column index for a node within a parent grid. This property is applicable only to direct children of grid auto-layout frames. ```APIDOC ## gridColumnAnchorIndex ### Description Determines the starting column index for this node within the parent grid. Applicable only on direct children of grid auto-layout frames. ### Signature `gridColumnAnchorIndex: number [readonly]` ### Remarks The column index is 0-based, where 0 is the first column in the grid. This property works in conjunction with `gridColumnSpan` to determine the node's column position and size in the grid. If the index provided is greater than the number of columns in the grid, the setter will throw an error. If the index provided results in the node overlapping with another node in the grid, the setter will throw an error. ### Supported on: * BooleanOperationNode * ComponentNode * ComponentSetNode * EllipseNode * FrameNode * GroupNode * HighlightNode * InstanceNode * LineNode * PolygonNode * RectangleNode * SliceNode * SlideNode * SlotNode * StampNode * StarNode * TextNode * TextPathNode * TransformGroupNode * VectorNode * WashiTapeNode ``` -------------------------------- ### Basic Promise Fetch Example Source: https://developers.figma.com/docs/plugins/async-tasks Demonstrates fetching data from an API using Promises and handling the response. The plugin is closed after the data is processed. ```javascript const fetchPromise = fetch("https://httpbin.org/anything"); fetchPromise.then((response) => { const textPromise = response.text(); textPromise.then((data) => { console.log(data); figma.closePlugin(); }); }); ``` -------------------------------- ### Plugin Operations Valid in Dev Mode Source: https://developers.figma.com/docs/plugins/working-in-dev-mode These are examples of operations that are permitted in Dev Mode, including getting nodes, reading properties, showing the UI, and listening to events. ```typescript // Get a node const node = await figma.getNodeByIdAsync('1:12'); // Read a property console.log(node.name) // showUI figma.showUI(__html__) // listen to events figma.on('selectionchange', () => { // Do something }) ``` -------------------------------- ### Component Property Definitions for Components Output Source: https://developers.figma.com/docs/plugins/api/properties/ComponentPropertiesMixin-componentpropertydefinitions Example output of `component.componentPropertyDefinitions`, showing boolean and instance swap properties available on a main component. ```json { ImageVisible#0:0: { type: 'BOOLEAN', defaultValue: true, }, Icon#0:1: { type: 'INSTANCE_SWAP', defaultValue: '7:23', }, } ``` -------------------------------- ### InstanceNode Methods Source: https://developers.figma.com/docs/plugins/api/InstanceNode Methods for resizing, rescaling, and managing aspect ratio and exports. ```APIDOC ## InstanceNode Methods ### resize(width: number, height: number): void Resizes the node. If the node contains children with constraints, it applies those constraints during resizing. If the parent has auto-layout, causes the parent to be resized. ### resizeWithoutConstraints(width: number, height: number): void Resizes the node. Children of the node are never resized, even if those children have constraints. If the parent has auto-layout, causes the parent to be resized (this constraint cannot be ignored). ### rescale(scale: number): void Rescales the node. This API function is the equivalent of using the Scale Tool from the toolbar. ### lockAspectRatio(): void Locks the node's `targetAspectRatio` to the current ratio of its width and height. ### unlockAspectRatio(): void Unlocks the node's `targetAspectRatio`. ### exportAsync(settings?: ExportSettings): Promise ### exportAsync(settings: ExportSettingsSVGString): Promise ### exportAsync(settings: ExportSettingsREST): Promise Exports the node as an encoded image. If the manifest contains `"documentAccess": "dynamic-page"`, **and** the node is a `PageNode`, you must first call `loadAsync` to access this function. ``` -------------------------------- ### Managing DevResources on a Node Source: https://developers.figma.com/docs/plugins/api/DevResource Provides examples for interacting with DevResources associated with a Figma node. This includes getting existing links, adding new ones, editing them, and deleting them. ```typescript const node = figma.currentPage.selection[0] // Get related link const links = await node.getDevResourcesAsync() // Get related link from node and all of its children const links = await node.getDevResourcesAsync({ includeChildren: true }) // Add a related link await node.addDevResourceAsync('https://google.com') // Edit related link await node.editDevResourceAsync( 'https://google.com', { name: 'Hotels', url: 'https://hotels.com' } ) // Delete related link await node.deleteDevResourceAsync('https://hotels.com') ``` -------------------------------- ### Show Basic UI with Options Source: https://developers.figma.com/docs/plugins/api/properties/figma-showui Renders a simple HTML string in a UI window with specified dimensions and title. Use this for basic UI displays. ```typescript figma.showUI( "Hello from Figma", { width: 400, height: 200, title: "My title" } ) ``` -------------------------------- ### getRangeBoundVariable Source: https://developers.figma.com/docs/plugins/api/node-properties Gets the `boundVariable` for a specified field from characters within a given range (start inclusive, end exclusive) of a text node. Returns `VariableAlias | null | figma.mixed`. Supported on TextNode and related types. ```APIDOC ## getRangeBoundVariable(start: number, end: number, field: VariableBindableTextField): VariableAlias | null | figma.mixed ### Description Get the `boundVariable` for a given field from characters in range `start` (inclusive) to `end` (exclusive). ### Method Synchronous function call ### Parameters #### Path Parameters - **start** (number) - Required - The starting index of the range (inclusive). - **end** (number) - Required - The ending index of the range (exclusive). - **field** (VariableBindableTextField) - Required - The field to get the bound variable for. ``` -------------------------------- ### UI File Configuration in manifest.json Source: https://developers.figma.com/docs/plugins/api/global-objects Shows how to configure UI files in the manifest.json for a plugin. ```json "ui": { "main": "main.html", "secondary": "secondary.html" } ``` -------------------------------- ### setBoundVariable(field, variable) Source: https://developers.figma.com/docs/plugins/api/VectorNode Binds the provided `field` on this node to the given variable. Please see the Working with Variables guide for how to get and set variable bindings. If `null` is provided as the variable, the given `field` will be unbound from any variables. ```APIDOC ## setBoundVariable(field, variable) ### Description Binds the provided `field` on this node to the given variable. Please see the Working with Variables guide for how to get and set variable bindings. If `null` is provided as the variable, the given `field` will be unbound from any variables. ### Method POST/PUT (conceptual) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters - **field** (VariableBindableNodeField | VariableBindableTextField) - Required - The field on this node to bind. - **variable** (Variable | null) - Required - The variable to bind the field to, or null to unbind. ``` -------------------------------- ### boundVariables Source: https://developers.figma.com/docs/plugins/api/PolygonNode Provides access to variables bound to specific fields on a node, including fills, strokes, effects, layout grids, component properties, and text range fills. Refer to the Working with Variables guide for detailed instructions on getting and setting these bindings. ```APIDOC ## boundVariables?: { readonly [field in VariableBindableNodeField]?: VariableAlias} & { readonly [field in VariableBindableTextField]?: VariableAlias[]} & { fills?: VariableAlias[]; strokes?: VariableAlias[]; effects?: VariableAlias[]; layoutGrids?: VariableAlias[]; componentProperties?: { [propertyName: string]: VariableAlias }; textRangeFills?: VariableAlias[] } [readonly] ### Description The variables bound to a particular field on this node. Please see the Working with Variables guide for how to get and set variable bindings. ### Type Readonly object containing variable bindings for various fields. ``` -------------------------------- ### InstanceNode Methods Source: https://developers.figma.com/docs/plugins/api/InstanceNode Provides information about the methods available for InstanceNodes, including cloning, getting the main component, swapping components, setting properties, detaching, and removing overrides. ```APIDOC ## InstanceNode Methods ### clone(): InstanceNode Duplicates the instance node. The new instance has the same main component. By default, the duplicate's parent is `figma.currentPage`. ### getMainComponentAsync(): Promise The component that this instance reflects. This could be a remote, read-only component. This can be set to turn this instance into a different component. On nested instances (instances inside other instances), setting this value clears all overrides and performs nested instance swapping. ### swapComponent(componentNode: ComponentNode): void Swaps this instance's current main component with `componentNode` and preserves overrides using the same heuristics as instance swap in the Figma editor UI. Note that we may update these override preservation heuristics from time to time. ### setProperties(properties: { [propertyName: string]: string | boolean | VariableAlias }): void Sets the component properties and values for this instance. `propertyName` corresponds to the names returned by `componentPropertyDefinitions` and should be suffixed with `'#'` and a unique ID for `'TEXT'`, `'BOOLEAN'`, and `'INSTANCE_SWAP'` properties. Does not support `'SLOT'` properties and will throw `cannotSetSlotProperty`. In the case of name collision, this function prioritizes updating the `'VARIANT'` type properties. Existing properties that are non-specified in the function will maintain their current value. ### detachInstance(): FrameNode Detaches the given instance from its component. Returns the frame node that results from detaching the instance. For nested instances (instances inside of other instances), also detaches all ancestors nodes that are instances. ### resetOverrides(): void **DEPRECATED:** Use `removeOverrides` instead. Resets all direct overrides on this instance. ### removeOverrides(): void Removes all direct overrides on this instance. ``` -------------------------------- ### Creating a New Project with ai-plugin-template Source: https://developers.figma.com/docs/plugins/libraries-and-bundling Initializes a new Figma plugin project using the official ai-plugin-template, which is based on Next.js for OpenAI integrations. Follow the instructions in the generated README.md. ```bash npx create-next-app@latest --example https://github.com/figma/ai-plugin-template/ ``` -------------------------------- ### Bundle Plugin Code with Webpack and Use React with TSX Source: https://developers.figma.com/docs/plugins/samples This example demonstrates bundling plugin code using Webpack and utilizing React with TSX for building the plugin's user interface. ```bash $ npm install $ npm run build ``` ```typescript // Source code for React plugin ``` -------------------------------- ### Start and Log Timer Remaining Time Source: https://developers.figma.com/docs/plugins/api/properties/figma-on Demonstrates starting a timer and logging its remaining time using the figma.timer interface. The timer is started with a duration of 300 seconds. ```typescript figma.on("timerstart", () => console.log(figma.timer.remaining)) figma.timer.start(300) // Output: // 300 ``` -------------------------------- ### timerstart Source: https://developers.figma.com/docs/plugins/api/properties/figma-on This event will trigger when somebody starts a timer in the document, either from the UI or by plugin code. Use `figma.timer` to inspect the timer's state. ```APIDOC ## timerstart ### Description This event will trigger when somebody starts a timer in the document. This can happen either by a user (either the current user or a multiplayer user) starting the timer from the UI, or triggered by plugin code. ### Usage Example ```typescript figma.on("timerstart", () => console.log(figma.timer.remaining)) figma.timer.start(300) // Output: // 300 ``` ``` -------------------------------- ### Guide Interface Definition Source: https://developers.figma.com/docs/plugins/api/Guide Defines the structure for a Guide object, specifying its orientation (axis) and position (offset). Guides are used for visual alignment within the Figma canvas or frames. ```typescript interface Guide { readonly axis: "X" | "Y" readonly offset: number } ``` -------------------------------- ### Grid Track Reordering Example Source: https://developers.figma.com/docs/plugins/api/GridTrackReorderOptions Illustrates the concept of reordering grid tracks using fromIndices and insertionIndex. The diagram shows possible insertion points relative to existing track indices. ```text 0 1 2 3 4 ← possible insertion indices ---- 0 --- --- 1 --- --- 2 --- --- 3 ---- ← track indices +-------------------+---------+---------+ | | | | | | | | +---------+---------+---------+---------+ | | | | | | | | | | +---------+---------+---------+---------+ ``` -------------------------------- ### Basic TypeScript Example with Type Annotations Source: https://developers.figma.com/docs/plugins/typescript Demonstrates basic type annotations in TypeScript for variables and function parameters. This helps in understanding how to add type information to your code. ```typescript let list: string[] = [] for (const node of figma.currentPage.selection) { list.push(node.type) } function doThing(x: number, str: string) { // ... } ``` -------------------------------- ### Plugin Manifest with Network Access Source: https://developers.figma.com/docs/plugins/updates/2023/05/10/version-1-update-66 Example of a `manifest.json` file including the `networkAccess` key with a list of allowed domains. This configuration specifies domains that the plugin is permitted to access. ```json { "name": "MyPlugin", "id": "737805260747778092", "api": "1.0.0", "main": "code.js", "ui": "ui.html", "networkAccess": { "allowedDomains": ["https://my-app.cdn.com", "wss://socket.io", "*.example.com", "example.com/api/", "exact-path.com/content"] } } ``` -------------------------------- ### Basic manifest.json with networkAccess key Source: https://developers.figma.com/docs/plugins/making-network-requests This snippet shows the initial structure of `manifest.json` with the `networkAccess` key and its default empty arrays for domains. ```json { "name": "MyPlugin", "id": "737805260747778092", "api": "1.0.0", "main": "code.js", "ui": "ui.html", "networkAccess": { "allowedDomains": [], "reasoning": "", "devAllowedDomains": [] } } ``` -------------------------------- ### run Source: https://developers.figma.com/docs/plugins/api/properties/figma-on This event is triggered when a plugin is run. For plugins with parameters, this happens after all parameters have been entered by the user in the quick action UI. For all other plugins, this happens immediately after launch. ```APIDOC ## run ### Description This event is triggered when a plugin is run. For plugins with parameters, this happens after all parameters have been entered by the user in the quick action UI. For all other plugins, this happens immediately after launch. ### Event Payload ```typescript interface RunEvent { parameters?: ParameterValues command: string } ``` - `parameters`: An optional object of type `ParameterValues` containing the values entered for each parameter. - `command`: A string representing the command, equivalent to `figma.command`. ### Handling Handling the `run` event is only required for plugins with parameters. For all plugins, it can be a convenient place to put top-level code as it is called on every plugin run. ``` -------------------------------- ### Plugin Manifest with Parameter List Source: https://developers.figma.com/docs/plugins/plugin-parameters Define a list of parameters for your plugin in the manifest.json file. Each parameter requires a 'name' and a 'key'. Optional flags like 'allowFreeform' and 'optional' can be set. ```json { "name": "Plugin with parameters", "api": "1.0.0", "main": "code.js", "editorType": [ "figma", "figjam" ], "documentAccess": "dynamic-page", "parameters": [ { "name": "Icon name", "key": "icon-name" }, { "name": "Size", "key": "size", "allowFreeform": true }, { "name": "Color", "key": "color", "allowFreeform": true, "optional": true } ] } ``` -------------------------------- ### Example CSS Variables: Prominence Source: https://developers.figma.com/docs/plugins/css-variables Provides examples of CSS variables using 'secondary' prominence for text and 'strong' prominence for borders, used to create visual hierarchy. ```css --figma-color-text-secondary --figma-color-border-strong ``` -------------------------------- ### createSlideRow Source: https://developers.figma.com/docs/plugins/api/properties/figma-createsliderow Creates a new Slide Row, which automatically gets appended to the Slide Grid. By default, the row gets appended to the end of the Slide Grid. To specify a position, pass a row index to the function. ```APIDOC ## createSlideRow ### Description Creates a new Slide Row, which automatically gets appended to the Slide Grid. By default, the row gets appended to the end of the Slide Grid. To specify a position, pass a row index to the function. ### Signature `createSlideRow(row?: number): SlideRowNode` ### Remarks - If no `row` index is provided, the slide row is appended to the end of the Slide Grid. - If a `row` index is provided, the slide row is inserted at that specific index. ### Example: Create a slide row at the end of the grid ```javascript const slideRow = figma.createSlideRow() ``` ### Example: Create a slide row at index 0 ```javascript const slideRow = figma.createSlideRow(0) ``` ``` -------------------------------- ### Set String Suggestions Source: https://developers.figma.com/docs/plugins/api/figma-parameters Provides a list of simple string suggestions to the user in the quick action UI. Filters suggestions based on the current query. ```typescript result.setSuggestions( ["Armadillo", "Baboon", "Cacatua", "Dolphin"] .filter(s => s.includes(query))) ``` -------------------------------- ### Basic Plugin Manifest Source: https://developers.figma.com/docs/plugins/manifest A basic example of a manifest.json file for a Figma plugin. This file defines essential properties like name, ID, API version, and entry points for the plugin's code and UI. ```json { "name": "MyPlugin", "id": "737805260747778092", "api": "1.0.0", "editorType": ["figma", "figjam"], "main": "code.js", "ui": "ui.html", "documentAccess": "dynamic-page", "networkAccess": { "allowedDomains": ["none"] } } ``` -------------------------------- ### Content Security Policy (CSP) Error Example Source: https://developers.figma.com/docs/plugins/making-network-requests Example of a Content Security Policy error message encountered when a network request is blocked due to domain restrictions. This indicates that the requested domain is not listed in `allowedDomains`. ```text Refused to connect to 'https://httpsbin.org/' because it violates the following Content Security Policy directive: "default-src data:". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback. ``` -------------------------------- ### Get Estimated Auto Layout Properties Source: https://developers.figma.com/docs/plugins/updates/2023/06/21/version-1-update-68 Use `node.inferredAutoLayout` to get estimated auto layout properties for a `FrameNode` and its children, even if they don't explicitly use auto layout. This aids in generating more accurate code for responsive designs. ```typescript const autoLayoutProps = node.inferredAutoLayout; ``` -------------------------------- ### Example CSS Variables: Type Source: https://developers.figma.com/docs/plugins/css-variables Demonstrates CSS variables for the 'bg' (background) and 'text' types, which are required parameters for defining color tokens. ```css --figma-color-bg --figma-color-text ``` -------------------------------- ### Instance Component Properties Structure Source: https://developers.figma.com/docs/plugins/api/properties/ComponentPropertiesMixin-componentpropertydefinitions An example of the structure returned by `instance.componentProperties`, displaying the current values set for each component property on an instance. ```json { Size: { type: 'VARIANT', value: 'Medium', }, IconVisible#0:0: { type: 'BOOLEAN', value: false, }, ButtonText#0:1: { type: 'TEXT', value: 'cancel', }, IconInstance#0:2: { type: 'INSTANCE_SWAP', defaultValue: '1:1', preferredValues: [ {type: 'COMPONENT', key: 'ckey1'}, {type: 'COMPONENT_SET', key: 'sgkey1'} ], }, } ``` -------------------------------- ### Codegen Preferences Example Source: https://developers.figma.com/docs/plugins/manifest Specifies a list of preferences for a codegen plugin, including custom units, select options, and actions. Supports custom scaled units and language-specific inclusions. ```json "codegenPreferences": [ // Optional but a unit itemType can be used to specify that the plugin supports a custom scaled unit. By default, all plugins // support the pixel unit. { "itemType": "unit", "scaledUnit": "Rem", "defaultScaleFactor": 16, // Optional, if true the scaled unit is the default. "default": true, // Optional, if omitted, all languages are included. "includedLanguages": [] }, { "itemType": "select", "propertyName": "tabSize", "label": "Tab Size", "options": [ {"label": "2", "value": "2", isDefault: true }, {"label": "4", "value": "4"}, {"label": "8", "value": "8"} ], // Optional, if omitted, all languages are included. "includedLanguages": ["tailwind"] }, { "itemType": "action", "propertyName": "showMore", "label": "More settings..." // Optional, if omitted, all languages are included. "includedLanguages": ["tailwind"], }, ] ``` -------------------------------- ### fontWeight Source: https://developers.figma.com/docs/plugins/api/node-properties Gets the font weight for text nodes. ```APIDOC ## fontWeight: number | figma.mixed [readonly] ### Description The weight of the font (e.g. 400 for "Regular", 700 for "Bold"). ### Method fontWeight (getter) ### Parameters None ### Response #### Success Response (200) * **number | figma.mixed** - The current font weight. #### Response Example ```json { "example": "400" } ``` ```