I would appreciate some guidance on figma.variables. setBoundVariableForPaint method.
I would like to run a simple script to bind a variable to the existing style. This is what I tried
// get a style ref
let style = figma.getLocalPaintStyles()[0];
// get a var ref
let variable = figma.variables.getVariableById("VariableID:1:53");
// bind?
figma.variables.setBoundVariableForPaint(style.paints[0], 'color', variable);
It returns a solid paint indeed, however, it has no effect on a given style. Confusing…
Very confusing API indeed. I think there’s an issue with your code, afaik you can’t update paints of existing styles, which has been a shortcoming I haven’t been able to overcome and I think is not possible (no updateLocalStyles for instance only create). The line style.paints = newPaints; shouldn’t work I believe, although confusingly it doesn’t give a warning when using TypeScript, the type is typed as readonly Paint[].
Update:
To my surprise it’s possible to update paints by reassigning, I wish I tried this approach before! I was able to create the styles to variables functionality similar to Styles-to-Variables-Converter.
My code is as follows that might benefit others:
const localPaintStyles = figma
.getLocalPaintStyles()
.filter((style) => style.paints[0].type === "SOLID");
const date = new Date();
const collectionName = `Colors (imported at ${date.toLocaleString()})`;
const collection = figma.variables.createVariableCollection(collectionName);
collection.name = collectionName;
for (const paintStyle of localPaintStyles) {
// Create variable.
const colorVariable = figma.variables.createVariable(
paintStyle.name,
collection.id,
"COLOR"
);
// This only works for single color per style.
const solidPaint = paintStyle.paints[0] as SolidPaint
// Set the current color to the first mode.
colorVariable.setValueForMode(
collection.modes[0].modeId,
solidPaint.color
);
// Also port the description of the paint style.
colorVariable.description = paintStyle.description
// Update the color style to use the variable.
const newPaint = figma.variables.setBoundVariableForPaint(
solidPaint,
"color",
colorVariable
);
// Change the paint on the existing style to use the variable.
paintStyle.paints = [newPaint];
}
throws a ts error for colorVar in setBoundVariableForPaint. Any ideas as to why? The Variable is getting fetched from a variable file that is available to the file
Ultimately I’m trying to swap FillStyles with Color Variables is the goal. Seems like setBoundVariableForPaint is the obvious way to do that but I’m not 100% clear on the types of the properties in that method. Like what goes is the third param expecting here?