diff --git a/packages/interactivity-router/src/assets/styles.ts b/packages/interactivity-router/src/assets/styles.ts index 8eebcd6da4f9f4..0e087c3630fa8b 100644 --- a/packages/interactivity-router/src/assets/styles.ts +++ b/packages/interactivity-router/src/assets/styles.ts @@ -259,12 +259,14 @@ export const applyStyles = ( styles: StyleElement[] ) => { window.document .querySelectorAll( 'style,link[rel=stylesheet]' ) .forEach( ( el: HTMLLinkElement | HTMLStyleElement ) => { - if ( styles.includes( el ) ) { - const { originalMedia = 'all' } = el.dataset; - el.sheet.media.mediaText = originalMedia; - el.sheet.disabled = false; - } else { - el.sheet.disabled = true; + if ( el.sheet ) { + if ( styles.includes( el ) ) { + const { originalMedia = 'all' } = el.dataset; + el.sheet.media.mediaText = originalMedia; + el.sheet.disabled = false; + } else { + el.sheet.disabled = true; + } } } ); }; diff --git a/packages/interactivity-router/src/index.ts b/packages/interactivity-router/src/index.ts index 34a906be5beecd..e72649ae8dce4e 100644 --- a/packages/interactivity-router/src/index.ts +++ b/packages/interactivity-router/src/index.ts @@ -46,13 +46,13 @@ interface VdomParams { interface Page { url: string; regions: Record< string, any >; - styles: Promise< StyleElement >[]; + styles: StyleElement[]; scriptModules: string[]; title: string; initialData: any; } -type RegionsToVdom = ( dom: Document, params?: VdomParams ) => Page; +type RegionsToVdom = ( dom: Document, params?: VdomParams ) => Promise< Page >; // Check if the navigation mode is full page or region based. const navigationMode: 'regionBased' | 'fullPage' = @@ -87,14 +87,8 @@ 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 = ( dom, { vdom, url } = {} ) => { +const regionsToVdom: RegionsToVdom = async ( dom, { vdom, url } = {} ) => { const regions = { body: undefined }; - const styles = prepareStyles( dom, url ); - const scriptModules = [ - ...dom.querySelectorAll< HTMLScriptElement >( - 'script[type=module][src]' - ), - ].map( ( s ) => s.src ); if ( globalThis.IS_GUTENBERG_PLUGIN ) { if ( navigationMode === 'fullPage' ) { @@ -115,21 +109,30 @@ const regionsToVdom: RegionsToVdom = ( dom, { vdom, url } = {} ) => { } const title = dom.querySelector( 'title' )?.innerText; const initialData = parseServerData( dom ); - return { regions, styles, scriptModules, title, initialData, url }; -}; -// Render all interactive regions contained in the given page. -const renderRegions = async ( page: Page ) => { + // Get module URLs. + const scriptModules = [ + ...dom.querySelectorAll< HTMLScriptElement >( + 'script[type=module][src]' + ), + ].map( ( s ) => s.src ); + // Wait for styles and modules to be ready. - await Promise.all( [ - ...page.styles, - ...page.scriptModules.map( - ( src ) => import( /* webpackIgnore: true */ src ) + const [ styles ] = await Promise.all( [ + Promise.all( prepareStyles( dom, url ) ), + Promise.all( + scriptModules.map( + ( src ) => import( /* webpackIgnore: true */ src ) + ) ), ] ); - // Replace style sheets. - const styles = await Promise.all( page.styles ); - applyStyles( styles ); + + return { regions, styles, scriptModules, title, initialData, url }; +}; + +// Render all interactive regions contained in the given page. +const renderRegions = ( page: Page ) => { + applyStyles( page.styles ); if ( globalThis.IS_GUTENBERG_PLUGIN ) { if ( navigationMode === 'fullPage' ) { @@ -181,7 +184,7 @@ window.addEventListener( 'popstate', async () => { const pagePath = getPagePath( window.location.href ); // Remove hash. const page = pages.has( pagePath ) && ( await pages.get( pagePath ) ); if ( page ) { - await renderRegions( page ); + renderRegions( page ); // Update the URL in the state. state.url = window.location.href; } else { @@ -335,13 +338,7 @@ export const { state, actions } = store< Store >( 'core/router', { ! page.initialData?.config?.[ 'core/router' ] ?.clientNavigationDisabled ) { - try { - yield renderRegions( page ); - } catch ( e ) { - // eslint-disable-next-line no-console - console.warn( e ); - yield forcePageReload( href ); - } + renderRegions( page ); window.history[ options.replace ? 'replaceState' : 'pushState' ]( {}, '', href ); diff --git a/test/e2e/specs/interactivity/router-styles.spec.ts b/test/e2e/specs/interactivity/router-styles.spec.ts index 9c6864909ea2a7..6ef93ce3348c3f 100644 --- a/test/e2e/specs/interactivity/router-styles.spec.ts +++ b/test/e2e/specs/interactivity/router-styles.spec.ts @@ -310,4 +310,71 @@ test.describe( 'Router styles', () => { await expect( blue ).toHaveCSS( 'color', COLOR_WRAPPER ); await expect( all ).toHaveCSS( 'color', COLOR_WRAPPER ); } ); + + test( 'should not cause race conditions during render', async ( { + page, + } ) => { + // Resolve functions for promises that fulfill once the target + // style is requested and resolved respectively. + let requestStyle: ( value?: unknown ) => void; + let resolveStyle: ( value?: unknown ) => void; + + // Promise that will resolve once the target style is intercepted. + // See the `page.route()` below. + const styleHasBeenRequested = new Promise( + ( resolve ) => ( requestStyle = resolve ) + ); + + // Setup a route handler to intercept a specific style sheet. + const linkPattern = '**/router-styles-red/style-from-link.css*'; + await page.route( linkPattern, async ( route ) => { + requestStyle(); + await new Promise( ( resolve ) => ( resolveStyle = resolve ) ); + await route.continue(); + } ); + + const csn = page.getByTestId( 'client-side navigation' ); + const red = page.getByTestId( 'red-from-inline' ); + const green = page.getByTestId( 'green-from-inline' ); + const blue = page.getByTestId( 'blue-from-inline' ); + const all = page.getByTestId( 'all-from-inline' ); + + await expect( red ).toHaveCSS( 'color', COLOR_WRAPPER ); + await expect( green ).toHaveCSS( 'color', COLOR_WRAPPER ); + await expect( blue ).toHaveCSS( 'color', COLOR_WRAPPER ); + await expect( all ).toHaveCSS( 'color', COLOR_WRAPPER ); + + // Hover the red link. + await page.getByTestId( 'link red' ).hover(); + + // Wait until the target style has been requested. + await styleHasBeenRequested; + + await page.getByTestId( 'link red' ).click(); + + // The red style is not ready yet; colors should stay the same. + await expect( red ).toHaveCSS( 'color', COLOR_WRAPPER ); + await expect( green ).toHaveCSS( 'color', COLOR_WRAPPER ); + await expect( blue ).toHaveCSS( 'color', COLOR_WRAPPER ); + await expect( all ).toHaveCSS( 'color', COLOR_WRAPPER ); + + await page.getByTestId( 'link green' ).click(); + + // Colors should change after navigation. + await expect( csn ).toBeVisible(); + await expect( red ).toHaveCSS( 'color', COLOR_WRAPPER ); + await expect( green ).toHaveCSS( 'color', COLOR_GREEN ); + await expect( blue ).toHaveCSS( 'color', COLOR_WRAPPER ); + await expect( all ).toHaveCSS( 'color', COLOR_GREEN ); + + // Resolve the requested style. + resolveStyle!(); + + // Styles should not change. + await expect( csn ).toBeVisible(); + await expect( red ).toHaveCSS( 'color', COLOR_WRAPPER ); + await expect( green ).toHaveCSS( 'color', COLOR_GREEN ); + await expect( blue ).toHaveCSS( 'color', COLOR_WRAPPER ); + await expect( all ).toHaveCSS( 'color', COLOR_GREEN ); + } ); } );