Skip to content

Commit d847876

Browse files
authored
Admin shell: Prewarm only the route a menu link opens (#55223)
* Admin shell: Prewarm only the route a menu link opens * Admin shell: Download a guest's route modules outside the prewarm queue Fix route ranking between two splat routes, and test the route stand-ins. * Admin shell: Test the route module preload
1 parent 7d2822d commit d847876

6 files changed

Lines changed: 357 additions & 21 deletions

File tree

‎projects/packages/admin-ui/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ Neither event fires while the shell is off.
229229
230230
### Admin shell: memory
231231
232-
Every dashboard the shell prewarms or mounts stays in the document until the next page load, since a booted app can't be disposed of. So the shell keeps at most a few dashboards live, the one the page loaded included, and once that many are live, opening another dashboard is a normal page load, which frees the rest. A menu link prewarms its dashboard once the pointer rests on it for 100 ms, so sweeping down the menu prewarms nothing, and hovering never spends the last slot, so the dashboard the user clicks next still opens in place. Hovering doesn't prewarm a dashboard whose page last opened to the turned-off panel. When the browser reports Save-Data, 2 GB of memory or less, or a 2G connection, hovering doesn't prewarm at all, and the dashboard loads on the click. It sizes the limit from the device memory the browser reports: 3 at 2 GB or less, 10 below 8 GB or when the browser doesn't say, and no limit from 8 GB. A site can set it with the `jetpack_admin_shell_max_live_apps` filter:
232+
Every dashboard the shell prewarms or mounts stays in the document until the next page load, since a booted app can't be disposed of. So the shell keeps at most a few dashboards live, the one the page loaded included, and once that many are live, opening another dashboard is a normal page load, which frees the rest. Prewarming downloads only the route the link opens; the dashboard's other routes load when it first navigates to them. A menu link prewarms its dashboard once the pointer rests on it for 100 ms, so sweeping down the menu prewarms nothing, and hovering never spends the last slot, so the dashboard the user clicks next still opens in place. Hovering doesn't prewarm a dashboard whose page last opened to the turned-off panel. When the browser reports Save-Data, 2 GB of memory or less, or a 2G connection, hovering doesn't prewarm at all, and the dashboard loads on the click. It sizes the limit from the device memory the browser reports: 3 at 2 GB or less, 10 below 8 GB or when the browser doesn't say, and no limit from 8 GB. A site can set it with the `jetpack_admin_shell_max_live_apps` filter:
233233
234234
```PHP
235235
add_filter( 'jetpack_admin_shell_max_live_apps', fn() => 4 );
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Significance: patch
2+
Type: changed
3+
4+
Admin shell: Prewarm only the route a menu link opens, and load a dashboard's other routes when it first reaches them.

‎projects/packages/admin-ui/src/admin-shell/adapter.js‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,36 @@ const importMapUrl = id =>
201201
.map( el => JSON.parse( el.textContent ).imports?.[ id ] )
202202
.find( Boolean );
203203

204+
/**
205+
* Download and parse modules without evaluating them, so a later import only has to evaluate.
206+
*
207+
* @param {string[]} ids - Module IDs in the page's import map.
208+
* @return {Promise<void>} Resolves once each has loaded or failed; the import reports a failure.
209+
*/
210+
export function preloadModules( ids ) {
211+
// A browser without modulepreload would fire neither load nor error.
212+
if ( ! document.createElement( 'link' ).relList?.supports?.( 'modulepreload' ) ) {
213+
return Promise.resolve();
214+
}
215+
return Promise.all(
216+
ids.map( id => {
217+
const url = importMapUrl( id );
218+
if ( ! url ) {
219+
return null;
220+
}
221+
const link = Object.assign( document.createElement( 'link' ), {
222+
rel: 'modulepreload',
223+
href: new URL( url, location.href ).href,
224+
} );
225+
const loaded = new Promise( resolve => {
226+
link.onload = link.onerror = resolve;
227+
} ).then( () => link.remove() );
228+
document.head.append( link );
229+
return loaded;
230+
} )
231+
).then( () => undefined );
232+
}
233+
204234
let bootSource;
205235

206236
/**
@@ -264,3 +294,87 @@ export async function bootFor( slug ) {
264294
URL.revokeObjectURL( blobUrl );
265295
}
266296
}
297+
298+
// A static segment outranks a `$param`, which outranks the `$` splat, as TanStack ranks them.
299+
const matchRoute = ( pattern, parts ) => {
300+
const score = [];
301+
for ( const [ i, segment ] of pattern.entries() ) {
302+
if ( segment === '$' ) {
303+
return i === pattern.length - 1 ? { score, splat: true } : null;
304+
}
305+
if ( i >= parts.length ) {
306+
return null;
307+
}
308+
if ( segment.startsWith( '$' ) ) {
309+
score.push( 1 );
310+
} else if ( segment.toLowerCase() === parts[ i ].toLowerCase() ) {
311+
score.push( 2 );
312+
} else {
313+
return null;
314+
}
315+
}
316+
return pattern.length === parts.length ? { score, splat: false } : null;
317+
};
318+
319+
const outranks = ( a, b ) => {
320+
if ( a.splat !== b.splat ) {
321+
return b.splat;
322+
}
323+
const differs = a.score.findIndex( ( rank, i ) => rank !== b.score[ i ] );
324+
return differs === -1
325+
? a.score.length > b.score.length
326+
: a.score[ differs ] > ( b.score[ differs ] ?? 0 );
327+
};
328+
329+
/**
330+
* The route boot renders for a path.
331+
*
332+
* @param {object[]} routes - wp-build routes, each with a `path` such as `/responses/$view`.
333+
* @param {string} path - The path boot reads from the `p` query argument.
334+
* @return {object|null} The matching route, or null when boot would show "Route not found".
335+
*/
336+
export function routeAt( routes, path ) {
337+
const parts = path.split( '/' ).filter( Boolean );
338+
let best = null;
339+
for ( const route of routes ) {
340+
const match = matchRoute( ( route.path ?? '' ).split( '/' ).filter( Boolean ), parts );
341+
if ( match && ( ! best || outranks( match, best.match ) ) ) {
342+
best = { route, match };
343+
}
344+
}
345+
return best?.route ?? null;
346+
}
347+
348+
const LOADERS = Symbol.for( 'jetpack-admin-shell.route-loaders' );
349+
350+
/**
351+
* Routes whose modules boot loads through `load( id )`, so the shell decides what they are evaluated with.
352+
*
353+
* Boot imports a route's modules by ID the first time it reaches that route. Each ID becomes a
354+
* stand-in that awaits `load( id )` and re-exports what boot reads: `route`, `stage`, `inspector`, `canvas`.
355+
*
356+
* @param {object[]} routes - wp-build routes.
357+
* @param {Function} load - Imports a module ID and resolves to the module.
358+
* @return {object[]} The routes, with stand-ins for their modules.
359+
*/
360+
export function routesLoadedBy( routes, load ) {
361+
const loaders = ( globalThis[ LOADERS ] ??= [] );
362+
const key = loaders.push( load ) - 1;
363+
const lookup = `globalThis[ Symbol.for( ${ JSON.stringify( LOADERS.description ) } ) ][ ${ key } ]`;
364+
// Never revoked: boot may first import one long after it boots, when the app reaches that route.
365+
const standIn = id =>
366+
URL.createObjectURL(
367+
new Blob(
368+
[
369+
`const m = await ${ lookup }( ${ JSON.stringify( id ) } );\n`,
370+
'export const { route, stage, inspector, canvas } = m;\n',
371+
],
372+
{ type: 'text/javascript' }
373+
)
374+
);
375+
return routes.map( route => ( {
376+
...route,
377+
...( route.route_module && { route_module: standIn( route.route_module ) } ),
378+
...( route.content_module && { content_module: standIn( route.content_module ) } ),
379+
} ) );
380+
}

‎projects/packages/admin-ui/src/admin-shell/index.js‎

Lines changed: 53 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ import {
88
loadPage,
99
notifyRouters,
1010
prefetchBoot,
11+
preloadModules,
12+
routeAt,
13+
routesLoadedBy,
1114
trackViewTransitions,
1215
transitionSettled,
1316
} from './adapter';
@@ -144,6 +147,29 @@ const start = ( {
144147
booting = run.catch( () => {} );
145148
return run;
146149
};
150+
// The config each guest's init set; none means the page's current one.
151+
const configOf = {};
152+
const imported = new Set();
153+
// Route modules keep the Jetpack config they are evaluated with: each gets its own page's.
154+
const evaluateAs = async ( slug, ids ) => {
155+
// Read first, to keep a config the host's init set since the last guest finished.
156+
const current = pageConfigNow();
157+
globalThis.jetpackConfig = configOf[ slug ] ?? current;
158+
const modules = await Promise.all( ids.map( id => import( /* webpackIgnore: true */ id ) ) );
159+
ids.forEach( id => imported.add( id ) );
160+
return modules;
161+
};
162+
// What a booted guest's router imports when it first reaches a route.
163+
const routeModuleLoader = slug => async id => {
164+
if ( imported.has( id ) ) {
165+
return import( /* webpackIgnore: true */ id );
166+
}
167+
log( 'switch', `${ slug }: importing ${ id } on first use` );
168+
// Downloaded outside the queue, so a prewarm another guest has queued doesn't hold up the visible one.
169+
await preloadModules( [ id ] );
170+
const [ module ] = await oneAtATime( () => evaluateAs( slug, [ id ] ) );
171+
return module;
172+
};
147173
const warm = {};
148174
const liveLimit = liveAppLimit( maxLiveApps );
149175
// Past the limit, opening another dashboard loads the page, which frees every hidden one.
@@ -154,17 +180,26 @@ const start = ( {
154180
// A page load drops the hidden apps too, edits and all; the visible one has its own beforeunload.
155181
const mayUnload = url =>
156182
[ ...apps.keys() ].every( slug => slug === visible || mayLeave( slug, url ) );
157-
// Everything short of mounting: a mounted router would start reading the visible page's URL.
158-
const prewarm = ( slug, reason ) => {
183+
/*
184+
* Everything short of mounting, for the route `url` opens: a mounted router would start reading
185+
* the visible page's URL. Other routes load when the app first reaches them.
186+
*/
187+
const prewarm = ( slug, reason, url ) => {
159188
if ( warm[ slug ] ) {
160189
return warm[ slug ];
161190
}
162191
const total = stopwatch();
163-
log( 'prewarm', `${ slug }: start (${ reason })` );
192+
log( 'prewarm', `${ slug }: start (${ reason })`, url );
164193
prefetchBoot().catch( () => {} ); // Download in parallel; bootFor() reports a failure.
194+
const path = new URL( url, location.href ).searchParams.get( 'p' ) ?? '/';
195+
const route = routeAt( members[ slug ].routes, path );
196+
const modules = [ route?.route_module, route?.content_module ].filter( Boolean );
197+
// Downloaded before this guest takes the queue, which then holds it only to evaluate them.
198+
const preloaded = preloadModules( [ ...members[ slug ].initModules, ...modules ] );
165199
warm[ slug ] = ( async () => {
166200
let step = stopwatch();
167201
const added = await applyGuestAssets( guestAssetsUrl, slug );
202+
await preloaded;
168203
log( 'prewarm', `${ slug }: page data fetched and applied in ${ step() }`, added );
169204
return oneAtATime( async () => {
170205
let guestConfig;
@@ -211,17 +246,12 @@ const start = ( {
211246
}
212247
}
213248
const boot = await bootFor( slug );
214-
const modules = members[ slug ].routes
215-
.flatMap( route => [ route.route_module, route.content_module ] )
216-
.filter( Boolean );
217249
step = stopwatch();
218-
// Set again here, in case the host's init replaced it while this guest's init ran.
219-
const current = pageConfigNow();
220-
globalThis.jetpackConfig = guestConfig ?? current;
221-
await Promise.all( modules.map( id => import( /* webpackIgnore: true */ id ) ) );
250+
configOf[ slug ] = guestConfig;
251+
await evaluateAs( slug, modules );
222252
log(
223253
'prewarm',
224-
`${ slug }: imported ${ modules.length } route modules in ${ step() }`,
254+
`${ slug }: imported ${ modules.length } modules for ${ path } in ${ step() }`,
225255
modules
226256
);
227257
log( 'prewarm', `${ slug }: ready to boot, ${ total() } in all` );
@@ -322,7 +352,7 @@ const start = ( {
322352
return;
323353
}
324354
const waited = stopwatch();
325-
const boot = await prewarm( slug, 'switch' );
355+
const boot = await prewarm( slug, 'switch', url );
326356
log( 'switch', `${ slug }: waited ${ waited() } for prewarm` );
327357
if ( visible !== slug ) {
328358
// Left before it could boot; it boots on the next visit, at that visit's URL.
@@ -334,7 +364,10 @@ const start = ( {
334364
gate.mount( slug );
335365
const render = stopwatch();
336366
log( 'switch', `${ slug }: initSinglePage into #${ el.id }` );
337-
boot.initSinglePage( { mountId: el.id, routes: members[ slug ].routes } );
367+
boot.initSinglePage( {
368+
mountId: el.id,
369+
routes: routesLoadedBy( members[ slug ].routes, routeModuleLoader( slug ) ),
370+
} );
338371
await whenRendered( el, RENDER_TIMEOUT );
339372
log( 'switch', `${ slug }: first route rendered ${ render() } after boot` );
340373
} catch ( error ) {
@@ -480,20 +513,22 @@ const start = ( {
480513
}
481514
};
482515

483-
const navigate = ( href, via ) => {
516+
// A bare menu link reopens its page where it was left, or else at the page's default path.
517+
const destinationOf = href => {
484518
const url = new URL( href, location.href );
485519
const slug = pageOf( url );
486520
const bare = [ ...url.searchParams.keys() ].length === 1 && ! url.hash;
487521
if ( bare && slug !== visible && lastUrl[ slug ] ) {
488-
log( 'switch', `bare menu link: reopening ${ slug } where it was left` );
489-
return show( lastUrl[ slug ], { push: true, via } );
522+
return lastUrl[ slug ];
490523
}
491524
if ( ! url.searchParams.has( 'p' ) && members[ slug ].defaultPath ) {
492525
url.searchParams.set( 'p', members[ slug ].defaultPath );
493526
}
494-
return show( url.href, { push: true, via } );
527+
return url.href;
495528
};
496529

530+
const navigate = ( href, via ) => show( destinationOf( href ), { push: true, via } );
531+
497532
// Not gated: the shell itself must hear Back/Forward across pages.
498533
gate.listen( 'popstate', event => {
499534
// Back/Forward inside the visible app writes nothing, so record where it now is.
@@ -583,7 +618,7 @@ const start = ( {
583618
* A hover isn't a visit, so it checks no feature, only skips one a visit found off.
584619
*/
585620
if ( ! apps.has( slug ) && ! knownOff.has( slug ) && hasRoomFor( slug, 1 ) && mayPrewarm() ) {
586-
prewarm( slug, 'menu hover' ).catch( () => {} );
621+
prewarm( slug, 'menu hover', destinationOf( a.href ) ).catch( () => {} );
587622
}
588623
}, HOVER_DELAY );
589624
} );

‎projects/packages/admin-ui/tests/js/admin-shell/adapter.test.js‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import {
22
isolateRouters,
3+
preloadModules,
34
renameBootStore,
5+
routeAt,
6+
routesLoadedBy,
47
trackViewTransitions,
58
transitionSettled,
69
} from '../../../src/admin-shell/adapter';
@@ -134,3 +137,100 @@ describe( 'renameBootStore', () => {
134137
expect( () => renameBootStore( source, 'jetpack-forms' ) ).toThrow( 'exactly once' );
135138
} );
136139
} );
140+
141+
describe( 'routeAt', () => {
142+
const routes = [
143+
'/',
144+
'/$',
145+
'/forms',
146+
'/responses/$view',
147+
'/video/$id',
148+
'/video/new',
149+
'/video/$id/editor',
150+
'/video/$',
151+
].map( path => ( { path } ) );
152+
153+
it.each( [
154+
[ '/', '/' ],
155+
[ '/forms', '/forms' ],
156+
[ '/Forms/', '/forms' ],
157+
[ '/responses/inbox', '/responses/$view' ],
158+
[ '/video/7/editor', '/video/$id/editor' ],
159+
[ '/video/new', '/video/new' ],
160+
[ '/responses', '/$' ],
161+
[ '/anything/else', '/$' ],
162+
[ '/video/7/8', '/video/$' ],
163+
] )( 'matches %s to %s', ( path, expected ) => {
164+
expect( routeAt( routes, path )?.path ).toBe( expected );
165+
} );
166+
167+
it( 'finds nothing when no route matches', () => {
168+
expect( routeAt( routes.slice( 2 ), '/responses' ) ).toBeNull();
169+
} );
170+
} );
171+
172+
describe( 'routesLoadedBy', () => {
173+
afterEach( () => delete URL.createObjectURL );
174+
175+
it( "hands each stand-in's import to the loader, and leaves a route's missing modules out", async () => {
176+
const sources = new Map();
177+
// jsdom has no createObjectURL.
178+
URL.createObjectURL = blob => {
179+
const url = `blob:${ sources.size }`;
180+
sources.set( url, blob.text() );
181+
return url;
182+
};
183+
const load = jest.fn( async id => ( { route: id, stage: 'stage' } ) );
184+
const [ both, routeOnly ] = routesLoadedBy(
185+
[
186+
{ path: '/', route_module: 'a/route', content_module: 'a/content' },
187+
{ path: '/b', route_module: 'b/route' },
188+
],
189+
load
190+
);
191+
// jsdom can't import a blob module, so its body runs as a function that returns what it exports.
192+
const run = async url =>
193+
new Function(
194+
`return ( async () => { ${ ( await sources.get( url ) ).replace(
195+
/export const \{ (.*) \} = m;/,
196+
'const { $1 } = m; return { $1 };'
197+
) } } )();`
198+
)();
199+
200+
expect( routeOnly ).toEqual( { path: '/b', route_module: expect.stringMatching( /^blob:/ ) } );
201+
await expect( run( both.content_module ) ).resolves.toEqual( {
202+
route: 'a/content',
203+
stage: 'stage',
204+
inspector: undefined,
205+
canvas: undefined,
206+
} );
207+
expect( load ).toHaveBeenCalledWith( 'a/content' );
208+
} );
209+
} );
210+
211+
describe( 'preloadModules', () => {
212+
afterEach( () => jest.restoreAllMocks() );
213+
214+
it( 'downloads the modules the import map knows, and settles once each loads or fails', async () => {
215+
jest.spyOn( DOMTokenList.prototype, 'supports' ).mockReturnValue( true );
216+
document.head.innerHTML = `<script type="importmap">${ JSON.stringify( {
217+
imports: { 'a/route': '/a/route.js?ver=1', 'b/route': '/b/route.js' },
218+
} ) }</script>`;
219+
let settled = false;
220+
const preloading = preloadModules( [ 'a/route', 'b/route', 'unknown' ] ).then(
221+
() => ( settled = true )
222+
);
223+
const links = [ ...document.head.querySelectorAll( 'link[rel="modulepreload"]' ) ];
224+
225+
expect( links.map( link => link.getAttribute( 'href' ) ) ).toEqual( [
226+
`${ location.origin }/a/route.js?ver=1`,
227+
`${ location.origin }/b/route.js`,
228+
] );
229+
links[ 0 ].dispatchEvent( new Event( 'load' ) );
230+
await Promise.resolve();
231+
expect( settled ).toBe( false );
232+
links[ 1 ].dispatchEvent( new Event( 'error' ) );
233+
await preloading;
234+
expect( document.head.querySelector( 'link' ) ).toBeNull();
235+
} );
236+
} );

0 commit comments

Comments
 (0)