Files
JayuCloud/JC-ArtList-Frontend/src/utils/action-loading.ts
T

77 lines
2.7 KiB
TypeScript
Raw Normal View History

2026-05-23 18:44:57 +08:00
/**
* Purpose: LoadingInstance supports action-loading.ts by holding or executing the loading instance page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
import { ElLoading, type LoadingInstance } from 'element-plus'
import 'element-plus/es/components/loading/style/css'
2026-05-23 18:44:57 +08:00
/**
* Purpose: GlobalLoadingOptions supports action-loading.ts by holding or executing the global loading options page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface GlobalLoadingOptions {
text?: string
lock?: boolean
}
2026-05-23 18:44:57 +08:00
/**
* Purpose: activeLoadingCount supports action-loading.ts by holding or executing the active loading count page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let activeLoadingCount = 0
let loadingInstance: LoadingInstance | null = null
2026-05-23 18:44:57 +08:00
/**
* Purpose: openGlobalLoading supports action-loading.ts by holding or executing the open global loading page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const openGlobalLoading = (options?: GlobalLoadingOptions) => {
activeLoadingCount += 1
if (typeof window === 'undefined' || loadingInstance) {
return
}
loadingInstance = ElLoading.service({
lock: options?.lock ?? true,
text: options?.text ?? '\u52a0\u8f7d\u4e2d',
background: 'rgba(255, 255, 255, 0.72)'
})
}
2026-05-23 18:44:57 +08:00
/**
* Purpose: closeGlobalLoading supports action-loading.ts by holding or executing the close global loading page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const closeGlobalLoading = () => {
activeLoadingCount = Math.max(0, activeLoadingCount - 1)
if (activeLoadingCount > 0) {
return
}
loadingInstance?.close()
loadingInstance = null
}
2026-05-23 18:44:57 +08:00
/**
* Purpose: runWithGlobalLoading supports action-loading.ts by holding or executing the run with global loading page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
export const runWithGlobalLoading = async <T>(
task: (() => Promise<T>) | Promise<T>,
options?: GlobalLoadingOptions
) => {
openGlobalLoading(options)
try {
if (typeof task === 'function') {
return await task()
}
return await task
} finally {
closeGlobalLoading()
}
}