Priority Queue: Fix for environments that don't have window defined#20486
Conversation
windowwindow
windowwindow defined
| */ | ||
| export function createRequestIdleCallback() { | ||
| if ( typeof 'window' === undefined ) { | ||
| if ( typeof window === 'undefined' ) { |
There was a problem hiding this comment.
Nice spotting. Would there by any chance of getting this in for 7.6.0 @aduth ?
There was a problem hiding this comment.
I can publish this fix to npm once merged.
There was a problem hiding this comment.
Interesting that no-constant-condition lint rule didn't catch this, I suppose that's because undefined can be a bound name?
There was a problem hiding this comment.
Thanks! This looks like a straightforward bug fix.
It looks like this bug would prevent the fallback function from ever being used, so I wanted to verify this works as expected. I changed a few things to rely on the typechecker:
/**
* @return {Window['requestIdleCallback'|'requestAnimationFrame']}
*/
export function createRequestIdleCallback() {
if ( typeof window === 'undefined' ) {
/**
* @param {Parameters<Window['requestAnimationFrame']>[0]} callback
*/
const requestIdleCallback = ( callback ) => {
setTimeout( () => callback( Date.now() ), 0 );
return -1;
};
return requestIdleCallback;
}
return window.requestIdleCallback || window.requestAnimationFrame;
}
export default createRequestIdleCallback();Notes:
- Narrow the type to satisfy
Window['requestIdleCallback'|'requestAnimationFrame'] - Type the returned function parameter
Date.now()is a number, but therequestIdleCallbackcallback parameter expects anIdleDeadline, which is more complex.numberdoes satisfy the callback ofrequestAnimationFrame.- Returns a
numberhandle.-1seems safe as it shouldn't collide, however ifwindowisundefined, andcancelIdleCallbackdoesn't exist, they're unlikely to ever be cancelled 🙂
|
I cherry-picked this commit to |
|
Thanks all for managing this, and sorry for having introduced this careless error 😬 |
Description
Importing
@wordpress/priority-queue, directly or indirectly, into an environment withoutwindowcauses an error.For example including the following in a test file so you can test a reducer:
and then running
jest --env=nodewill fail with a "window is not defined" error.The erroring code was added in #19282, and it looks like it was supposed to guard against this but there was just a typo.
How has this been tested?
I've tested this change against the test suite where I'm getting the errors and it resolves the issue.
Types of changes
Bug fix. I can't think of any situations where this would break existing code. The branch that includes the mock
requestIdleCallbackimplementation is basically in aif ( false ) { ... }block at the moment, so I can't think of a way that any code would start using the wrong implementation.Checklist: