frctl / fractal

A tool to help you build and document website component libraries and design systems.
https://fractal.build
MIT License
2.11k stars 168 forks source link

Allow context.variable.function in a component context. #697

Open samuelbirch opened 3 years ago

samuelbirch commented 3 years ago

Can it be supported that functions will work in the component context object.

module.exports = { context: { comeVariableName: { someFunction: function(param){ return "value"; } } } }

it can work in the same way as normal variables in terms of rendering the value. Its so we can use the syntax in twig.

mihkeleidast commented 3 years ago

The context is parsed into a JSON object and functions can not be represented in JSON as far as I know.

I investigated this in #539 a bit (since I would love to have this for React projects) but concluded that this is probably not going to happen because of the JSON requirement.

If you have any ideas on how to implement this without a breaking change, I'm all ears.

samuelbirch commented 3 years ago

would something like this work?

JSON.stringify( { a: 5 , b: x => x }, (k,v) => typeof v === "function" ? "" + v : v);

JSON.parse(json, (k,v) => typeof v === "string"? (v.startsWith('function')? eval("("+v+")") : v): v)

from: https://stackoverflow.com/questions/36517173/how-to-store-a-javascript-function-in-json

mihkeleidast commented 3 years ago

Not really - that technique is a bit hacky in the sense that it's basically a workaround for what JSON does not support. Additionally, the evaling of the string to be an actual function again is basically a security exploit waiting to happen and I would not allow this in Fractal source.