summaryrefslogtreecommitdiff
path: root/packages/frontend/src/components/SkFetchNote.vue
blob: ab702c28f84dc85ee1e7d25d09fe5ab097f7e6ae (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<!--
SPDX-FileCopyrightText: hazelnoot and other Sharkey contributors
SPDX-License-Identifier: AGPL-3.0-only
-->

<template>
<MkLazy @show="showing = true">
	<MkLoading v-if="state === 'loading'"/>

	<div v-if="state === 'error'">{{ i18n.ts.cannotLoadNote }}</div>

	<DynamicNote v-if="state === 'done' && note" :note="note"/>
</MkLazy>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import * as Misskey from 'misskey-js';
import { i18n } from '@/i18n.js';
import { misskeyApi } from '@/scripts/misskey-api';
import DynamicNote from '@/components/DynamicNote.vue';

const props = withDefaults(defineProps<{
	noteId: string,
	lazy?: boolean,
}>(), {
	lazy: true,
});

// Lazy-load, unless props.lazy is false.
// eslint-disable-next-line vue/no-setup-props-reactivity-loss
const showing = ref(!props.lazy);
const state = ref<'loading' | 'error' | 'done'>('loading');
const note = ref<Misskey.entities.Note | null>(null);

watch(
	[
		() => props.noteId,
		() => showing.value,
	],
	async ([noteId, show]) => {
		// Wait until the note is visible to avoid bombarding the API with requests.
		if (!show) return;

		// Unload the old note
		note.value = null;
		state.value = 'loading';

		// Fetch the new note
		const newNote = await misskeyApi('notes/show', { noteId }).catch(() => null);

		// Check for race conditions (ex. the note changed again while the first request was still running)
		if (noteId !== props.noteId) return;

		// Check for errors
		if (!newNote) {
			state.value = 'error';
			return;
		}

		// Display the new note
		note.value = newNote;
		state.value = 'done';
	},
	{
		immediate: true,
	},
);
</script>