figma / code-connect

A tool for connecting your design system components in code with your design system in Figma
MIT License
972 stars 70 forks source link

[SwiftUI] Support for Adding Imports in SwiftUI with Code Connect #185

Open mackoj opened 1 month ago

mackoj commented 1 month ago

The documentation for SwiftUI shows an approach for handling imports that seems unfamiliar in a typical Swift environment. The concept of handling imports with paths doesn’t align with how imports are generally managed in Swift, which doesn’t require paths. I’m trying to figure out the correct way to add imports in the generated Swift code.

I attempted the following configuration:

{
  "codeConnect": {
    "swiftPackagePath": "Package.swift",
    "importMapping": {
      ".": "import VitaminPlay"
    }
  }
}

However, this did not work as expected.

In the React SDK, there is an API to add imports, and it works well. I would like to achieve something similar for Swift. Specifically, I want to be able to add imports like the following at the top of a Figma-generated SwiftUI snippet:

import SwiftUI
import VitaminPlay

Potential Approach:

One possible solution could be to allow the importMapping field to accept an array of imports, making it easier to add multiple imports. Alternatively, this functionality could be implemented using Swift Syntax to dynamically extract and add the necessary imports from the code.

Here’s an example of how you could achieve this using Swift Syntax:

import Foundation
import SwiftSyntax

class GetImportVisitor: SyntaxRewriter {
  var imports: [String] = []

  override func visit(_ node: ImportPathComponentSyntax) -> ImportPathComponentSyntax {
    imports.append(node.name.text.trimmingCharacters(in: .whitespacesAndNewlines))
    return node
  }

  func drain() -> [String] {
    return imports
  }
}

Would it be possible to implement this kind of functionality in the Code Connect SDK? This feature would make managing imports much more straightforward when working with Swift code generated from Figma.

Environement:

Thanks in advance for your help!

tomduncalf-figma commented 1 month ago

Hey @mackoj, thank you for the feedback here. I'm not a Swift expert but I can see how this doesn't necessarily align with how imports are usually done in Swift, and also isn't very well documented. I'm going to raise this for discussion with the team, having the ability to pass an array of strings to override the imports as in React could make a lot of sense. I'll update you when we have more to share

mackoj commented 1 month ago

Thanks @tomduncalf-figma