Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,22 @@ Router regions can be placed anywhere on the page. Their behavior depends on whe
</div>
```

- **Inside `data-wp-html` content** — The router ignores a router region inside the content of a [`data-wp-html`](/docs/reference-guides/interactivity-api/directives-and-store.md#wp-html) element, whether that's the server-rendered fallback or HTML the directive inserted, because the Interactivity API treats that content as [inert](/docs/reference-guides/interactivity-api/directives-and-store.md#inert-content). Navigation behaves as if the region's `data-wp-router-region` attribute were absent, on the initial page and on every page the router fetches or restores from history: the region never supplies content for a region with the same ID, and its `attachTo` never attaches anything.

```html
<div data-wp-interactive="myPlugin">
<div data-wp-html="state.description">
<!-- Fallback content: this region is ignored during navigation -->
<div
data-wp-interactive="myPlugin"
data-wp-router-region="myPlugin/sidebar"
></div>
</div>
</div>
```

In this guide, a `data-wp-html` element is one whose content is inert: it's inside an interactive region and doesn't also have `data-wp-text`, `data-wp-each` or `data-wp-router-region` (see [Conflicts with other directives](/docs/reference-guides/interactivity-api/directives-and-store.md#conflicts-with-other-directives)). `data-wp-html` on a router region itself doesn't make the region's content inert, because `data-wp-router-region` takes precedence.

### Implementing navigation

To trigger client-side navigation, you define an **action** in your store and connect it to a DOM event using an Interactivity API directive. Actions are functions defined inside `store()` that handle user interactions. When connected to an element through a directive like `data-wp-on--click`, the action runs whenever that event fires.
Expand Down Expand Up @@ -387,7 +403,7 @@ The pattern above only runs for navigations this action started. To also cover n

### Adding new regions on navigation

Sometimes you need UI elements — like modals, sidebars, or notification panels — that only appear on certain pages. With regular router regions, a region must already exist on the current page to be updated during navigation. The `attachTo` option solves this by letting you define regions that are dynamically created and inserted into the DOM when navigating to a page where they exist, even if they weren't present on the original page.
Sometimes you need UI elements — like modals, sidebars, or notification panels — that only appear on certain pages. With regular router regions, a region must already exist on the current page to be updated during navigation. The `attachTo` option solves this by letting you define regions that are dynamically created and inserted into the DOM when navigating to a page where they exist, even if they weren't present on the original page. The region itself doesn't have to be on the current page, but the element it attaches to does.

**Defining a region with `attachTo`:**

Expand All @@ -405,7 +421,9 @@ Sometimes you need UI elements — like modals, sidebars, or notification panels
</div>
```

The `attachTo` value is a CSS selector. When navigating to this page from a page without this region, the region will be created and appended to the element matching the selector.
The `attachTo` value is a CSS selector. When navigating to this page from a page without this region, the router creates the region and appends it to the first element on the current page that matches the selector and is neither a [`data-wp-html`](/docs/reference-guides/interactivity-api/directives-and-store.md#wp-html) element nor inside its [inert content](/docs/reference-guides/interactivity-api/directives-and-store.md#inert-content).

If there is no such element, the region is not attached and the rest of the navigation completes as if the destination page didn't have the region: the other regions update, the title and URL change, and no error is thrown. This happens when the selector matches nothing, when every match is a `data-wp-html` element or inside one, or when the value isn't a valid CSS selector. The router resolves the selector every time it renders the page, so restoring the page from history tries again against the document as it is then.

**Example: Modal that appears on navigation**

Expand Down Expand Up @@ -1152,7 +1170,7 @@ When the router fetches a new page (either through `prefetch()` or as part of `n
First, the router parses the fetched HTML into a document structure using the browser's built-in HTML parser. This gives it a complete DOM tree to work with, just as if the page had been loaded normally.

Next, the router scans this document for all elements that have both `data-wp-interactive` and `data-wp-router-region` attributes. For each region found, it extracts the region ID and checks whether the region is nested inside another region. Only top-level regions are processed directly; nested regions are handled as part of their parent's content.
Next, the router scans this document for all elements that have both `data-wp-interactive` and `data-wp-router-region` attributes. For each region found, it extracts the region ID and checks whether the region is nested inside another region. Only top-level regions are processed directly; nested regions are handled as part of their parent's content. The scan skips router regions inside `data-wp-html` content, as described in [Where to place router regions](#where-to-place-router-regions), so they never supply a region's content or get attached. The router filters the initial page the same way.

For each top-level region, the router converts the HTML into a virtual DOM (vDOM) representation. The virtual DOM is a lightweight JavaScript object structure that mirrors the actual DOM but can be compared and manipulated much more efficiently by the Interactivity API. Importantly, the region element itself is included in this conversion — not just its children. This means that attributes on the region element, such as `data-wp-context`, will also be processed and updated during navigation.

Expand All @@ -1178,16 +1196,18 @@ The reconciliation algorithm relies on heuristics that can fail when elements sh

**Scenario 2: Region exists only on the target page with `attachTo` (create)**

Sometimes a page contains a region that doesn't exist on the current page — for example, a modal dialog that only appears on certain pages. If this region has the `attachTo` property specified, the router will dynamically create it.
Sometimes a page contains a region that doesn't exist on the current page — for example, a modal dialog that only appears on certain pages. If this region has the `attachTo` property specified, the router dynamically creates it, provided the current page has an element to attach it to.
The `attachTo` property contains a CSS selector that identifies where in the current page the new region should be appended. When the router encounters such a region, it:
1. Finds the element matching the `attachTo` selector in the current page
1. Finds the first element in the current page that matches the `attachTo` selector and is neither a `data-wp-html` element nor inside its content
2. Creates new DOM elements for the region
3. Appends these elements to the matched parent
4. Renders the region's virtual DOM into the newly created elements

This allows content that exists on one page but not another to appear smoothly during navigation, without requiring the target element to exist in advance.
When step 1 finds no element, the router skips the region, as described in [Adding new regions on navigation](#adding-new-regions-on-navigation). Skipping a region doesn't change the cached page, so a later render can attach it if the selector then matches a usable element. A region that an earlier navigation attached also shows nothing on a page whose `attachTo` has no usable element, as it would on a page without the region.
This allows content that exists on one page but not another to appear smoothly during navigation, without the region having to exist on the current page in advance.
**Scenario 3: Region exists only on the current page (remove)**
Expand Down Expand Up @@ -1508,7 +1528,7 @@ When `navigate()` is called (for example, on link click):
- In a batch for efficiency:
- Server state is merged with client state.
- Each router region is updated with its new virtual DOM.
- Regions with `attachTo` that don't exist are created and appended.
- Regions with `attachTo` that don't exist are created and appended to the first usable element matching their selector. A region with no such element in the current page is skipped, as described in [Adding new regions on navigation](#adding-new-regions-on-navigation).
- The document title is updated.
7. Browser history is updated (pushState or replaceState).
8. Screen reader announcement is made for accessibility.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ To keep showing the fallback, return a pending value, not `null`. After [client-

#### Inert content

Inside an interactive region (an element with `data-wp-interactive`, or any of its descendants), the Interactivity API doesn't process the directives or hydrate the interactive islands within the element's content. This covers the server-rendered fallback and the inserted HTML alike. Outside any interactive region, the attribute does nothing and the element is plain markup.
Inside an interactive region (an element with `data-wp-interactive`, or any of its descendants), the Interactivity API doesn't process the directives or hydrate the interactive islands within the element's content. This covers the server-rendered fallback and the inserted HTML alike. Outside any interactive region, the attribute does nothing and the element is plain markup. Client-side navigation ignores router regions in this content too; see [Where to place router regions](/docs/reference-guides/interactivity-api/core-concepts/client-side-navigation.md#where-to-place-router-regions).

#### Conflicts with other directives

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 3,
"name": "test/router-html-regions",
"title": "E2E Interactivity tests - HTML router regions",
"category": "text",
"supports": { "interactivity": true },
"attributes": {
"letter": { "type": "string", "default": "A" },
"next": { "type": "string", "default": "" },
"mode": { "type": "string", "default": "fallback" },
"before": { "type": "boolean", "default": false },
"copy": { "type": "boolean", "default": true }
},
"viewScriptModule": "file:./view.js",
"render": "file:./render.php"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php
/**
* Markup for navigation around inert HTML content.
*
* @package gutenberg-test-interactive-blocks
*/

// Block rendering supplies attributes; standalone inclusion uses defaults.
$fixture_attributes = get_defined_vars()['attributes'] ?? array();
$letter = $fixture_attributes['letter'] ?? 'A';
$mode = $fixture_attributes['mode'] ?? 'fallback';
$has_copy = $fixture_attributes['copy'] ?? true;
$copy_before = $fixture_attributes['before'] ?? false;
$region_value = 'attach' === $mode ? wp_json_encode(
array(
'id' => 'html/o',
'attachTo' => 'body',
)
) : 'html/r';

// Derived server state keeps fallback content without defining a client value.
wp_interactivity_state(
'router-html-regions',
array(
/**
* Computes the fallback's pending server value.
*
* @return null The client getter is intentionally unavailable.
*/
'pending' => static function () {
return null;
},
)
);

add_filter(
'script_module_data_@wordpress/interactivity',
/**
* Declares the server getter referenced by the HTML directive.
*
* @param array|null $data Serialized runtime data.
* @return array Runtime data with the pending getter declaration.
*/
static function ( $data ) {
$data = $data ?? array();
$data['derivedStateClosures']['router-html-regions'][] = 'state.pending';
return $data;
}
);

$copy_markup = $has_copy ? sprintf(
'<div data-testid="html-owner" data-wp-html="state.pending"><div data-testid="copy" data-wp-interactive="router-html-regions" data-wp-router-region="%s" data-wp-init="actions.mark"><p>copy</p></div></div>',
esc_attr( $region_value )
) : '';
?>
<div data-wp-interactive="router-html-regions">
<a data-testid="next" data-wp-on--click="actions.navigate" href="<?php echo esc_url( $fixture_attributes['next'] ?? '' ); ?>">Next</a>
<output data-testid="marks" data-wp-text="state.marks">0</output>
<?php
if ( $copy_before && 'fallback' === $mode ) {
echo $copy_markup;
}
?>
<?php if ( 'attach' !== $mode || 'B' === $letter ) : ?>
<div data-testid="real" data-wp-interactive="router-html-regions" data-wp-router-region="<?php echo esc_attr( $region_value ); ?>">
<p><?php echo esc_html( 'attach' === $mode ? 'overlay ' . $letter : $letter ); ?></p>
</div>
<?php endif; ?>
<?php
if ( ! $copy_before && 'inserted' !== $mode ) {
echo $copy_markup;
}
?>
<?php if ( 'inserted' === $mode && 'A' === $letter ) : ?>
<div data-testid="html-owner" data-wp-html="state.inserted"></div>
<?php endif; ?>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php
/**
* Script module dependencies for HTML router regions.
*
* @package gutenberg-test-interactive-blocks
*/
return array(
'dependencies' => array(
'@wordpress/interactivity',
array(
'id' => '@wordpress/interactivity-router',
'import' => 'dynamic',
),
),
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {
asDangerousHTML,
store,
withSyncEvent,
} from '@wordpress/interactivity';

const { state } = store( 'router-html-regions', {
state: {
/** Number of directives initialized inside inert copies. */
marks: 0,
/** HTML supplied during hydration, outside every router region. */
inserted: asDangerousHTML(
'<div data-wp-interactive="router-html-regions" data-wp-router-region="html/r"><p>inserted</p></div>'
),
},
actions: {
/** Records an initialization that must not occur inside HTML content. */
mark() {
state.marks++;
},
/**
* Navigates from a fixture link without a document reload.
*
* @param {MouseEvent} event Link click.
* @return {Object} Iterator yielding navigation completion.
*/
navigate: withSyncEvent( function* ( event ) {
event.preventDefault();
// currentTarget is only available during synchronous event dispatch.
const href = event.currentTarget.href;
const { actions } =
yield import( '@wordpress/interactivity-router' );
yield actions.navigate( href );
} ),
},
} );
2 changes: 2 additions & 0 deletions packages/interactivity-router/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
- `navigate()` and `prefetch()`: Only read options passed as own properties of the options object. ([#85930](https://github.com/WordPress/gutenberg/pull/85930))
- Read the Script Module data via a `script` type selector so an element with a colliding `id` (e.g. a `<div>` in post content) cannot shadow the data script tag. ([#85930](https://github.com/WordPress/gutenberg/pull/85930))
- Only render fetched pages that are same-origin HTML documents, and perform a full page load for any other response. ([#85930](https://github.com/WordPress/gutenberg/pull/85930))
- Ignore router regions and `attachTo` targets inside `data-wp-html` content ([#84919](https://github.com/WordPress/gutenberg/pull/84919)).
- Fix navigation breaking when an `attachTo` selector matches nothing or is invalid ([#84919](https://github.com/WordPress/gutenberg/pull/84919)).

## 3.0.0 (2026-10-20)

Expand Down
9 changes: 7 additions & 2 deletions packages/interactivity-router/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,15 +90,20 @@ Example:
</div>
```

The `attachTo` property is a CSS selector that points to the parent element where the new router region should be rendered. This is useful for regions that may not exist on the initial page but are present on subsequent pages, like a modal or an overlay.
Navigation ignores a router region inside the [inert content](https://developer.wordpress.org/block-editor/reference-guides/interactivity-api/directives-and-store/#inert-content) of a [`data-wp-html`](https://developer.wordpress.org/block-editor/reference-guides/interactivity-api/directives-and-store/#wp-html) element, whether that's the server-rendered fallback or HTML the directive inserted, as if the region had no `data-wp-router-region` attribute. `data-wp-html` on a router region itself doesn't make the region's content inert, because `data-wp-router-region` takes precedence. See [Where to place router regions](https://developer.wordpress.org/block-editor/reference-guides/interactivity-api/core-concepts/client-side-navigation/#where-to-place-router-regions) in the Client-Side Navigation guide.

The `attachTo` property is a CSS selector that points to the parent element where the new router region should be rendered. This is useful for regions that may not exist on the initial page but are present on subsequent pages, like a modal or an overlay. The router uses the first element on the current page that matches the selector, skipping any element with [inert `data-wp-html` content](https://developer.wordpress.org/block-editor/reference-guides/interactivity-api/directives-and-store/#inert-content) and anything inside that content.

When navigating between pages:

- If a region exists on both the current and the new page, its content is updated. `attachTo` is ignored in this case.
- If a region exists on both the current and the new page, its content is updated, and `attachTo` doesn't move it. If the new page's `attachTo` has no usable element, though, the region shows nothing, as if the new page didn't have it.
- If a region without `attachTo` exists on the new page but not on the current one, it is not added to the DOM.
- If a region with `attachTo` exists on the new page but not on the current one, it is created and appended to the parent element specified in `attachTo`.
- If the new page's `attachTo` has no usable element, the region isn't attached, and the rest of the navigation completes as if the new page didn't have the region: the other regions update, the title and URL change, and no error is thrown. There's no usable element when the selector matches nothing, when every match has inert `data-wp-html` content or is inside it, or when the selector isn't valid. The router resolves `attachTo` every time it renders the page, including on Back and Forward, so a later render can still attach the region.
- If a region exists on the current page but not on the new one, it is removed from the DOM. `attachTo` is ignored in this case.

The router ignores `attachTo` for a region that the initial page declared with `attachTo`: on every later page, that region behaves as a regular router region.

Example with `attachTo`:

```html
Expand Down
Loading
Loading