Skip to content

Commit

Permalink
Set the search state in the interactivity state for inherited queries.
Browse files Browse the repository at this point in the history
  • Loading branch information
michalczaplinski committed Dec 10, 2024
1 parent 006dd38 commit d1483a2
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
6 changes: 5 additions & 1 deletion packages/block-library/src/search/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ function render_block_core_search( $attributes, $content, $block ) {
wp_enqueue_script_module( '@wordpress/block-library/search/view' );

if ( $instant_search_enabled ) {
$input->set_attribute( 'data-wp-bind--value', 'context.search' );
$input->set_attribute( 'data-wp-bind--value', 'state.searchGetter' );
$input->set_attribute( 'data-wp-on-async--input', 'actions.updateSearch' );
}
}
Expand Down Expand Up @@ -238,6 +238,10 @@ function render_block_core_search( $attributes, $content, $block ) {
// If the query is defined in the URL, it overrides the block context value.
$search = empty( $_GET[ $search_key ] ) ? $search : sanitize_text_field( $_GET[ $search_key ] );

if ( $is_inherited ) {
wp_interactivity_state( 'core/search', array( 'search' => $search ) );
}

$form_context = array_merge(
$form_context,
array(
Expand Down
16 changes: 12 additions & 4 deletions packages/block-library/src/search/view.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ const { state, actions } = store(
}
return ctx.isSearchInputVisible;
},
get searchGetter() {
const { isInherited, search } = getContext();
return isInherited ? state.search : search;
},
},
actions: {
openSearchInput( event ) {
Expand Down Expand Up @@ -88,14 +92,18 @@ const { state, actions } = store(
*updateSearch( e ) {
const { value } = e.target;

const ctx = getContext();

// Don't navigate if the search didn't really change.
if ( value === ctx.search ) {
if ( value === state.searchGetter ) {
return;
}

ctx.search = value;
const ctx = getContext();

if ( ctx.isInherited ) {
state.search = value;
} else {
ctx.search = value;
}

// Debounce the search by 300ms to prevent multiple navigations.
supersedePreviousSearch?.();
Expand Down

0 comments on commit d1483a2

Please sign in to comment.