import React, { useState, useEffect, createContext } from 'react' import { Spinner } from '@freesewing/react/components/Spinner' import { OkIcon, WarningIcon } from '@freesewing/react/components/Icon' /* * The actual context */ export const LoadingStatusContext = createContext([false]) /* * Timeout in seconds before the loading status dissapears */ const timeout = 2 /* * The React component displaying the loading status */ const LoadingStatus = ({ loadingStatus }) => { const [fade, setFade] = useState('tw:opacity-100') const [timer, setTimer] = useState(false) useEffect(() => { if (loadingStatus[2]) { if (timer) clearTimeout(timer) setTimer( window.setTimeout( () => { setFade('opacity-0') }, timeout * 1000 - 350 ) ) } }, [loadingStatus[2]]) if (!loadingStatus[0]) return null let color = 'secondary' let icon = if (loadingStatus[2]) { color = loadingStatus[3] ? 'success' : 'error' icon = loadingStatus[3] ? ( ) : ( ) } return (
{icon} {loadingStatus[1]}
) } /* * An animated loading state */ const LoadingProgress = ({ val = 0, max = 1, msg }) => (
{msg}
) /* * The Context provider */ export const LoadingStatusContextProvider = ({ children }) => { /* * LoadingStatus should hold an array with 1 to 4 elements: * 0 => Show loading status or not (true or false) * 1 => Message to show * 2 => Set this to true to make the loadingStatus dissapear after 2 seconds * 3 => Set this to true to show success, false to show error (only when 2 is true) */ const [timer, setTimer] = useState(false) const [__loadingStatus, __setLoadingStatus] = useState({ status: [false], setLoadingStatus, loading: false, LoadingStatus: () => , LoadingProgress, }) useEffect(() => { if (__loadingStatus.status[2]) { if (timer) clearTimeout(timer) setTimer( window.setTimeout(() => { setLoadingStatus([false]) }, timeout * 1000) ) } }, [__loadingStatus.status[2]]) function setLoadingStatus(newStatus) { __setLoadingStatus({ ...__loadingStatus, status: newStatus, loading: newStatus[0] || false, LoadingStatus: () => , }) } return ( {children} ) }