figma / plugin-typings

Typings for the Figma Plugin API
MIT License
190 stars 44 forks source link

Can't access node parent and children properties #260

Closed gabrielrbarbosa closed 11 months ago

gabrielrbarbosa commented 11 months ago

Example here: https://github.com/gabrielrbarbosa/figma-to-bootstrap-plugin/blob/b1d597cf6ae56d62b547cabd65ae71aadc53b53e/src/bootstrap/bootstrapMain.ts#L230

I had to add // @ts-ignore for each of these calls: node.parent.width or node.children

Is there anything missing? Thanks

james04321 commented 11 months ago

This is because nodes aren't guaranteed to have width and children properties. A better approach might be:

export const bootstrapGrid = (
    node: SceneNode
  ) : string => {
    let classes = '';

    if (node.parent && 'width' in node.parent) {
      let breakpoint = '';

      if (node.parent.width > 1400) breakpoint = 'xxl-'; 
      else if(node.parent.width > 1200) breakpoint = 'xl-'; 
      else if(node.parent.width > 992) breakpoint = 'lg-'; 
      else if(node.parent.width > 768) breakpoint = 'md-'; 
      else if(node.parent.width > 768) breakpoint = 'sm-';
      else breakpoint = '';

      //console.log(node.name + ': ' + node.width + '/' + node.parent.width + '*12=' + Math.round(node.width / node.parent.width * 12));
      classes += `col-${breakpoint}${Math.round(node.width / node.parent.width * 12)}`;
    }

    if ('children' in node && node.children.length > 1) {
      classes += ' row';
    }

    return classes;
  };