summaryrefslogtreecommitdiff
path: root/packages/frontend/src/components/hook/useLoading.ts
blob: 6c6ff6ae0d5a128ed8ee0d5e167f728f1f231303 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
 * SPDX-FileCopyrightText: syuilo and misskey-project
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import { computed, h, ref } from 'vue';
import MkLoading from '@/components/global/MkLoading.vue';

export const useLoading = (props?: {
	static?: boolean;
	inline?: boolean;
	colored?: boolean;
	mini?: boolean;
	em?: boolean;
}) => {
	const showingCnt = ref(0);

	const show = () => {
		showingCnt.value++;
	};

	const close = (force?: boolean) => {
		if (force) {
			showingCnt.value = 0;
		} else {
			showingCnt.value = Math.max(0, showingCnt.value - 1);
		}
	};

	const scope = <T>(fn: () => T) => {
		show();

		const result = fn();
		if (result instanceof Promise) {
			return result.finally(() => close());
		} else {
			close();
			return result;
		}
	};

	const showing = computed(() => showingCnt.value > 0);
	const component = computed(() => showing.value ? h(MkLoading, props) : null);

	return {
		show,
		close,
		scope,
		component,
		showing,
	};
};