Skip to content

Interactivity API Router proposal: reactive state for the navigation lifecycle and its initiator #80960

Closed

Description

@luisherranz

The router (@wordpress/interactivity-router, store core/router) performs client-side navigations. It swaps router regions, updates state.url, and manages history. But it gives extenders no supported way to observe those navigations, and no way at all to tell where a navigation was initiated.

The only navigation state we have besides state.url is the deprecated state.navigation.hasStarted/hasFinished pair, and that was never really a lifecycle API. It is presentation state for Core's loading bar. It sits behind a 400 ms delay, it is only written when the loading animation is enabled, it is blind to back/forward restores and to failures, and it latches to true after the first navigation. A navigation that completes in under 400 ms (a cached or prefetched page) produces no observable transition at all.

In that vacuum, several codebases have hand-rolled the same workaround in slightly different (and slightly broken) ways.

  • Core's loading bar binds the router's private store.
  • The Query block walks the DOM with closest( '[data-wp-router-region]' ) to recover its own region, then focuses inside it after navigating.
  • The create-block interactive scaffold teaches a per-block isNavigating flag that inherits every defect described above.
  • WooCommerce's Product Collection block walks the DOM for its region and then broadcasts a custom DOM event to tell everyone else what happened.
  • Our own e2e fixtures roll their own counters.

There have been earlier attempts to fix this too. A global state.navigation.isLoading was merged and then reverted as not future-proof, and a per-block "am I the origin" context flag was explored and closed. There is also #80302, which explores a CustomEvent-based approach (more on that in a section below). And the "Changes to the Interactivity API in WordPress 7.0" dev note publicly committed that WordPress 7.1 will add an official mechanism for tracking navigation states.

This proposal is that mechanism. It is deliberately small and built only on Interactivity API primitives (reactive state you can consume with watch(), data-wp-watch, data-wp-bind, data-wp-class).

The proposal

Two new public reactive keys on the existing core/router store, plus one optional field on the existing navigate() options.

const { state } = store( 'core/router' );

state.navigating; // boolean. True while a client-side navigation is in flight.
state.initiator;  // string | null. Identity of the most recent navigation's initiator.

actions.navigate( url, { initiator: 'my-id' } ); // optional declaration

The initiator is detected by default. When navigate() is called from a directive scope (a click handler in a block, for example), the router derives the id of the innermost data-wp-router-region that contains the initiating element. The consequence is that the core Query block's enhanced pagination is identified per instance, out of the box, with zero changes to the block. Two Query blocks on the same page are distinguishable with no setup at all.

The initiator option covers the rest. Passing a string declares an explicit identity (it always wins over detection), passing null opts out, and navigations that have no scope (the full-page listener, back/forward restores, programmatic calls) read null by construction. Note that containment is not initiation. A plain link that happens to sit inside a region does not attribute the navigation to that region, only navigations started by the region's own code do.

The semantic guarantees, in plain words.

  • Every client-side navigation is observable. No 400 ms gate, no dependence on loadingAnimation, cached and same-URL navigations included. Even a navigation that completes in under a frame produces a distinct start and end that data-wp-watch can observe.
  • The end fires after the new content is committed to the DOM. A watcher reacting to the end sees the new page and the new state.url, not the old ones.
  • Back/forward restores served from the router's page cache produce a normal cycle with initiator: null, so you can finally tell a traversal apart from a navigation your block started.
  • Overlapping navigations follow the router's existing latest-wins model. The state reads in-flight continuously from the first start to the winning navigation's end, and initiator always reflects the most recent navigation. No stuck indicators, no spurious idle gaps.
  • A navigation that fails and falls back to a full page load is never reported as successfully ended.
  • On pages where the router module never loads, the keys are simply absent and read as falsy. Directives bound to them resolve without errors and no import of @wordpress/interactivity-router is needed. Because of this, the idiom is truthiness (state.navigating), never === false.

The per-region question ("is this block the origin of an in-flight navigation?") is just the conjunction of the two keys.

state.navigating && state.initiator === myRegionId

Let's see what that enables in practice.

Example 1. A per-Query-block loader, from a plugin

Imagine a plugin that overlays a loading placeholder on top of the specific Query block that is paginating. Not on every Query block, just the one the user clicked. Today this requires the kind of workarounds listed above. With this API it is basically three small files.

The PHP reads the region id the Query block already carries and injects an overlay with its own interactivity island.

add_filter( 'render_block_core/query', 'myql_add_loader', 10, 2 );

function myql_add_loader( $block_content, $block ) {
	// Only queries with enhanced pagination navigate client-side.
	if ( empty( $block['attrs']['enhancedPagination'] ) ) {
		return $block_content;
	}

	$p = new WP_HTML_Tag_Processor( $block_content );
	if ( ! $p->next_tag() ) {
		return $block_content;
	}

	$region = $p->get_attribute( 'data-wp-router-region' );
	if ( ! is_string( $region ) || '' === $region ) {
		return $block_content;
	}

	wp_enqueue_script_module( 'my-query-loader' );
	wp_enqueue_style( 'my-query-loader' );

	$overlay = sprintf(
		'<div class="myql-overlay" aria-hidden="true"
			data-wp-interactive="my-plugin/query-loader"
			data-wp-context="%s"
			data-wp-class--is-active="state.isLoading">
			<span class="myql-spinner"></span>
		</div>',
		esc_attr( wp_json_encode( array( 'regionId' => $region ) ) )
	);

	return '<div class="myql-wrap">' . $block_content . $overlay . '</div>';
}

The view module is the whole logic. Note that it imports @wordpress/interactivity only, not the router package.

import { store, getContext } from '@wordpress/interactivity';

const { state: routerState } = store( 'core/router' );

store( 'my-plugin/query-loader', {
	state: {
		get isLoading() {
			const { regionId } = getContext();
			return !! routerState.navigating && routerState.initiator === regionId;
		},
	},
} );

And the CSS does the animation, including an anti-flash trick. Since the API guarantees a cycle even for sub-frame cached navigations, the class toggles on and off within a frame or two there, so a small transition-delay on activation means the overlay never becomes visible for fast navigations. A consumer-side debounce in pure CSS.

.myql-wrap {
	position: relative;
}

.myql-overlay {
	position: absolute;
	inset: 0;
	display: grid;
	place-items: center;
	background: rgba( 255, 255, 255, 0.65 );
	opacity: 0;
	visibility: hidden;
	pointer-events: none;
	transition: opacity 120ms ease, visibility 0s 120ms;
}

.myql-overlay.is-active {
	opacity: 1;
	visibility: visible;
	pointer-events: auto;
	/* The 150ms delay is the anti-flash. Fast (cached) navigations
	   toggle the class within a frame, so opacity never ramps. */
	transition: opacity 120ms ease 150ms, visibility 0s;
}

The resulting behavior falls out of the semantics. With two Query blocks, only the one that paginated shows its overlay. If the user paginates block A and then block B before A finishes, A's overlay turns off at the moment B takes over (the initiator switches) and B's turns on. On back/forward, initiator is null, so no overlay shows. On a failed navigation the overlay stays visible while the page falls back to a full reload, which I think is the honest reading, since the page really is loading.

Example 2. Region-scoped focus that is actually correct

The Query block moves focus into its region after navigating. Today it does that by awaiting actions.navigate(), and that mechanism has real problems. A navigation that gets superseded by another block resolves its promise indistinguishably from success, so with two Query blocks racing, the losing block still runs its focus code, possibly before the winning navigation has even rendered. And back/forward restores run no focus logic at all, because there is no promise to await there.

With the two keys, the pattern is a watcher on the falling edge.

store( 'my-plugin/query-loader', {
	callbacks: {
		manageFocus() {
			const ctx = getContext();
			const navigating = !! routerState.navigating;
			if (
				ctx.wasNavigating &&
				! navigating &&
				routerState.initiator === ctx.regionId
			) {
				document
					.querySelector( `[data-wp-router-region="${ ctx.regionId }"] a[href]` )
					?.focus();
			}
			ctx.wasNavigating = navigating;
		},
	},
} );

Bound with data-wp-watch="callbacks.manageFocus", this fixes all three problems structurally. There is exactly one end per settled cycle (a superseded navigation never publishes an end, the state just stays in-flight until the winner finishes), the initiator at the end identifies the winner (so only the block that actually navigated focuses), and the end is guaranteed to fire after the new DOM is committed (so the query hits the new page, with no need to capture DOM references before navigating). Traversals read initiator: null, so the code correctly refrains on back/forward instead of misfiring.

To clarify, migrating the Query block's own focus logic onto this would be follow-up work, not part of this proposal. The point here is that the API makes that migration possible and correct.

What about view transitions?

This API is shaped so a future view-transitions phase can land on top of it without breaking anyone, but it deliberately does not implement any of it now.

The relevant choices are three. First, navigating is a boolean and is documented to stay true across any future sub-phases of a navigation, so nobody's spinner breaks the day a pre-commit phase signal is added (React kept useTransition's isPending boolean unchanged when it layered <ViewTransition> on the same mechanism, which I think is good precedent). Second, the end timing contract is one-sided. The end is published after the new content is committed, and the delay between commit and end is explicitly not bounded, so a future release could publish the end when a view transition settles instead of at the next frame, and that would be a narrowing, not a break. Third, the documentation will state where future growth lands (a navigation kind, from/to URLs, caller-supplied metadata, a pre-commit signal, all as additional state on core/router) together with the consumer rules that make those additions non-breaking (read the keys you know and ignore the rest, never treat the set of keys as closed, consume navigating by truthiness).

Why reactive state and not DOM events?

This is worth addressing head on, because #80302 explores the opposite route (two CustomEvents on window) and its motivation deserves a fair answer. The concern there is a real audience. Scripts that are not built on the Interactivity API and never will be, like consent managers, tag managers, analytics, or chat widgets. They land on the page as plain script tags, and the argument goes that they cannot call watch().

I think that argument does not quite hold, for two reasons.

First, the genuinely vendor-controlled snippet does not know our custom event either. An event name like wp-router-navigation-end is exactly as WordPress-specific as watch() is. Generic vendor SDKs integrate with the web platform instead. They wrap history.pushState or use their platform's native mechanisms (GTM's built-in History Change trigger, for example). Since the router already calls pushState, those mechanisms fire for client-side navigations today, with zero WordPress code involved.

Second, whoever can write the WordPress-specific glue for an event listener can write the same glue against the reactive state. A classic script tag can import the runtime dynamically, because the import map WordPress prints applies to the whole document, and it is guaranteed to be present on any page where the router navigates (the router depends on it).

import( '@wordpress/interactivity' ).then( ( { store, watch } ) => {
	const { state } = store( 'core/router' );
	watch( () => {
		if ( ! state.navigating ) {
			myVendorThing.pageChanged( state.url );
		}
	} );
} );

(On pages without script modules the bare specifier rejects, so real glue would wrap this in a catch. An event listener degrades silently instead. That is fair to count as an ergonomic point for events, but I think it is a small one.)

That said, there is an asymmetry that in my opinion decides the question. Events are derivable from the state in userland, with a few lines of watch() that dispatch whatever event shape you like. The reverse is not possible, since there is no way to reconstruct reactive, directive-consumable state from DOM events. So if Core commits to one permanent surface, it has to be the state. A DOM event layer can still be added later, additively, in Core or even as a tiny bridge plugin, if grounded demand shows up. Shipping both from day one would mean maintaining two vocabularies for every semantic decision (supersession, failures, back/forward coverage, end timing) and keeping them agreeing with each other forever.

One honest concession. Events model discrete occurrences and can carry per-navigation payloads (#80302's detail includes url, referrer, and title), while latest-wins state intentionally does not represent superseded navigations as separate records. For analytics-grade "log every navigation" needs, that gap is real. My reading is that it points at per-navigation data (a navigation kind, from/to URLs), which is exactly what the growth section above reserves room for, rather than at DOM events as the delivery mechanism. But I would love to hear about use cases where this reading falls short.

What this deliberately does not change

  • No custom DOM events. Reactive store state is the delivery mechanism, per the Interactivity API's model (see the previous section for the reasoning).
  • The deprecated state.navigation machinery is untouched, so Core's loading bar keeps working exactly as today.
  • navigate() promise semantics, the a11y announcements, the 400 ms loading-animation debounce, prefetch(), page caching, and popstate handling are all observably unchanged.
  • No cancellation or interception of navigations. This is a read channel.
  • No lifecycle for prefetch(). A hover-triggered prefetch firing "navigation started" would corrupt every loading-indicator use case.

Follow-ups

Two pieces of work are deliberately not part of this proposal, but are worth naming here because this API unlocks the first one and the research for it surfaced the second one.

Migrating the existing consumers. The Query block's focus logic, the create-block interactive template, and (outside this repo) WooCommerce's Product Collection could all drop their workarounds and consume the two keys instead. Example 2 above is basically the shape the Query migration would take. Keeping the migrations out of the API PR keeps it small and reviewable, and they become straightforward follow-up issues once the API lands.

Fixing the pre-commit ordering inside navigate(). While researching this we found a pre-existing quirk. The hash scroll, the "loaded" screen reader announcement, and the history.pushState call all run before the new DOM is actually committed (the render batch returns with the old DOM still in place, and the commit lands a moment later). The navigate() promise also resolves without a commit guarantee. This proposal deliberately does not touch any of that, since its whole compatibility story is that existing observable behavior stays exactly as it is. But reordering that tail to run after the commit would fix hash scrolls that target elements that only exist on the new page, make the announcement truthful, and give await navigate() an honest "the DOM you see is the new one" contract. It is an observable behavior change, so it deserves its own issue and its own compatibility discussion.

Feedback

My feeling is that the two flat keys plus the detected-by-default initiator hit a good balance between "as simple as possible" and "actually correct in the edge cases" (supersession, fast cached navigations, back/forward, failures), but this is exactly the kind of API where more eyes help.

Some questions I would love opinions on.

  • Naming. state.navigating and state.initiator.
  • The detected-by-default attribution. Declaration-only would be a smaller surface, but detection is what makes Query (and existing third-party blocks) work per instance with zero changes. Does anyone see a case where deriving the enclosing region id would be surprising?
  • Any use cases for the lifecycle or the initiator that these semantics would not cover?

Other thoughts? :)

Activity

  1. fabiankaegy commented on Jul 30, 2026

    @fabiankaegy
    Member

    @luisherranz Thanks for this. On first read this all looks and sounds very promising! I never realized that it would be possible to do this:

    import( '@wordpress/interactivity' ).then( ( { store, watch } ) => {
    	const { state } = store( 'core/router' );
    	watch( () => {
    		if ( ! state.navigating ) {
    			myVendorThing.pageChanged( state.url );
    		}
    	} );
    } );

    With that I agree that the custom event is no needed 👍

    I will let this marinate a bit more :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions