element-visibility-manager.js
1 import { isVideoActuallyPlaying, shouldShowSpinner } from '../utils/video/index.js'; 2 3 export function toggleElementVisibility(element, isVisible, visibleClassName) { 4 if (!element) { 5 return false; 6 } 7 8 if (isVisible) { 9 element.classList.add(visibleClassName); 10 } else { 11 element.classList.remove(visibleClassName); 12 } 13 14 return isVisible; 15 } 16 17 export function isElementVisible(element, visibleClassName) { 18 if (!element) { 19 return false; 20 } 21 22 return element.classList.contains(visibleClassName); 23 } 24 25 export function showElement(element, visibleClassName, hideAfterMs) { 26 if (!element) { 27 return null; 28 } 29 30 element.classList.add(visibleClassName); 31 32 if (hideAfterMs) { 33 return setTimeout(() => { 34 element.classList.remove(visibleClassName); 35 }, hideAfterMs); 36 } 37 38 return null; 39 } 40 41 export function hideElement(element, visibleClassName) { 42 if (!element) { 43 return; 44 } 45 46 element.classList.remove(visibleClassName); 47 } 48 49 export function updateSpinnerState({ 50 spinnerElement, 51 videoElement, 52 videoController, 53 videoSwitcher, 54 isVideoPaused, 55 forceShow = null, 56 visibleClassName, 57 timeoutRef = { current: null }, 58 }) { 59 if (!spinnerElement) { 60 return { isVisible: false }; 61 } 62 63 if (timeoutRef.current) { 64 clearTimeout(timeoutRef.current); 65 timeoutRef.current = null; 66 } 67 68 if (forceShow === false) { 69 spinnerElement.classList.remove(visibleClassName); 70 return { isVisible: false }; 71 } 72 73 const videoActuallyPlaying = isVideoActuallyPlaying( 74 videoElement, 75 typeof isVideoPaused === 'function' ? isVideoPaused() : true, 76 ); 77 78 const shouldBeVisible = shouldShowSpinner( 79 videoElement, 80 videoController, 81 videoSwitcher, 82 forceShow, 83 isVideoPaused, 84 ); 85 const isCurrentlyVisible = isElementVisible(spinnerElement, visibleClassName); 86 87 if (shouldBeVisible && !isCurrentlyVisible) { 88 spinnerElement.classList.add(visibleClassName); 89 90 timeoutRef.current = setTimeout(() => { 91 if (videoActuallyPlaying) { 92 spinnerElement.classList.remove(visibleClassName); 93 } 94 timeoutRef.current = null; 95 }, 3000); 96 97 return { isVisible: true }; 98 } 99 100 if (!shouldBeVisible && isCurrentlyVisible) { 101 spinnerElement.classList.remove(visibleClassName); 102 return { isVisible: false }; 103 } 104 105 if (videoActuallyPlaying && isCurrentlyVisible) { 106 timeoutRef.current = setTimeout(() => { 107 spinnerElement.classList.remove(visibleClassName); 108 timeoutRef.current = null; 109 }, 1000); 110 111 return { isVisible: true, willHide: true }; 112 } 113 114 return { isVisible: isCurrentlyVisible }; 115 } 116 117 export function clearSpinnerTimeout(timeoutRef) { 118 if (timeoutRef.current) { 119 clearTimeout(timeoutRef.current); 120 timeoutRef.current = null; 121 } 122 }