How to access the full dictionary in registerTransform method in StyleDictionary?

588 Views Asked by At

Pretty simple question, I'm registering a transformation and the transformer need one item, actually one design token, that lives in the same file I'm applying this transformation. So I would need to access the dictionary.properties to retrieve this element via its name, used to transform all the others.

    this.#handler.registerTransform({
      name: 'my/size/transform',
      type: 'value',
      matcher: (prop) => {
        return prop?.attributes?.category === 'size'
      },
      transformer: (prop, options) => {
        return parseFloat(prop.original.value) + [A DESIGN TOKEN DATA COMING FROM DICTIONARY];
      }
    })

in transformer I've access only to prop and options, not enough and I don't think it is information available in this.#handler too (to clarify this.#handler = require('style-dictionary')) is it possible to have access to this info? thanks

1

There are 1 best solutions below

0
On BEST ANSWER

I found out this approach, since there is the prop.filePath information, I read it directly from file system and parse it as an object. It works, I don't see substantial decrease of performances (because this access is done in a loop), but it works:

    this.#handler.registerTransform({
      name: 'my/size/transform',
      type: 'value',
      matcher: (prop) => {
        return prop?.attributes?.category === 'size'
      },
      transformer: (prop) => {
        const dictionary = JSON.parse(
          fs.readFileSync(prop.filePath).toString()
        )
        return parseFloat(prop.original.value) + dictionary['design-token-to-fetch'].value;
      }
    })

Maybe like this to reduce the file system access:

    let dictionary: any

    this.#handler.registerTransform({
      name: 'my/size/transform',
      type: 'value',
      matcher: (prop) => {
        return prop?.attributes?.category === 'size'
      },
      transformer: (prop) => {
        dictionary ??= JSON.parse(
          fs.readFileSync(prop.filePath).toString()
        )
        return parseFloat(prop.original.value) + dictionary['design-token-to-fetch'].value;
      }
    })

Better ideas are more than welcome!