Skip to content
This repository was archived by the owner on Oct 13, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
d6428fd
WIP Move full-page logic to its own module
DAreRodz Apr 11, 2025
230f41a
Fix interactivity-router TS with sub-packages
sirreal Apr 9, 2025
2c87637
Needs to be composite project
sirreal Apr 9, 2025
429df79
Add empty files for good measure
sirreal Apr 9, 2025
ab264a5
Add package.json export
sirreal Apr 9, 2025
23e6a96
Remove extra whitespace
DAreRodz Apr 9, 2025
0fb4976
Remove exports property
DAreRodz Apr 9, 2025
50d7092
Add full-page client-side navigation support
DAreRodz Apr 14, 2025
efe5cad
Import script modules before render
DAreRodz Apr 14, 2025
5337993
Turn php logic into a class
DAreRodz Apr 15, 2025
35c814d
Change default mode priority to 9
DAreRodz Apr 16, 2025
e749c9b
Fix init action in WP_Interactivity_API_Full_Page_Navigation
DAreRodz Apr 21, 2025
d112a77
Prevent warning accessing to clientNavigationMode
DAreRodz Apr 22, 2025
f7b458d
Change body router region ID to core/body
DAreRodz Apr 22, 2025
2ae7c4b
Remove unnecessary `body` prop inside `regions`
DAreRodz Apr 22, 2025
c371c86
Merge branch 'interactivity-api' into iapi-move-full-page-logic-to-it…
DAreRodz Apr 22, 2025
2679a52
Add a filter to enable/disable the experimental feature
DAreRodz Apr 22, 2025
ad96ad3
Use `wp_body_open` instead of `wp_footer`
DAreRodz Apr 24, 2025
d949f0b
Move the experiment filter to `set_default_mode`
DAreRodz Apr 24, 2025
503e965
Merge branch 'interactivity-api' into iapi-move-full-page-logic-to-it…
DAreRodz May 8, 2025
8b70137
Remove full-page unlock
DAreRodz May 8, 2025
9a64d97
Only add the client navigation mode when full page is enabled
DAreRodz May 9, 2025
51f5ed2
Move Full Page class to experimental folder
DAreRodz May 12, 2025
7aa02e5
End buffer on `wp_footer` instead of `wp_body_open`
DAreRodz May 12, 2025
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,108 @@
<?php
/**
* Enables full page client-side navigation for the Interactivity API.
*
* IMPORTANT: this code is not meant to be included in Gutenberg yet. Instead,
* it will be part of an external plugin to test this feature separately.
*/

if ( ! class_exists( 'WP_Interactivity_API_Full_Page_Navigation' ) ) {

/**
* Class to enable full page client-side navigation for the Interactivity API.
*/
class WP_Interactivity_API_Full_Page_Navigation {

private static $instance = null;

private static $unlock_message = 'I acknowledge that full-page client-side navigation is still experimental and will probably change, breaking my plugin or website on its next version.';

public function __construct() {
add_action( 'init', array( $this, 'set_default_mode' ), 9 );
add_action( 'wp_head', array( $this, 'buffer_start' ) );
add_action( 'wp_footer', array( $this, 'buffer_end' ), 8 );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_script_modules' ) );
}

/**
* Returns whether the client navigation mode is `experimentalFullPage`.
*/
public function is_enabled() {
$iapi_router_config = wp_interactivity_config( 'core/router' );
return 'experimentalFullPage' === ( $iapi_router_config['clientNavigationMode'] ?? '' );
}

/**
* Sets the client navigation mode by default.
*/
public function set_default_mode() {
$unlock_message = apply_filters( 'wp_interactivity_experimental_full_page_client_navigation', '' );
if ( self::$unlock_message === $unlock_message ) {
wp_interactivity_config(
'core/router',
array( 'clientNavigationMode' => 'experimentalFullPage' )
);
}
}

/**
* Enqueues the required script modules.
*/
public function enqueue_script_modules() {
if ( $this->is_enabled() ) {
wp_enqueue_script_module(
'@wordpress/interactivity-router/full-page'
);
}
}

/**
* Starts output buffering at the end of the 'wp_head' action, adding the
* required directives for client-side navigation to the BODY tags when the
* buffer is flushed.
*/
public function buffer_start() {
if ( $this->is_enabled() ) {
ob_start( array( $this, 'add_directives_to_body' ) );
}
}

/**
* Flushes the output buffer at the end of the 'wp_footer' action.
*/
public function buffer_end() {
if ( $this->is_enabled() ) {
ob_end_flush();
}
}

/**
* Adds client-side navigation directives to BODY tag in the passed output
* buffer.
*
* Note: This should probably be done per site, not by default when this option
* is enabled.
*
* @param string $buffer Passed output buffer.
*
* @return string The same HTML with modified BODY attributes.
*/
public function add_directives_to_body( $buffer ) {
$p = new WP_HTML_Tag_Processor( $buffer );
if ( $p->next_tag( array( 'tag_name' => 'BODY' ) ) ) {
$p->set_attribute( 'data-wp-interactive', true );
$p->set_attribute( 'data-wp-router-region', 'core/body' );
return $p->get_updated_html();
} else {
return $buffer;
}
}

public static function instance() {
if ( null === self::$instance ) {
self::$instance = new WP_Interactivity_API_Full_Page_Navigation();
}
return self::$instance;
}
}
}
4 changes: 4 additions & 0 deletions lib/load.php
Original file line number Diff line number Diff line change
Expand Up @@ -156,3 +156,7 @@ function gutenberg_is_experiment_enabled( $name ) {
if ( gutenberg_is_experiment_enabled( 'gutenberg-media-processing' ) ) {
require_once __DIR__ . '/experimental/media/load.php';
}

// Interactivity API full page client-side navigation.
require __DIR__ . '/experimental/interactivity-api/class-wp-interactivity-api-full-page-navigation.php';
WP_Interactivity_API_Full_Page_Navigation::instance();
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
}

echo <<<HTML
<script type="application/json" id="wp-interactivity-data">
<script type="application/json" id="wp-script-module-data-@wordpress/interactivity">
$test_store_tag_json
</script>
HTML;
Expand Down
5 changes: 4 additions & 1 deletion packages/interactivity-router/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@
"main": "build/index.js",
"module": "build-module/index.js",
"react-native": "src/index",
"wpScriptModuleExports": "./build-module/index.js",
"wpScriptModuleExports": {
".": "./build-module/index.js",
"./full-page": "./build-module/full-page.js"
},
"types": "build-types",
"dependencies": {
"@wordpress/a11y": "file:../a11y",
Expand Down
65 changes: 65 additions & 0 deletions packages/interactivity-router/src/full-page.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* WordPress dependencies
*/
import { getConfig } from '@wordpress/interactivity';

// Check if the navigation mode is full page or region based.
const clientNavigationMode: 'regionBased' | 'experimentalFullPage' =
getConfig( 'core/router' ).clientNavigationMode ?? 'regionBased';

// Check if the link is valid for client-side navigation.
const isValidLink = ( ref: HTMLAnchorElement ) =>
ref &&
ref instanceof window.HTMLAnchorElement &&
ref.href &&
( ! ref.target || ref.target === '_self' ) &&
ref.origin === window.location.origin &&
! ref.pathname.startsWith( '/wp-admin' ) &&
! ref.pathname.startsWith( '/wp-login.php' ) &&
! ref.getAttribute( 'href' ).startsWith( '#' ) &&
! new URL( ref.href ).searchParams.has( '_wpnonce' );

// Check if the event is valid for client-side navigation.
const isValidEvent = ( event: MouseEvent ) =>
event &&
event.button === 0 && // Left clicks only.
! event.metaKey && // Open in new tab (Mac).
! event.ctrlKey && // Open in new tab (Windows).
! event.altKey && // Download.
! event.shiftKey &&
! event.defaultPrevented;

// Add click and prefetch to all links.
if ( clientNavigationMode === 'experimentalFullPage' ) {
// Navigate on click.
document.addEventListener(
'click',
async ( event ) => {
const ref = ( event.target as Element ).closest( 'a' );
if ( isValidLink( ref ) && isValidEvent( event ) ) {
event.preventDefault();
const { actions } = await import(
'@wordpress/interactivity-router'
);
actions.navigate( ref.href );
}
},
true
);
// Prefetch on hover.
document.addEventListener(
'mouseenter',
async ( event ) => {
if ( ( event.target as Element )?.nodeName === 'A' ) {
const ref = ( event.target as Element ).closest( 'a' );
if ( isValidLink( ref ) && isValidEvent( event ) ) {
const { actions } = await import(
'@wordpress/interactivity-router'
);
actions.prefetch( ref.href );
}
}
},
true
);
}
49 changes: 19 additions & 30 deletions packages/interactivity-router/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const {

const regionAttr = `data-${ directivePrefix }-router-region`;
const interactiveAttr = `data-${ directivePrefix }-interactive`;
const regionsSelector = `[${ interactiveAttr }][${ regionAttr }]:not([${ interactiveAttr }] [${ interactiveAttr }])`;

export interface NavigateOptions {
force?: boolean;
Expand Down Expand Up @@ -60,10 +61,6 @@ interface Page {

type RegionsToVdom = ( dom: Document, params?: VdomParams ) => Promise< Page >;

// Check if the navigation mode is full page or region based. The only supported
// mode for now is 'regionBased'.
const navigationMode: 'regionBased' = 'regionBased';

// The cache of visited and prefetched pages, stylesheets and scripts.
const pages = new Map< string, Promise< Page | false > >();

Expand Down Expand Up @@ -94,17 +91,14 @@ const fetchPage = async ( url: string, { html }: { html: string } ) => {
// Return an object with VDOM trees of those HTML regions marked with a
// `router-region` directive.
const regionsToVdom: RegionsToVdom = async ( dom, { vdom, url } = {} ) => {
const regions = { body: undefined };
if ( navigationMode === 'regionBased' ) {
dom.querySelectorAll(
`[${ interactiveAttr }][${ regionAttr }]:not([${ interactiveAttr }] [${ interactiveAttr }])`
).forEach( ( region ) => {
const id = region.getAttribute( regionAttr );
regions[ id ] = vdom?.has( region )
? vdom.get( region )
: toVdom( region );
} );
}
const regions = {};
dom.querySelectorAll( regionsSelector ).forEach( ( region ) => {
const id = region.getAttribute( regionAttr );
regions[ id ] = vdom?.has( region )
? vdom.get( region )
: toVdom( region );
} );

const title = dom.querySelector( 'title' )?.innerText;
const initialData = parseServerData( dom );

Expand All @@ -120,22 +114,16 @@ const regionsToVdom: RegionsToVdom = async ( dom, { vdom, url } = {} ) => {
// Render all interactive regions contained in the given page.
const renderRegions = ( page: Page ) => {
applyStyles( page.styles );
importScriptModules( page.scriptModules );

if ( navigationMode === 'regionBased' ) {
batch( () => {
populateServerData( page.initialData );
document
.querySelectorAll(
`[${ interactiveAttr }][${ regionAttr }]:not([${ interactiveAttr }] [${ interactiveAttr }])`
)
.forEach( ( region ) => {
const id = region.getAttribute( regionAttr );
const fragment = getRegionRootFragment( region );
render( page.regions[ id ], fragment );
} );

batch( () => {
populateServerData( page.initialData );
document.querySelectorAll( regionsSelector ).forEach( ( region ) => {
const id = region.getAttribute( regionAttr );
const fragment = getRegionRootFragment( region );
render( page.regions[ id ], fragment );
} );
}
} );

if ( page.title ) {
document.title = page.title;
}
Expand Down Expand Up @@ -295,6 +283,7 @@ export const { state, actions } = store< Store >( 'core/router', {
! page.initialData?.config?.[ 'core/router' ]
?.clientNavigationDisabled
) {
yield importScriptModules( page.scriptModules );
Comment thread
luisherranz marked this conversation as resolved.
Resolved
renderRegions( page );
window.history[
options.replace ? 'replaceState' : 'pushState'
Expand Down
12 changes: 12 additions & 0 deletions packages/interactivity-router/tsconfig.full-page.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"$schema": "https://json.schemastore.org/tsconfig.json",
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"allowJs": false,
"checkJs": false,
"strict": false
},
"references": [ { "path": "tsconfig.main.json" } ],
"files": [ "src/full-page.ts" ],
"include": [],
}
13 changes: 9 additions & 4 deletions packages/interactivity-router/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
{
"$schema": "https://json.schemastore.org/tsconfig.json",
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"checkJs": false,
"strict": false
"composite": true
},
"references": [ { "path": "../a11y" }, { "path": "../interactivity" } ]
"files": [],
"references": [
{ "path": "../a11y" },
{ "path": "../interactivity" },
{ "path": "tsconfig.main.json" },
{ "path": "tsconfig.full-page.json" }
]
}

21 changes: 21 additions & 0 deletions packages/interactivity-router/tsconfig.main.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"$schema": "https://json.schemastore.org/tsconfig.json",
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"allowJs": false,
"checkJs": false,
"strict": false
},
"references": [ { "path": "../a11y" }, { "path": "../interactivity" } ],
"exclude": [
"**/*.android.js",
"**/*.ios.js",
"**/*.native.js",
"**/benchmark",
"build-*/**",
"build/**",
"**/test/**",
"**/react-native-*/**",
"src/full-page.ts"
]
}