Skip to content

Clarify Interactivity API evaluate function and directives to not allow action usage for what should be state #69269

Open

Description

@felixarntz

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.

Activity

  1. added
    [Feature] Interactivity API
    [Type] Enhancement
    Developer Experience
    on Feb 20, 2025
  2. felixarntz commented on Feb 20, 2025

    @felixarntz
    MemberAuthor

    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:

    type NoFunctionValue = boolean | string | number | null | undefined | { [key: string]: NoFunctionValue } | Array<NoFunctionValue>;
    
    const evaluateValue = ( entry: DirectiveEntry ): NoFunctionValue => {
    	const result = evaluate( entry );
    	if ( typeof result === 'function' ) {
    		throw new Error( 'Value must not be a function.' );
    	}
    	return result;
    };
    
    const evaluateFunction = ( entry: DirectiveEntry ): Function => {
    	const result = evaluate( entry );
    	if ( typeof result !== 'function' ) {
    		throw new Error( 'Value must be a function.' );
    	}
    	return result;
    };

    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?

  3. luisherranz commented on Mar 3, 2025

    @luisherranz
    Member

    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 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`:
    const cb = evaluate( entry );
    if ( typeof value !== "function" ) throw new Error( `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`
    const value = evaluate( entry );
    if ( typeof value === "function" ) throw new Error( `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 compatibility
    let result = evaluate( entry );
    // Deprecated: Support for function values.
    if ( typeof result === '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.

  4. felixarntz commented on Mar 5, 2025

    @felixarntz
    MemberAuthor

    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.:

    type NoFunctionValue = boolean | string | number | null | undefined | { [key: string]: NoFunctionValue } | Array<NoFunctionValue>;
    
    const validateNoFunctionValue = ( result: any, entry: DirectiveEntry, directive: string ): NoFunctionValue => {
    	if ( typeof result === 'function' ) {
    		// First this would just trigger a deprecation warning and call the function, but eventually it should error like below.
    		throw new Error(
    			`The reference of ${directive} must point to a value, not a function. Please check ${entry.value}.`
    		);
    	}
    	return result;
    };
    
    const validateFunctionValue = ( result: any, entry: DirectiveEntry, directive: string ): Function => {
    	if ( typeof result !== 'function' ) {
    		throw new Error(
    			`The reference of ${directive} must point to a function, not a value. Please check ${entry.value}.`
    		);
    	}
    	return result;
    };

    Your code example from above could use them like this:

    // Directives that require a function, like `data-wp-on`:
    const cb = validateFunctionValue( evaluate( entry ), entry, `data-wp-on--${entry.suffix}` );
    cb( ...args);
    
    // Directives that require a value, like `data-wp-bind`:
    const value = 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.

    WDYT?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Developer Experience[Feature] Interactivity API[Type] Enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions