0

I am writing a Figma plugin to generate a random colour and modify the fill of a selection. This works fine when the selection node has a fill. But when there is no fill I get an error when trying to apply fills[0].color = newColor;.

When logging the fill on that node I get [] which I'm assuming is an empty array. Figma nodes can have multiple fills and requires the format node.fills[1].color when assigning values.

So how can I create a color assignment for a node where there is an empty array?

import chroma from '../node_modules/chroma-js/chroma'
import clone from './clone'

for (const node of figma.currentPage.selection) {

  if ("fills" in node) {

    const fills = clone(node.fills);

    // Get a random colour from chroma-js.
    const random = chroma.random().gl();

    // Create an array that matches the fill structure (rgb represented as 0 to 1)
    const newColor = {r: random[0], g: random[1], b: random[2]};

    // Only change the first fill
    fills[0].color = newColor;

    // Replace the fills on the node.
    node.fills = fills;
  }
}

// Make sure to close the plugin when you're done. Otherwise the plugin will
// keep running, which shows the cancel button at the bottom of the screen.
figma.closePlugin();
Craig
  • 972
  • 3
  • 13
  • 38

1 Answers1

0

I have a solution (not necessarily correct).

It looks like I need to check if the original node has an array and if not, create a complete object within an array. I think I had the structure wrong when I attempted this before.

import chroma from '../node_modules/chroma-js/chroma'
import clone from './clone'

for (const node of figma.currentPage.selection) {

  if ("fills" in node) {

    let fills;

    // Check to see if the initial node has an array and if it's empty
    if (Array.isArray(node.fills) && node.fills.length) {

      // Get the current fills in order to clone and modify them      
      fills = clone(node.fills);

    } else {

      // Construct the fill object manually
      fills = [{type: "SOLID", visible: true, opacity: 1, blendMode: "NORMAL", color: {}}]
    }

      // Get a random colour from chroma-js.
      const random = chroma.random().gl();

      // Create an array that matches the fill structure (rgb represented as 0 to 1)
      const newColor = {r: random[0], g: random[1], b: random[2]};

      // Only change the first fill
      fills[0].color = newColor;

      // Replace the fills on the node.
      node.fills = fills;

    // }
  }
}

// Make sure to close the plugin when you're done. Otherwise the plugin will
// keep running, which shows the cancel button at the bottom of the screen.
figma.closePlugin();
Craig
  • 972
  • 3
  • 13
  • 38