Determining library variable scope

Hi

I’ve used the following to help me populate dropdowns in my plugin with the variables that exist in a document.

I’m able to determine whether variable is a FLOAT or COLOR. However, I’d like to be able to determine if a FLOAT variable is scoped to a corner radius or a gap, etc.

Is there a way to do this?

Thanks in advance!

const libraryCollections = await figma.teamLibrary.getAvailableLibraryVariableCollectionsAsync();

    let colorVariablesList: Array<{ name: string; key: string }> = [];
    let floatVariablesList: Array<{ name: string; key: string }> = [];
  
    for (const collection of libraryCollections) {
      const variables = await figma.teamLibrary.getVariablesInLibraryCollectionAsync(collection.key);
  
      variables.forEach(variable => {
  
        let colorVariablename = `${variable.name}`;
        //create list of color variables
        if (variable.resolvedType === "COLOR") {
          // Push the variable into the variablesList
          colorVariablesList.push({ name: colorVariablename, key: variable.key });
        } else { // it's of type "FLOAT"
          floatVariablesList.push({ name: colorVariablename, key: variable.key });
        }
      });
    }

To get the scopes of a variable from a library, you must first import it and then access this property.

Thanks. Yeah, I’d tried scopes, but wasn’t getting anywhere.

On further inspection scopes isn’t available on a type LibraryVariable (which is what getVariablesInLibraryCollection returns). It’s only available on Variable.

I tried to do a further call to getVariableByIdAsync to see if could get more info, but LibraryVariable only has a key, not an ID (or at least it returned null for me).

I’m probably missing something obvious. Any ideas?

You missed importing a variable. Please see an example of using the getVariablesInLibraryCollectionAsync method.

1 Like

Thank you for pointing me in the right direction! I got there in the end! :slight_smile:

Here’s the code if anyone finds this useful…

for (const collection of libraryCollections) {
      const variables = await figma.teamLibrary.getVariablesInLibraryCollectionAsync(collection.key);

      for (const variable of variables) {
        const importedVariable = await figma.variables.importVariableByKeyAsync(variable.key);

        let variableName = `${importedVariable.name}`;

        if (variable.resolvedType === "COLOR") {
          colorVariablesList.push({ name: variableName, key: variable.key });
        } 
        if (variable.resolvedType === "FLOAT" && importedVariable.scopes.indexOf("GAP") !== -1) {
          spacingVariablesList.push({ name: variableName, key: variable.key });
        }
        if (variable.resolvedType === "FLOAT" && importedVariable.scopes.indexOf("CORNER_RADIUS") !== -1) {
          radiusVariablesList.push({ name: variableName, key: variable.key });
        }
      }
    }