Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Interactivity API: router with region-based client-side navigation #53733

Merged
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,15 @@
</button>
</div>
</div>

<div
data-wp-interactive
data-wp-navigation-id="navigation"
data-wp-context='{ "text": "first page" }'
>
<div data-testid="navigation text" data-wp-text="context.text"></div>
<div data-testid="navigation new text" data-wp-text="context.newText"></div>
<button data-testid="toggle text" data-wp-on--click="actions.toggleText">Toggle Text</button>
<button data-testid="add new text" data-wp-on--click="actions.addNewText">Add new text</button>
<button data-testid="navigate" data-wp-on--click="actions.navigate">Navigate</button>
</div>
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
( ( { wp } ) => {
const { store } = wp.interactivity;
const { store, navigate } = wp.interactivity;

const html = `
<div
data-wp-interactive
data-wp-navigation-id="navigation"
data-wp-context='{ "text": "second page" }'
>
<div data-testid="navigation text" data-wp-text="context.text"></div>
<div data-testid="navigation new text" data-wp-text="context.newText"></div>
<button data-testid="toggle text" data-wp-on--click="actions.toggleText">Toggle Text</button>
<button data-testid="add new text" data-wp-on--click="actions.addNewText">Add new text</button>
<button data-testid="navigate" data-wp-on--click="actions.navigate">Navigate</button>
</div>`;

store( {
derived: {
Expand All @@ -17,6 +30,18 @@
toggleContextText: ( { context } ) => {
context.text = context.text === 'Text 1' ? 'Text 2' : 'Text 1';
},
toggleText: ( { context } ) => {
context.text = "changed dynamically";
},
addNewText: ( { context } ) => {
context.newText = 'some new text';
},
navigate: () => {
navigate( window.location, {
force: true,
html,
} );
}
},
} );
} )( window );
5 changes: 5 additions & 0 deletions packages/interactivity/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,15 @@

## Unreleased

### Enhancements

- Merge new server-side rendered context on client-side navigation. ([#53853](https://github.com/WordPress/gutenberg/pull/53853))

## 2.1.0 (2023-08-16)

### New Features

- Support region-based client-side navigation. ([#53733](https://github.com/WordPress/gutenberg/pull/53733))
luisherranz marked this conversation as resolved.
Show resolved Hide resolved
- Allow passing optional `afterLoad` callbacks to `store` calls. ([#53363](https://github.com/WordPress/gutenberg/pull/53363))

### Bug Fix
Expand Down
26 changes: 15 additions & 11 deletions packages/interactivity/src/directives.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* External dependencies
*/
import { useContext, useMemo, useEffect } from 'preact/hooks';
import { useContext, useMemo, useEffect, useRef } from 'preact/hooks';
import { deepSignal, peek } from 'deepsignal';

/**
Expand Down Expand Up @@ -36,20 +36,24 @@ export default () => {
'context',
( {
directives: {
context: { default: context },
context: { default: newContext },
},
props: { children },
context: inherited,
context: inheritedContext,
} ) => {
const { Provider } = inherited;
const inheritedValue = useContext( inherited );
const value = useMemo( () => {
const localValue = deepSignal( context );
mergeDeepSignals( localValue, inheritedValue );
return localValue;
}, [ context, inheritedValue ] );
const { Provider } = inheritedContext;
const inheritedValue = useContext( inheritedContext );
const currentValue = useRef( deepSignal( {} ) );
currentValue.current = useMemo( () => {
const newValue = deepSignal( newContext );
mergeDeepSignals( newValue, currentValue.current );
mergeDeepSignals( newValue, inheritedValue );
return newValue;
}, [ newContext, inheritedValue ] );

return <Provider value={ value }>{ children }</Provider>;
return (
<Provider value={ currentValue.current }>{ children }</Provider>
);
},
{ priority: 5 }
);
Expand Down
22 changes: 0 additions & 22 deletions packages/interactivity/src/hydration.js

This file was deleted.

9 changes: 3 additions & 6 deletions packages/interactivity/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,17 @@
* Internal dependencies
*/
import registerDirectives from './directives';
import { init } from './hydration';
import { init } from './router';
import { rawStore, afterLoads } from './store';
export { store } from './store';
export { directive } from './hooks';
export { navigate, prefetch } from './router';
export { h as createElement } from 'preact';
export { useEffect, useContext, useMemo } from 'preact/hooks';
export { deepSignal } from 'deepsignal';

/**
* Initialize the Interactivity API.
*/
registerDirectives();

document.addEventListener( 'DOMContentLoaded', async () => {
registerDirectives();
await init();
afterLoads.forEach( ( afterLoad ) => afterLoad( rawStore ) );
} );
127 changes: 127 additions & 0 deletions packages/interactivity/src/router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/**
* External dependencies
*/
import { hydrate, render } from 'preact';
/**
* Internal dependencies
*/
import { toVdom, hydratedIslands } from './vdom';
import { createRootFragment } from './utils';
import { directivePrefix } from './constants';

// The cache of visited and prefetched pages.
const pages = new Map();

// Keep the same root fragment for each interactive region node.
const regionRootFragments = new WeakMap();
const getRegionRootFragment = ( region ) => {
if ( ! regionRootFragments.has( region ) ) {
regionRootFragments.set(
region,
createRootFragment( region.parentElement, region )
);
}
return regionRootFragments.get( region );
};

// Helper to remove domain and hash from the URL. We are only interesting in
// caching the path and the query.
const cleanUrl = ( url ) => {
const u = new URL( url, window.location );
return u.pathname + u.search;
};

// Fetch a new page and convert it to a static virtual DOM.
const fetchPage = async ( url, { html } ) => {
try {
if ( ! html ) {
const res = await window.fetch( url );
if ( res.status !== 200 ) return false;
html = await res.text();
}
const dom = new window.DOMParser().parseFromString( html, 'text/html' );
return regionsToVdom( dom );
} catch ( e ) {
return false;
}
};

// Return an object with VDOM trees of those HTML regions marked with a
// `navigation-id` directive.
const regionsToVdom = ( dom ) => {
const regions = {};
const attrName = `data-${ directivePrefix }-navigation-id`;
dom.querySelectorAll( `[${ attrName }]` ).forEach( ( region ) => {
const id = region.getAttribute( attrName );
regions[ id ] = toVdom( region );
} );

return { regions };
};

// Prefetch a page. We store the promise to avoid triggering a second fetch for
// a page if a fetching has already started.
export const prefetch = ( url, options = {} ) => {
url = cleanUrl( url );
if ( options.force || ! pages.has( url ) ) {
pages.set( url, fetchPage( url, options ) );
}
};

// Render all interactive regions contained in the given page.
const renderRegions = ( page ) => {
const attrName = `data-${ directivePrefix }-navigation-id`;
document.querySelectorAll( `[${ attrName }]` ).forEach( ( region ) => {
const id = region.getAttribute( attrName );
const fragment = getRegionRootFragment( region );
render( page.regions[ id ], fragment );
} );
};

// Navigate to a new page.
export const navigate = async ( href, options = {} ) => {
const url = cleanUrl( href );
prefetch( url, options );
const page = await pages.get( url );
if ( page ) {
renderRegions( page );
window.history[ options.replace ? 'replaceState' : 'pushState' ](
{},
'',
href
);
} else {
window.location.assign( href );
}
};

// Listen to the back and forward buttons and restore the page if it's in the
// cache.
window.addEventListener( 'popstate', async () => {
const url = cleanUrl( window.location ); // Remove hash.
const page = pages.has( url ) && ( await pages.get( url ) );
if ( page ) {
renderRegions( page );
} else {
window.location.reload();
}
} );

// Initialize the router with the initial DOM.
export const init = async () => {
document
.querySelectorAll( `[data-${ directivePrefix }-interactive]` )
.forEach( ( node ) => {
if ( ! hydratedIslands.has( node ) ) {
const fragment = getRegionRootFragment( node );
const vdom = toVdom( node );
hydrate( vdom, fragment );
}
} );

// Cache the current regions.
pages.set(
cleanUrl( window.location ),
Promise.resolve( regionsToVdom( document ) )
);
};
18 changes: 18 additions & 0 deletions test/e2e/specs/interactivity/directives-context.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,4 +162,22 @@ test.describe( 'data-wp-context', () => {
await expect( element ).toHaveText( 'Text 1' );
await expect( element ).toHaveAttribute( 'value', 'Text 1' );
} );

test( 'should replace values on navigation', async ( { page } ) => {
const element = page.getByTestId( 'navigation text' );
await expect( element ).toHaveText( 'first page' );
await page.getByTestId( 'toggle text' ).click();
await expect( element ).toHaveText( 'changed dynamically' );
await page.getByTestId( 'navigate' ).click();
await expect( element ).toHaveText( 'second page' );
} );

test( 'should preserve the previous context values', async ( { page } ) => {
const element = page.getByTestId( 'navigation new text' );
await expect( element ).toHaveText( '' );
await page.getByTestId( 'add new text' ).click();
await expect( element ).toHaveText( 'some new text' );
await page.getByTestId( 'navigate' ).click();
await expect( element ).toHaveText( 'some new text' );
} );
} );