import {createApplicationServiceComponent} from "../Application/service/createApplicationServiceComponent"; import {closeLoadingServiceHook, iLoadingServiceOption} from "./loading.service.utils"; import {computed, createHooks, getComponentCls, iHTMLDivElement, onBeforeUnmount, reactive, ref, useClasses, useRefs, useStyles} from "@peryl/react-compose"; import {ThemeStatus} from "../../uses/useStyle"; import {createTransitionHandler} from "../createTransitionHandler"; import './loading.service.scss'; import {delay} from "@peryl/utils/delay"; import {createEffects} from "@peryl/utils/createEffects"; export const LoadingService = createApplicationServiceComponent({ name: 'loading-service', setup({ option, destroy }) { const { refs, onRef } = useRefs({ el: iHTMLDivElement }); const isShow = ref(false); const isOpen = ref(false); const { effects: setupEffects } = createEffects(); const { effects: timerEffects } = createEffects(); const state = reactive({ option, percent: 0, }); const classes = useClasses(() => [ getComponentCls('loading-service'), { 'loading-service-show': isShow.value } ]); const innerStyles = useStyles(style => {style.transform = `scaleX(${state.percent})`;}); const hooks = { onOpen: createHooks(), onClose: createHooks(), }; const targetOption = computed(() => { return { ...state.option, status: state.option.status || ThemeStatus.primary, maxTime: state.option.maxTime === undefined ? 60 * 1000 : state.option.maxTime }; }); async function service(option: iLoadingServiceOption) { state.option = option; await delay(23); isShow.value = true; handleTransition(); await delay(78); state.percent = 0.2; if (targetOption.value.maxTime) { const timer = setTimeout(() => hide(), targetOption.value.maxTime); timerEffects.push(() => clearTimeout(timer)); } const maxPercent = 0.9; let spacePrefix = '0.0'; const interval = setInterval(() => { const space = Number(`${spacePrefix}${Math.ceil(Math.random() * 10)}`); state.percent = Math.min(maxPercent, state.percent + (space)); if (state.percent > 0.75 && spacePrefix.length === 3) {spacePrefix += '0';} if (state.percent >= maxPercent) {clearInterval(interval);} }, 500); timerEffects.push(() => clearInterval(interval)); } const hide = async () => { state.percent = 1; timerEffects.clear(); await delay(150); isShow.value = false; handleTransition(); }; const handleTransition = createTransitionHandler({ getTransitionElement: () => refs.el, isShow, isOpen, onOpen: () => hooks.onOpen.exec(undefined), onClose: () => hooks.onClose.exec(undefined), }); setupEffects.push(closeLoadingServiceHook.use(id => {(!id || (id === state.option.id)) && (hide());})); setupEffects.push(hooks.onClose.use(() => {destroy();})); onBeforeUnmount(setupEffects.clear); return { refer: { service, isShow, isOpen, }, render: () => (
) }; }, });