I’m building a Figma plugin using TypeScript and the figma-api. The plugin has a UI component and needs to track when users change their selection.
My plugin structure includes:
main.ts
- handles figma-api calls
interface.html
- contains the UI with embedded JavaScript
Currently I’m working with selection data like this:
const selectedItem = figma.currentPage.selection[0];
I need to detect when figma.currentPage.selection
changes so I can update the UI with fresh data. When someone clicks on a different element in the canvas, I want to automatically send the new selection info to my plugin interface.
What’s the best way to listen for these selection changes? Any suggestions would be helpful.
You can utilize the ‘selectionchange’ event listener in your main.ts file to effectively monitor selection changes in Figma. This event will enable you to capture updates and relay the changes to your UI as follows:
figma.on('selectionchange', () => {
const currentSelection = figma.currentPage.selection;
figma.ui.postMessage({
type: 'selection-updated',
selection: currentSelection
});
});
Make sure to implement a message listener in your interface.html to react to selection updates:
window.onmessage = (event) => {
if (event.data.pluginMessage.type === 'selection-updated') {
updateInterface(event.data.pluginMessage.selection);
}
};
This setup ensures your UI remains in sync with any selection changes.
use figma.on('selectionchange', callback)
in your main.ts. it triggers when selection changes and you can send the new data to your ui with postMessage. works perfectly!