Files
beavergram/frontend/src/lib/components/annotations/AnnotationsPanel.svelte
T

110 lines
3.0 KiB
Svelte

<script lang="ts">
import { untrack } from "svelte";
import {
createAnnotation,
deleteAnnotation,
listAnnotations,
updateAnnotation,
} from "#lib/api/endpoints.js";
import type { Annotation } from "#lib/api/types.js";
import EmptyState from "#lib/components/ui/EmptyState.svelte";
import Spinner from "#lib/components/ui/Spinner.svelte";
import { t } from "#lib/i18n/locale.svelte.js";
import { accounts } from "#lib/stores/accounts.svelte.js";
import { notes } from "#lib/stores/notes.svelte.js";
import { ui } from "#lib/stores/ui.svelte.js";
import { page } from "$app/state";
import AnnotationEditor from "./AnnotationEditor.svelte";
import AnnotationList from "./AnnotationList.svelte";
const chatId = $derived(
page.params.chatId ? Number(page.params.chatId) : null
);
const messageId = $derived(ui.panelMessageId);
let items = $state<Annotation[]>([]);
let loading = $state(false);
let saving = $state(false);
let token = 0;
$effect(() => {
const cid = chatId;
const mid = messageId;
if (cid === null || mid === null || accounts.selectedId === null) {
return;
}
untrack(() => {
token += 1;
const current = token;
loading = true;
items = [];
listAnnotations({ chatId: cid, messageId: mid })
.then((rows) => {
if (current === token) {
items = rows;
notes.mark(cid, mid, rows.length > 0);
}
})
.finally(() => {
if (current === token) {
loading = false;
}
});
});
});
async function add(text: string) {
if (chatId === null || messageId === null) {
return;
}
saving = true;
try {
const created = await createAnnotation(chatId, messageId, text);
items = [created, ...items];
notes.mark(chatId, messageId, true);
} finally {
saving = false;
}
}
async function edit(annotation: Annotation, text: string) {
const updated = await updateAnnotation(annotation.id, text);
items = items.map((item) => (item.id === updated.id ? updated : item));
}
async function remove(annotation: Annotation) {
await deleteAnnotation(annotation.id);
items = items.filter((item) => item.id !== annotation.id);
notes.mark(annotation.chat_id, annotation.message_id, items.length > 0);
}
</script>
{#if chatId === null || messageId === null}
<EmptyState description={t("ui.noMessage")} title={t("notes.title")} />
{:else}
<div class="panel-content">
<AnnotationEditor onsubmit={add} {saving} />
{#if loading && items.length === 0}
<div class="center"><Spinner /></div>
{:else if items.length > 0}
<AnnotationList annotations={items} ondelete={remove} onupdate={edit} />
{/if}
</div>
{/if}
<style lang="scss">
.panel-content {
display: flex;
flex-direction: column;
gap: 1rem;
padding: 1rem;
}
.center {
display: flex;
justify-content: center;
padding: 2rem 0;
}
</style>