|
|
import { TimerHandle } from 'calypso/types'; |
|
|
|
|
|
export interface Cancelable { |
|
|
cancel: () => void; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export default function afterLayoutFlush< T extends ( ...args: any[] ) => any >( func: T ) { |
|
|
let timeoutHandle: TimerHandle | undefined = undefined; |
|
|
let rafHandle: number | undefined = undefined; |
|
|
|
|
|
const hasRAF = typeof requestAnimationFrame === 'function'; |
|
|
|
|
|
let lastThis: any; |
|
|
let lastArgs: any[] | undefined; |
|
|
|
|
|
const scheduleRAF = function ( rafFunc: T ) { |
|
|
return function ( this: any, ...args: any[] ) { |
|
|
|
|
|
lastThis = this; |
|
|
lastArgs = args; |
|
|
|
|
|
|
|
|
if ( rafHandle !== undefined ) { |
|
|
return; |
|
|
} |
|
|
|
|
|
rafHandle = requestAnimationFrame( () => { |
|
|
|
|
|
rafHandle = undefined; |
|
|
rafFunc(); |
|
|
} ); |
|
|
} as T; |
|
|
}; |
|
|
|
|
|
const scheduleTimeout = function ( timeoutFunc: T ) { |
|
|
return function ( this: any, ...args: any[] ) { |
|
|
if ( ! hasRAF ) { |
|
|
|
|
|
lastThis = this; |
|
|
lastArgs = args; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if ( timeoutHandle !== undefined ) { |
|
|
return; |
|
|
} |
|
|
|
|
|
timeoutHandle = setTimeout( () => { |
|
|
const callArgs = lastArgs !== undefined ? lastArgs : []; |
|
|
const callThis = lastThis; |
|
|
|
|
|
lastArgs = undefined; |
|
|
lastThis = undefined; |
|
|
|
|
|
|
|
|
timeoutHandle = undefined; |
|
|
timeoutFunc.apply( callThis, callArgs ); |
|
|
}, 0 ); |
|
|
} as T; |
|
|
}; |
|
|
|
|
|
|
|
|
|
|
|
let wrappedFunc: T = scheduleTimeout( func ); |
|
|
if ( hasRAF ) { |
|
|
wrappedFunc = scheduleRAF( wrappedFunc ); |
|
|
} |
|
|
|
|
|
const wrappedWithCancel = wrappedFunc as T & Cancelable; |
|
|
wrappedWithCancel.cancel = () => { |
|
|
lastThis = undefined; |
|
|
lastArgs = undefined; |
|
|
|
|
|
if ( rafHandle !== undefined ) { |
|
|
cancelAnimationFrame( rafHandle ); |
|
|
rafHandle = undefined; |
|
|
} |
|
|
|
|
|
if ( timeoutHandle !== undefined ) { |
|
|
clearTimeout( timeoutHandle ); |
|
|
timeoutHandle = undefined; |
|
|
} |
|
|
}; |
|
|
|
|
|
return wrappedWithCancel; |
|
|
} |
|
|
|