Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 3,
"name": "test/hydration-timing-async",
"title": "E2E Interactivity tests - hydration timing async import",
"category": "text",
"icon": "heart",
"description": "",
"supports": {
"interactivity": true
},
"textdomain": "e2e-interactivity",
"viewScriptModule": "file:./view.js",
"render": "file:./render.php"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php
/**
* HTML for testing hydration timing - async import block.
*
* This block's view module dynamically imports @wordpress/interactivity
* on DOMContentLoaded, simulating a lazy-loading scenario. The test verifies
* that hydration still occurs even when the library is loaded after
* DOMContentLoaded has fired.
*
* @package gutenberg-test-interactive-blocks
*
* @phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable
*/
?>

<div
data-wp-interactive="test/hydration-timing-async"
<?php echo wp_interactivity_data_wp_context( array( 'hydrated' => false ) ); ?>
>
<p
data-wp-text="state.asyncModuleLoaded"
data-testid="async-module-loaded"
>no</p>

<p
data-wp-text="context.hydrated"
data-testid="async-hydrated"
>no</p>

<div
data-wp-init="callbacks.init"
data-testid="async-hydration-status"
>
Async import hydration test block
</div>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php return array(
'dependencies' => array(
array(
'id' => '@wordpress/interactivity',
'import' => 'dynamic',
),
),
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* This module dynamically imports @wordpress/interactivity on DOMContentLoaded.
*
* This simulates a lazy-loading scenario where the Interactivity API is not
* statically imported. The test verifies that hydration still occurs even
* when the library is loaded after DOMContentLoaded has already fired.
*/

const initStore = async () => {
const { store, getContext } = await import( '@wordpress/interactivity' );
Comment thread
luisherranz marked this conversation as resolved.
Resolved

store( 'test/hydration-timing-async', {
state: {
asyncModuleLoaded: 'yes',
},
callbacks: {
// TODO: this could be unavailable during hydration. Fix
// `data-wp-init` to support that case.
init() {
const context = getContext();
context.hydrated = true;
},
},
} );
};

document.addEventListener( 'DOMContentLoaded', () =>
setTimeout( initStore, 1 )
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 3,
"name": "test/hydration-timing-slow",
"title": "E2E Interactivity tests - hydration timing slow module",
"category": "text",
"icon": "heart",
"description": "",
"supports": {
"interactivity": true
},
"textdomain": "e2e-interactivity",
"viewScriptModule": "file:./view.js",
"render": "file:./render.php"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php
/**
* HTML for testing hydration timing - slow module block.
*
* This block's view module will be artificially delayed in the test
* to simulate a slow network connection. The test verifies that
* hydration waits for this module to load even when other modules
* that import @wordpress/interactivity have already been evaluated.
*
* @package gutenberg-test-interactive-blocks
*
* @phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable
*/
?>

<div
data-wp-interactive="test/hydration-timing"
<?php echo wp_interactivity_data_wp_context( array( 'slowInitialized' => false ) ); ?>
>
<p
data-wp-text="state.slowModuleLoaded"
data-testid="slow-module-loaded"
>no</p>

<p
data-wp-text="context.slowInitialized"
data-testid="slow-context-initialized"
>no</p>

<div
data-wp-init="callbacks.slowInit"
data-testid="slow-hydration-status"
>
Slow module hydration test block
</div>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<?php return array( 'dependencies' => array( '@wordpress/interactivity' ) );
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* WordPress dependencies
*/
import { store, getContext } from '@wordpress/interactivity';

// This module will be artificially delayed in the test.
// It also imports @wordpress/interactivity, so when it's evaluated,
// the interactivity runtime will have already been initialized by
// the fast module. The test verifies that hydration waits for this
// module to finish loading before running.

store( 'test/hydration-timing', {
state: {
slowModuleLoaded: 'yes',
},
callbacks: {
slowInit() {
const context = getContext();
context.slowInitialized = true;
},
},
} );
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 3,
"name": "test/hydration-timing",
"title": "E2E Interactivity tests - hydration timing",
"category": "text",
"icon": "heart",
"description": "",
"supports": {
"interactivity": true
},
"textdomain": "e2e-interactivity",
"viewScriptModule": "file:./view.js",
"render": "file:./render.php"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php
/**
* HTML for testing hydration timing with delayed module loading.
*
* @package gutenberg-test-interactive-blocks
*
* @phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable
*/
?>

<div
data-wp-interactive="test/hydration-timing"
<?php echo wp_interactivity_data_wp_context( array( 'initialized' => false ) ); ?>
>
<p
data-wp-text="state.moduleLoaded"
data-testid="module-loaded"
>no</p>

<p
data-wp-text="context.initialized"
data-testid="context-initialized"
>no</p>

<div
data-wp-init="callbacks.init"
data-testid="hydration-status"
>
Hydration test block
</div>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<?php return array( 'dependencies' => array( '@wordpress/interactivity' ) );
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* WordPress dependencies
*/
import { store, getContext } from '@wordpress/interactivity';

// This is the "fast" module that loads immediately. It imports
// @wordpress/interactivity, which initializes the runtime.
//
// The test pairs this with a "slow" module (hydration-timing-slow) that is
// artificially delayed. The race condition occurs when this fast module
// triggers hydration before the slow module has finished loading.

store( 'test/hydration-timing', {
state: {
moduleLoaded: 'yes',
},
callbacks: {
init() {
const context = getContext();
context.initialized = true;
},
},
} );
1 change: 1 addition & 0 deletions packages/interactivity/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Bug Fixes

- Preserve boolean HTML attributes during client-side navigation. ([#74446](https://github.com/WordPress/gutenberg/pull/74446))
- Fix and refactor runtime initialization logic. ([#71123](https://github.com/WordPress/gutenberg/pull/71123))

## 6.36.0 (2025-11-26)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,20 +30,9 @@ export const getRegionRootFragment = (
export const initialVdom = new WeakMap< Element, ComponentChild >();

// Initialize the router with the initial DOM.
export const init = async () => {
export const hydrateRegions = async () => {
const nodes = document.querySelectorAll( `[data-wp-interactive]` );

/*
* This `await` with setTimeout is required to apparently ensure that the interactive blocks have their stores
* fully initialized prior to hydrating the blocks. If this is not present, then an error occurs, for example:
* > view.js:46 Uncaught (in promise) ReferenceError: Cannot access 'state' before initialization
* This occurs when splitTask() is implemented with scheduler.yield() as opposed to setTimeout(), as with the former
* split tasks are added to the front of the task queue whereas with the latter they are added to the end of the queue.
*/
await new Promise( ( resolve ) => {
setTimeout( resolve, 0 );
} );

for ( const node of nodes ) {
if ( ! hydratedIslands.has( node ) ) {
await splitTask();
Expand Down
20 changes: 17 additions & 3 deletions packages/interactivity/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,17 @@ import { batch } from '@preact/signals';
* Internal dependencies
*/
import registerDirectives, { routerRegions } from './directives';
import { init, getRegionRootFragment, initialVdom } from './init';
import {
initialVdom,
hydrateRegions,
getRegionRootFragment,
} from './hydration';

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I renamed init.js to hydration.js to further clarify this file's purpose. The same goes for the init function, now renamed to hydrateRegions. Let me know what you think about these changes.

import { toVdom } from './vdom';
import { directive } from './hooks';
import { getNamespace } from './namespaces';
import { parseServerData, populateServerData } from './store';
import { proxifyState } from './proxies';
import { deepReadOnly, navigationSignal } from './utils';
import { deepReadOnly, navigationSignal, onDOMReady } from './utils';

export {
store,
Expand Down Expand Up @@ -71,5 +75,15 @@ export const privateApis = (
throw new Error( 'Forbidden access.' );
};

// Parses and populates the initial state and config. All the core directives
// are registered at this point as well.
populateServerData( parseServerData() );

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved the state and config initialization here so that index.js is the only file that calls functions.

registerDirectives();
init();

// Hydrates all interactive regions when `DOMContentLoaded` is dispatched, or as
// soon as the `@wordpress/interactivity` module is evaluated in the case that
// the event was already dispatched. This ensures synchronous modules had the
// opportunity to register their stores before hydration takes place. For
// asynchronous modules, or modules importing this module asynchronously, this
// cannot be guaranteed.
onDOMReady( hydrateRegions );
4 changes: 0 additions & 4 deletions packages/interactivity/src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,3 @@ export const populateServerData = ( data?: {
);
}
};

// Parse and populate the initial state and config.
const data = parseServerData();
populateServerData( data );
21 changes: 21 additions & 0 deletions packages/interactivity/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,27 @@ export const splitTask =
setTimeout( resolve, 0 );
} );
};
/**
* Executes the passed callback on `DOMContentLoaded`, or immediately if that
* event has already been triggered.
*
* This function depends on `PerformanceNavigationTiming` (see
* https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming) to
* detect whether the event has been dispatched.
*
* @param callback Function to execute on `DOMContentLoaded`.
*/
export const onDOMReady = ( callback: () => void ) => {
const [ navigation ] = performance.getEntriesByType( 'navigation' );
if (
( navigation as PerformanceNavigationTiming )
.domContentLoadedEventStart > 0
) {
callback();
} else {
document.addEventListener( 'DOMContentLoaded', callback );
}
};

/**
* Creates a Flusher object that can be used to flush computed values and notify listeners.
Expand Down
Loading
Loading