You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Clarify Interactivity API evaluate function and directives to not allow action usage for what should be state #69269
This came up as part of working on #68097 in conversation with @luisherranz, specifically in the comments starting with #68097 (review).
Problems to address:
Some developers today rely on store functions such as actions to determine the value for attributes. However, values should always use context or derived state, so this is an anti-pattern that should be more strongly discouraged or even made impossible.
The evaluate() function today invokes functions, whereas in relation to the above it should only look up the function and return it, just like it does for regular values.
As part of the PR #68097, the behavior was already moved closer towards the right direction, but it's definitely in a temporary state. Here's a list of a few more low-level technical issues that should be ironed out for a proper solution:
Currently, every caller of evaluate() needs to check whether the return value is a function and, if so, invoke it. This should be made more ergonomic.
Currently, it is possible to provide reference to a function in combination with a negation operator. This should no longer be allowed because functions should only be used for actions like for data-wp-on, callbacks like for data-wp-watch etc - i.e. functions should never return a value, and thus a negation operator for them is irrelevant.
One part that's already prepared for a step in the right direction is that providing a reference to a function in combination with a negation operator will trigger a console warning going forward, since this should never be used, as functions should never be used to return values in the first place. For now it still works due to backward compatibility, but is now deprecated and can eventually be removed.
Let's discuss in this issue what would be a good strategy to get to the end goal. We also need to consider potential in-between steps, such as first deprecating something that is discouraged, launching that in a release, and only later making it impossible.
A potential final solution could be something like this:
evaluate() should under no circumstances invoke functions. It should simply return the function.
As such, the ...args should be removed from evaluate(), as no function would ever be invoked with them.
If the evaluated value is a function and a negation operator is provided, it should throw an error that this is invalid.
In order for directives not to manually have to check for whether the return value from evaluate() is a function or not, two wrapper functions for evaluate() should be added:
evaluateValue() would always return a value (e.g. scalar, object, or array), never a function.
evaluateFunction() would always return a function, never an actual value.
Each directive would use either evaluateValue() or evaluateFunction(), depending on the directive's purposes. All directives responsible for e.g. an attribute value would use evaluateValue() and all directives responsible for e.g. event listeners or callbacks would use evaluateFunction().
The wrapper functions could be as simple as something like this:
typeNoFunctionValue=boolean|string|number|null|undefined|{[key: string]: NoFunctionValue}|Array<NoFunctionValue>;constevaluateValue=(entry: DirectiveEntry): NoFunctionValue=>{constresult=evaluate(entry);if(typeofresult==='function'){thrownewError('Value must not be a function.');}returnresult;};constevaluateFunction=(entry: DirectiveEntry): Function=>{constresult=evaluate(entry);if(typeofresult!=='function'){thrownewError('Value must be a function.');}returnresult;};
With those functions available, directives would never need to check what the value is, as it would be guaranteed to be the format each directive expects.
I agree with everything except that I'm not sure if we should abstract so early and create two functions simply to abstract an error. I would prefer to leave the API as simple as possible until we know better how it will be used, because even though it seems that there are only two types of directives now (those that need a function and those that need a value), we may encounter more use cases in the future.
So, for me, it wouldn't be so terrible to delegate this check to the directives for now, and keep only a single evaluate function that simply returns the value or the function (and ignores the negation operator of the functions).
// Directives that require a function, like `data-wp-on`:constcb=evaluate(entry);if(typeofvalue!=="function")thrownewError(`The reference of data-wp-on--${entry.suffix} must point to a value, not a function. Please check ${entry.value}.`)cb( ...args);// Directives that require a value, like `data-wp-bind`constvalue=evaluate(entry);if(typeofvalue==="function")thrownewError(`The reference of data-wp-bind--${entry.suffix} must point to a value, not a function. Please check ${entry.value}.`)element[prop]=value;
For backward compatibility, we can delegate it to the existing directives that need it, and it won't be necessary to do anything in the new directives that we add.
// Temporary `data-wp-bind` with backward compatibilityletresult=evaluate(entry);// Deprecated: Support for function values.if(typeofresult==='function'){result=entry.value[0]==='!' ? !result() : result();warn('The use of functions in `data-wp-bind` is deprecated and will stop working in a future version of WordPress. Please use derived state instead. See: https://developer.wordpress.org/block-editor/reference-guides/interactivity-api/core-concepts/undestanding-global-state-local-context-and-derived-state/');}element[prop]=result;
And then, once we decide, we'll replace the deprecation with the error.
I agree with everything except that I'm not sure if we should abstract so early and create two functions simply to abstract an error. I would prefer to leave the API as simple as possible until we know better how it will be used, because even though it seems that there are only two types of directives now (those that need a function and those that need a value), we may encounter more use cases in the future.
I think this is generally a valid point, but what we're talking about is a private API. While there are intentions to make the API public (likely later than sooner), as long as it's not public, adding an abstraction on private code doesn't require the same consideration about future compatibility, since there is no chance of doing something here that would later "code us into a corner" or risk breaking backward compatibility. So from my perspective, I think we should rather focus on addressing the problems we're facing today.
So, for me, it wouldn't be so terrible to delegate this check to the directives for now
You're saying that it "wouldn't be so terrible", but that kind of points to what I'm getting at - it's still "terrible". Obviously, since it's all private code too, there is no concern about external implementers facing this problem, but there's also the aspect of maintainability of our own codebase today. And I think that's where the current solution is showing an actual problem, due to all of the code duplication that's required if we keep the responsibility within the inline logic of each directive.
I don't see any harm by introducing reusable private functions to address this problem. They would allow for the same logic to apply as you're suggesting, but without all that code duplication, since each directive would call one of the functions. And just because those functions would exist, it wouldn't mean they would need to ever become public. We could remove them or refactor them at any point if we find another more appropriate solution in the future.
Potentially we could alternatively separate these private functions to simply act as validation instead of calling evaluate(), e.g.:
typeNoFunctionValue=boolean|string|number|null|undefined|{[key: string]: NoFunctionValue}|Array<NoFunctionValue>;constvalidateNoFunctionValue=(result: any,entry: DirectiveEntry,directive: string): NoFunctionValue=>{if(typeofresult==='function'){// First this would just trigger a deprecation warning and call the function, but eventually it should error like below.thrownewError(`The reference of ${directive} must point to a value, not a function. Please check ${entry.value}.`);}returnresult;};constvalidateFunctionValue=(result: any,entry: DirectiveEntry,directive: string): Function=>{if(typeofresult!=='function'){thrownewError(`The reference of ${directive} must point to a function, not a value. Please check ${entry.value}.`);}returnresult;};
Your code example from above could use them like this:
// Directives that require a function, like `data-wp-on`:constcb=validateFunctionValue(evaluate(entry),entry,`data-wp-on--${entry.suffix}`);cb( ...args);// Directives that require a value, like `data-wp-bind`:constvalue=validateNoFunctionValue(evaluate(entry),entry,`data-wp-bind--${entry.suffix}`);element[prop]=value;
This is probably an even cleaner solution, as it decouples the validation from evaluate() and it makes it more obvious that these two functions are just private helpers.
Activity
felixarntz commentedon Feb 20, 2025
A potential final solution could be something like this:
evaluate()should under no circumstances invoke functions. It should simply return the function....argsshould be removed fromevaluate(), as no function would ever be invoked with them.evaluate()is a function or not, two wrapper functions forevaluate()should be added:evaluateValue()would always return a value (e.g. scalar, object, or array), never a function.evaluateFunction()would always return a function, never an actual value.evaluateValue()orevaluateFunction(), depending on the directive's purposes. All directives responsible for e.g. an attribute value would useevaluateValue()and all directives responsible for e.g. event listeners or callbacks would useevaluateFunction().The wrapper functions could be as simple as something like this:
With those functions available, directives would never need to check what the value is, as it would be guaranteed to be the format each directive expects.
WDYT?
luisherranz commentedon Mar 3, 2025
Thanks for starting this discussion, Felix! 🙏
I agree with everything except that I'm not sure if we should abstract so early and create two functions simply to abstract an error. I would prefer to leave the API as simple as possible until we know better how it will be used, because even though it seems that there are only two types of directives now (those that need a function and those that need a value), we may encounter more use cases in the future.
So, for me, it wouldn't be so terrible to delegate this check to the directives for now, and keep only a single
evaluatefunction that simply returns the value or the function (and ignores the negation operator of the functions).For backward compatibility, we can delegate it to the existing directives that need it, and it won't be necessary to do anything in the new directives that we add.
And then, once we decide, we'll replace the deprecation with the error.
felixarntz commentedon Mar 5, 2025
I think this is generally a valid point, but what we're talking about is a private API. While there are intentions to make the API public (likely later than sooner), as long as it's not public, adding an abstraction on private code doesn't require the same consideration about future compatibility, since there is no chance of doing something here that would later "code us into a corner" or risk breaking backward compatibility. So from my perspective, I think we should rather focus on addressing the problems we're facing today.
You're saying that it "wouldn't be so terrible", but that kind of points to what I'm getting at - it's still "terrible". Obviously, since it's all private code too, there is no concern about external implementers facing this problem, but there's also the aspect of maintainability of our own codebase today. And I think that's where the current solution is showing an actual problem, due to all of the code duplication that's required if we keep the responsibility within the inline logic of each directive.
I don't see any harm by introducing reusable private functions to address this problem. They would allow for the same logic to apply as you're suggesting, but without all that code duplication, since each directive would call one of the functions. And just because those functions would exist, it wouldn't mean they would need to ever become public. We could remove them or refactor them at any point if we find another more appropriate solution in the future.
Potentially we could alternatively separate these private functions to simply act as validation instead of calling
evaluate(), e.g.:Your code example from above could use them like this:
This is probably an even cleaner solution, as it decouples the validation from
evaluate()and it makes it more obvious that these two functions are just private helpers.WDYT?