import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { act } from 'preact/test-utils';
import '../directives';
import { hydrateRegions, initialVdom } from '../hydration';
import { populateServerData, store } from '../store';
import { getContext, getElement, getServerContext } from '../scopes';
import { asDangerousHTML } from '../html';
/** Counter for store namespaces, whose registry persists between tests. */
let namespaceCount = 0;
/**
* Provides an independent store namespace for each hydration fixture.
*
* @return A namespace unused by earlier tests.
*/
function uniqueNamespace(): string {
return `test/hydration-${ ++namespaceCount }`;
}
describe( 'hydrateRegions', () => {
beforeEach( () => {
document.body.innerHTML = '';
} );
afterEach( () => {
vi.unstubAllGlobals();
} );
it( 'hydrates descendants of ignored HTML variants without evaluating their references', async () => {
vi.stubGlobal( 'SCRIPT_DEBUG', false );
const namespace = uniqueNamespace();
const nestedNamespace = uniqueNamespace();
const readHtml = vi.fn();
const renderHtml = vi.fn( () => asDangerousHTML( 'ignored' ) );
const initialize = vi.fn();
const { state } = store( namespace, {
state: {
/** Text shared by the ordinary descendants and host bindings. */
label: 'hydrated',
/**
* Records reference reads before returning an HTML function.
*
* @return The function that an ignored entry must never call.
*/
get html() {
readHtml();
return renderHtml;
},
},
actions: {
/** Updates descendants through their normal event handler. */
update() {
state.label = 'updated';
},
},
} );
store( nestedNamespace, {
actions: {
/** Records initialization within each ignored binding's content. */
initialize,
},
} );
const variants = [ '', '---id', '--suffix', '--suffix---id' ];
document.body.innerHTML = `
${ variants
.map(
( variant ) =>
`
`
)
.join( '' ) }
following
`;
const hosts = [ ...document.querySelectorAll( 'section' ) ];
const children = hosts.map( ( host ) => host.firstElementChild );
await act( () => hydrateRegions() );
expect(
hosts.map( ( host ) => host.querySelector( 'span' )!.textContent )
).toEqual( variants.map( () => 'hydrated' ) );
expect( initialize ).toHaveBeenCalledTimes( variants.length );
expect( readHtml ).not.toHaveBeenCalled();
expect( renderHtml ).not.toHaveBeenCalled();
await act( () => hosts[ 1 ].querySelector( 'button' )!.click() );
expect(
hosts.map( ( host ) => host.querySelector( 'span' )!.textContent )
).toEqual( variants.map( () => 'updated' ) );
expect( hosts.map( ( host ) => host.title ) ).toEqual(
variants.map( () => 'updated' )
);
expect( hosts.map( ( host ) => host.firstElementChild ) ).toEqual(
children
);
expect( document.querySelector( 'p' ) ).toHaveTextContent(
/^updated$/
);
expect( initialize ).toHaveBeenCalledTimes( variants.length );
expect( readHtml ).not.toHaveBeenCalled();
expect( renderHtml ).not.toHaveBeenCalled();
} );
it.each( [ false, true ] )(
'hydrates HTML fallback islands only outside an interactive region (inside: %s)',
async ( inside ) => {
const namespace = uniqueNamespace();
const mark = vi.fn();
const markFollowing = vi.fn();
populateServerData( {
// Identifies HTML as a getter whose implementation is pending.
state: { [ namespace ]: { html: {} } },
derivedStateClosures: { [ namespace ]: [ 'state.html' ] },
} );
store( namespace, {
state: {
/** Text rendered only by eligible islands. */
label: 'live',
},
actions: {
/** Records initialization inside HTML content. */
mark,
/** Records initialization of the following ordinary island. */
markFollowing,
},
} );
const htmlElement = ``;
document.body.innerHTML =
( inside
? `${ htmlElement }
`
: htmlElement ) +
`static
`;
const fallback = document.querySelector( '[data-wp-html] span' )!;
const paragraph = document.querySelector( 'p' )!;
const island = fallback.parentElement!;
const roots = [
...document.querySelectorAll( '[data-wp-interactive]' ),
].filter(
( node ) =>
! node.parentElement?.closest( '[data-wp-interactive]' )
);
await act( () => hydrateRegions() );
expect( mark ).toHaveBeenCalledTimes( inside ? 0 : 1 );
expect( fallback ).toHaveTextContent(
inside ? /^static$/ : /^live$/
);
expect( fallback.isConnected ).toBe( true );
expect( document.querySelector( 'p' ) ).toBe( paragraph );
expect( paragraph ).toHaveTextContent( /^fallback$/ );
expect( initialVdom.has( island ) ).toBe( ! inside );
for ( const root of roots ) {
expect( initialVdom.has( root ) ).toBe( true );
}
expect( markFollowing ).toHaveBeenCalledTimes( 1 );
expect(
document.querySelector( '#following span' )
).toHaveTextContent( /^live$/ );
}
);
it.each( [ false, true ] )(
'runs template islands, never server item islands, when the list is pending: %s',
async ( pending ) => {
const namespace = uniqueNamespace();
const origins: unknown[] = [];
const after = vi.fn();
if ( pending ) {
populateServerData( {
// The list's getter has not yet registered on the client.
state: { [ namespace ]: { list: {} } },
derivedStateClosures: { [ namespace ]: [ 'state.list' ] },
} );
}
store( namespace, {
state: pending
? {}
: {
/** Items whose template islands run as part of the list. */
list: [ 'one', 'two' ],
},
actions: {
/** Records the origin of every initialized list island. */
mark: () => {
origins.push(
Reflect.get(
getElement().attributes,
'data-origin'
)
);
},
/** Records initialization of the separate following island. */
after,
},
} );
const serverItem = ``;
document.body.innerHTML = `${ serverItem }${ serverItem }
`;
const roots = [
document.querySelector( '#list' )!,
document.querySelector( '#following' )!,
];
const serverItems = [
...document.querySelectorAll( '[data-wp-each-child]' ),
];
const serverIslands = serverItems.map(
( item ) => item.firstElementChild!
);
await act( () => hydrateRegions() );
expect( origins ).toEqual(
pending ? [] : [ 'template', 'template' ]
);
expect( after ).toHaveBeenCalledTimes( 1 );
for ( const root of roots ) {
expect( initialVdom.has( root ) ).toBe( true );
}
for ( const island of serverIslands ) {
expect( initialVdom.has( island ) ).toBe( false );
}
expect(
[
...document.querySelectorAll( '[data-origin="server"]' ),
].map( ( island ) => island.parentElement )
).toEqual( pending ? serverItems : [] );
expect(
serverIslands.every( ( island ) => island.isConnected )
).toBe( pending );
if ( pending ) {
await act( async () => {
store( namespace, {
state: {
/**
* Supplies the pending derived list.
*
* @return The two list items to render.
*/
get list() {
return [ 'one', 'two' ];
},
},
} );
} );
}
expect( origins ).toEqual( [ 'template', 'template' ] );
expect(
serverIslands.every( ( island ) => ! island.isConnected )
).toBe( true );
expect( after ).toHaveBeenCalledTimes( 1 );
}
);
it( 'keeps fallback and inserted islands inert when trusted HTML replaces content during hydration and reactive updates', async () => {
const namespace = uniqueNamespace();
const mark = vi.fn();
const markFollowing = vi.fn();
const island = `static
`;
const { state } = store( namespace, {
state: {
/** Replaces fallback islands while the initial snapshot is processed. */
html: asDangerousHTML( `` ),
/** Text that must not render inside either fallback or inserted HTML. */
label: 'hydrated',
},
actions: {
/** Records any initialization of an inert island. */
mark,
/** Records initialization after the replaced fallback in document order. */
markFollowing,
},
} );
document.body.innerHTML = `static
`;
const target = document.querySelector( '[data-wp-html]' )!;
const fallbackIsland = target.firstElementChild!;
await act( () => hydrateRegions() );
expect( fallbackIsland.isConnected ).toBe( false );
expect( fallbackIsland.querySelector( 'span' ) ).toHaveTextContent(
/^static$/
);
expect( target.innerHTML ).toBe( `` );
expect( mark ).not.toHaveBeenCalled();
expect( markFollowing ).toHaveBeenCalledTimes( 1 );
expect( document.querySelector( '#following span' ) ).toHaveTextContent(
/^hydrated$/
);
await act( () => {
state.html = asDangerousHTML( `${ island }` );
state.label = 'updated';
} );
expect( target.innerHTML ).toBe( `${ island }` );
expect( mark ).not.toHaveBeenCalled();
expect( document.querySelector( '#following span' ) ).toHaveTextContent(
/^updated$/
);
} );
it( 'keeps the server-rendered content of data-wp-each items whose value is the server representation', async () => {
const propertyNamespace = uniqueNamespace();
const itemNamespace = uniqueNamespace();
populateServerData( {
state: {
[ propertyNamespace ]: {
list: [
{ html: { wpServerHtml: true } },
{ html: { wpServerHtml: true } },
],
},
[ itemNamespace ]: { list: [ { wpServerHtml: true } ] },
},
} );
const { state } = store( propertyNamespace, { state: {} } );
const listState = state as { list: Array< { html: unknown } > };
document.body.innerHTML = `
`;
const targets = [
...document.querySelectorAll< HTMLElement >( '[data-wp-html]' ),
];
const serverNodes = targets.map(
( target ) => target.firstElementChild
);
await act( () => hydrateRegions() );
await new Promise( ( resolve ) => setTimeout( resolve, 0 ) );
targets.forEach( ( target, index ) =>
expect( target.firstElementChild ).toBe( serverNodes[ index ] )
);
// An item added on the client shows the template's fallback.
await act( () => {
listState.list = [
...listState.list,
{ html: { wpServerHtml: true } },
];
} );
const items = [
...document.querySelectorAll< HTMLElement >(
'#property [data-wp-html]'
),
];
expect( items.map( ( item ) => item.innerHTML ) ).toEqual( [
'one',
'two',
'Fallback',
] );
// A token updates only its own item.
await act( () => {
listState.list[ 0 ].html = asDangerousHTML( 'new' );
} );
await new Promise( ( resolve ) => setTimeout( resolve, 0 ) );
expect( items.map( ( item ) => item.innerHTML ) ).toEqual( [
'new',
'two',
'Fallback',
] );
expect( items[ 1 ].firstElementChild ).toBe( serverNodes[ 1 ] );
} );
it( 'leaves no scope behind when a directive throws during hydration', async () => {
const namespace = uniqueNamespace();
const failure = new Error( 'directive failure' );
vi.stubGlobal( 'SCRIPT_DEBUG', true );
store( namespace, {
actions: {
/** Throws while the element it is attached to renders. */
fail: () => {
throw failure;
},
},
} );
document.body.innerHTML = ``;
await expect( act( () => hydrateRegions() ) ).rejects.toBe( failure );
// A callback scheduled after hydration runs without a scope.
const results = await new Promise< Array< { value?: unknown } > >(
( resolve ) => {
setTimeout( () => {
resolve(
[ getContext, getElement, getServerContext ].map(
( reader ) => {
try {
return { value: reader( namespace ) };
} catch {
return {};
}
}
)
);
}, 0 );
}
);
expect( results ).toEqual( [ {}, {}, {} ] );
} );
} );