Working with Nodes
Nodes are the building blocks that make up the content in a project. They are represented as "layers" in the editor UI.
There are different types of nodes, each with their own set of properties and methods:
FrameNode
TextNode
SVGNode
CodeComponentNode
UnknownNode
Getting Nodes
Most of the time users will be selecting nodes on the canvas and running plugins based on their selection. The following code returns an array of nodes.
You can also subscribe to the selection to by notified when it changes.
All nodes have an unique ID. If you know the ID of a node, you can get it specifically.
It's possible to also get nodes all the Nodes in a Project that match a certain criteria. In these cases you can use the getNodesWith…()
set of APIs.
This will return an array of Nodes that match the criteria you set, with options for Node types and attributes.
This API can also be used to query within a selection.
A more complete use case, would be a hook that gets all the background images within set on Frames within a project. Here is an example implementation of that.
Creating Nodes
Create a generic frame node. This creates a frame on the canvas
To add text to the canvas
Other more specific nodes can be used to add text, images or code components. See docs on how to create them:
Traits
Traits are a way to differentiate between kinds of nodes, or nodes with specific attributes.
For example, to check if the selected node is text, we can use the isTextNode
trait function:
Other trait functions for checking the node type include:
isFrameNode
isTextNode
isSVGNode
isCodeComponentNode
Traits can also be used to check if a node has a specific attribute. This is useful because different node types may have similar attributes. For example, all nodes have a position.
To check if a node has a specific attribute, use a trait function that begins with the word "supports".
For example, logging out all the locked layers that support setting a background image:
Some other trait functions for checking node attributes include:
supportsPosition
supportsVisible
supportsRotation
supportsBackgroundGradient
supportsBorderRadius
To see a full list, check the types file index.d.ts
.
Replicas
Every node has a `isReplica` property that indicate if the node is a replica. Replica nodes are used within non-primary Breakpoints and Component variants and inherit attributes from the primary variant or breakpoint. Once a specific attribute is overridden on a replica node, it is no longer inherited from the primary node and is instead set on that replica.
Children & Parents
If you need to access the children or parents of a layer, you can do that via the getParent()
or getChildren()
async functions.
Working with Async Layer APIs
Example of combining async APIs for layers.