import { type Component, computed, getCurrentScope, markRaw, onScopeDispose, type Ref, ref } from 'vue'; type Options = { delay?: number; }; type Content = string | Component; type LoadingItem = { id: string; content?: Content; props?: Ref; timer: ReturnType | 0; clearOnDispose?: boolean; }; type LoadingItemOption = Pick; type UsePLoading = { show: Ref; content: Content; props: Ref; loadingShow: (loadingItem: LoadingItemOption) => void; loadingHide: (id?: LoadingItemOption['id']) => void; isLoading: (id?: LoadingItemOption['id']) => boolean; }; const LOADING_TEXT = 'Loading...'; const show = ref(false); const loadingItems = ref([]); const content = computed(() => loadingItems.value[loadingItems.value.length - 1]?.content); const props = computed(() => loadingItems.value[loadingItems.value.length - 1]?.props); export const usePLoading = (options?: Options): UsePLoading => { const { delay } = { delay: 200, ...options }; const scope = getCurrentScope(); const clearLoadingItems = () => { loadingItems.value.forEach((item) => { clearTimeout(item.timer); }); loadingItems.value = []; }; const loadingShow = (loadingItem: LoadingItemOption) => { let timer: ReturnType | 0 = 0; if (!loadingItem.id) { throw new Error('id is required'); } if (loadingItems.value.length === 0 && delay > 0) { timer = setTimeout(() => { show.value = true; }, delay); } else { show.value = true; } loadingItems.value.push({ id: loadingItem.id, content: loadingItem.content && typeof loadingItem.content === 'object' ? markRaw(loadingItem.content) : loadingItem.content || LOADING_TEXT, props: loadingItem.props, timer, clearOnDispose: loadingItem.clearOnDispose ?? true, }); }; const loadingHide = (id?: LoadingItemOption['id']) => { if (id && typeof id === 'string') { const index = loadingItems.value.findIndex((item) => item.id === id); const loadingItem = loadingItems.value[index]; if (index !== -1) { clearTimeout(loadingItem.timer); loadingItems.value.splice(index, 1); } } else { clearLoadingItems(); } if (loadingItems.value.length === 0) { show.value = false; } }; const isLoading = (id?: LoadingItemOption['id']) => { if (id) { return loadingItems.value.some((item) => item.id === id); } return loadingItems.value.length > 0; }; if (scope) { onScopeDispose(() => { if (loadingItems.value.some((item) => item.clearOnDispose === false)) { loadingItems.value.forEach((item) => { if (item.clearOnDispose) { clearTimeout(item.timer); } }); loadingItems.value = loadingItems.value.filter((item) => item.clearOnDispose === false); } else { clearLoadingItems(); show.value = false; } }); } return { show, content, props, loadingShow, loadingHide, isLoading }; };