Skip to content

Good way to get slot children? #387

@adbutterfield

Description

@adbutterfield

We started updating our component library to use slots, which is really helpful because we use atomic design.

However it feels like the code connect API for slots could have bit better DX.

For now, I'm doing like this:

const slotNames = Object.keys(instance.slots || {});
if (slotNames.length === 1) {
  const slotChildren = instance
      .findConnectedInstances((ci) => {
        const path = ci.path || [];
        return path[path.length - 1] === slotNames[0];
      });
}

Things in the API we have available currently:

instance.slots
returns something like:

{
  "Contents": {
    "guid": "1234:5678",
    "developerFriendlyId": "9012:13456:7890"
  }
}

instance.getSlot("Contents")
returns something like:

[
  {
     "type": "SLOT",
     "guid": "1234:5678",
     "propertyName": "Contents"
   }
]

figma.properties.slot("Contents")
returns something like:

[
  {
     "type": "SLOT",
     "guid": "1234:5678",
     "propertyName": "Contents"
   }
]

All three of those options don't give us any information about what's in the slot.

It might help a bit to understand our use cases where the current API makes things difficult for us.
1) Component has slot along with other components as siblings
In some cases we have a slot in the design component that we use as the children of the component in code, and the siblings are baked in parts of the component, so we don't actually need to generate code snippets for. For this case we can't simply use instance.findConnectedInstances() because it gives us the slot children + siblings (which we don't want to generate code snippets for).

2) Component has multiple slots (and potentially siblings)
Some components have multiple slots, like multi-column layout components. For these cases we have to use the filter method twice. I've started creating helper functions to reduce duplicated code. But DX also isn't ideal with this approach, because I have to copy/paste these helper functions in multiple templates. (I'm considering implementing a custom build step so I can import custom helpers from an external file and have them inlined before publish).

Final thought, in generally generating code for slots seems brittle too because designers who use the components can change the name of the slot and it will break code connect since it relies on hardcoded names. I think we could make things smoother and less brittle if we had a method to get an instance by guid. But I guess slots aren't instances, so maybe it still wouldn't help us here...

Code Connect CLI version: 1.4.3

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions