| 1 |
const MILLISECONDS_MULTIPLIER = 1000; |
| 2 |
|
| 3 |
function getTransitionDurationFromElement(element) { |
| 4 |
if (!element) { |
| 5 |
return 0; |
| 6 |
} |
| 7 |
|
| 8 |
// Get transition-duration of the element |
| 9 |
let { transitionDuration, transitionDelay } = |
| 10 |
window.getComputedStyle(element); |
| 11 |
|
| 12 |
const floatTransitionDuration = Number.parseFloat(transitionDuration); |
| 13 |
const floatTransitionDelay = Number.parseFloat(transitionDelay); |
| 14 |
|
| 15 |
// Return 0 if element or transition duration is not found |
| 16 |
if (!floatTransitionDuration && !floatTransitionDelay) { |
| 17 |
return 0; |
| 18 |
} |
| 19 |
|
| 20 |
// If multiple durations are defined, take the first |
| 21 |
[transitionDuration] = transitionDuration.split(','); |
| 22 |
[transitionDelay] = transitionDelay.split(','); |
| 23 |
|
| 24 |
return ( |
| 25 |
(Number.parseFloat(transitionDuration) + |
| 26 |
Number.parseFloat(transitionDelay)) * |
| 27 |
MILLISECONDS_MULTIPLIER |
| 28 |
); |
| 29 |
} |
| 30 |
|
| 31 |
function execute(possibleCallback, args = [], defaultValue = possibleCallback) { |
| 32 |
return typeof possibleCallback === 'function' |
| 33 |
? possibleCallback(...args) |
| 34 |
: defaultValue; |
| 35 |
} |
| 36 |
|
| 37 |
export default function transitionCallback( |
| 38 |
callback, |
| 39 |
transitionElement, |
| 40 |
waitForTransition = true |
| 41 |
) { |
| 42 |
if (!waitForTransition) { |
| 43 |
execute(callback); |
| 44 |
return; |
| 45 |
} |
| 46 |
|
| 47 |
const durationPadding = 5; |
| 48 |
const emulatedDuration = |
| 49 |
getTransitionDurationFromElement(transitionElement) + durationPadding; |
| 50 |
|
| 51 |
let called = false; |
| 52 |
|
| 53 |
const handler = ({ target }) => { |
| 54 |
if (target !== transitionElement) { |
| 55 |
return; |
| 56 |
} |
| 57 |
|
| 58 |
called = true; |
| 59 |
transitionElement.removeEventListener('transitionend', handler); |
| 60 |
execute(callback); |
| 61 |
}; |
| 62 |
|
| 63 |
transitionElement.addEventListener('transitionend', handler); |
| 64 |
setTimeout(() => { |
| 65 |
if (!called) { |
| 66 |
transitionElement.dispatchEvent(new Event('transitionend')); |
| 67 |
} |
| 68 |
}, emulatedDuration); |
| 69 |
} |
| 70 |
|