teleport-code-generators
teleport-code-generators copied to clipboard
Support simple expressions in dynamic nodes
Context
When using a dynamic node, we reference the exact value of that prop/state/local var. Like in this example:
{
"type": "dynamic",
"content": {
"referenceType": "prop",
"id": "title"
}
}
Whenever this value is used, it will be replaced with the expression props.title
or this.props.title
or however the framework references a prop value.
Problem
Sometimes the props
or states
are more than just simple values that need to be show on the screen or passed as some arguments. A relevant example is a state value representing the activeTab
.
activeTab
can be: 0, 1, 2, 3, etc. but I would like to be able to set an attribute to true
when the activeTab is equal to a certain value.
The code that would set the data-active
value to true
when the third tab is selected would be:
<div rol="tabpanel" data-active={ activeTab === 2 }>
However, we can only set an attribute to an exact dynamic value, not to an expression using that dynamic value.
{
"attrs": {
"data-active": {
"type": "dynamic",
"content": {
"referenceType": "state",
"id": "activeTab"
}
}
}
}
Solution
The dyamic node should have some additional constructs that allows you to write a transformation / expression on that particular value. A few ideas / proposals below:
Expression
Here we produce { state.activeTab === 2 }
{
"attrs": {
"data-active": {
"type": "dynamic",
"content": {
"referenceType": "state",
"id": "activeTab",
"expression": {
"operation": "===",
"operand": 2
}
}
}
}
}
Transformation
Here we produce { state.activeTab + 3 }
{
"attrs": {
"data-active": {
"type": "dynamic",
"content": {
"referenceType": "state",
"id": "activeTab",
"expression": {
"operation": "+",
"operand": 3
}
}
}
}
}
Member Expression
Here we would produce { state.products.length }
{
"attrs": {
"data-active": {
"type": "dynamic",
"content": {
"referenceType": "state",
"id": "products",
"memberExpression": "length"
}
}
}
}
Function Expression
Here we would produce { parseInt(state.activeTab, 10) }
{
"attrs": {
"data-active": {
"type": "dynamic",
"content": {
"referenceType": "state",
"id": "activeTab",
"functionExpression": {
"name": "parseInt",
"otherArguments": [10]
}
}
}
}
}