Skip to content

Commit

Permalink
Support negation operator in selectors in the Interactivity API (#50732)
Browse files Browse the repository at this point in the history
* Support negation operator in selectors

* Change file block to use negation operator
  • Loading branch information
SantosGuillamot authored May 19, 2023
1 parent a8da93f commit ac28fa6
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 16 deletions.
2 changes: 1 addition & 1 deletion lib/experimental/interactivity-api/blocks.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ function gutenberg_block_core_file_add_directives_to_content( $block_content, $b
$processor->next_tag();
$processor->set_attribute( 'data-wp-island', '' );
$processor->next_tag( 'object' );
$processor->set_attribute( 'data-wp-bind.hidden', 'selectors.core.file.hasNoPdfPreview' );
$processor->set_attribute( 'data-wp-bind.hidden', '!selectors.core.file.hasPdfPreview' );
$processor->set_attribute( 'hidden', true );
return $processor->get_updated_html();
}
Expand Down
6 changes: 2 additions & 4 deletions packages/block-library/src/file/interactivity.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,13 @@
* Internal dependencies
*/
import { store } from '../utils/interactivity';
import { browserSupportsPdfs } from './utils';
import { browserSupportsPdfs as hasPdfPreview } from './utils';

store( {
selectors: {
core: {
file: {
hasNoPdfPreview() {
return ! browserSupportsPdfs();
},
hasPdfPreview,
},
},
},
Expand Down
24 changes: 13 additions & 11 deletions packages/block-library/src/utils/interactivity/hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,26 +19,28 @@ export const directive = ( name, cb ) => {

// Resolve the path to some property of the store object.
const resolve = ( path, ctx ) => {
// If path starts with !, remove it and save a flag.
const hasNegationOperator =
path[ 0 ] === '!' && !! ( path = path.slice( 1 ) );
let current = { ...store, context: ctx };
path.split( '.' ).forEach( ( p ) => ( current = current[ p ] ) );
return hasNegationOperator ? ! current : current;
return current;
};

// Generate the evaluate function.
const getEvaluate =
( { ref } = {} ) =>
( path, extraArgs = {} ) => {
// If path starts with !, remove it and save a flag.
const hasNegationOperator =
path[ 0 ] === '!' && !! ( path = path.slice( 1 ) );
const value = resolve( path, extraArgs.context );
return typeof value === 'function'
? value( {
ref: ref.current,
...store,
...extraArgs,
} )
: value;
const returnValue =
typeof value === 'function'
? value( {
ref: ref.current,
...store,
...extraArgs,
} )
: value;
return hasNegationOperator ? ! returnValue : returnValue;
};

// Directive wrapper.
Expand Down

0 comments on commit ac28fa6

Please sign in to comment.