Files
minstrel/web/src/lib/components/LikeButton.svelte
T

49 lines
1.3 KiB
Svelte

<script lang="ts">
import { useQueryClient } from '@tanstack/svelte-query';
import { createLikedIdsQuery, likeEntity, unlikeEntity, type EntityKind } from '$lib/api/likes';
let {
entityType,
entityId,
size = 'md'
}: { entityType: EntityKind; entityId: string; size?: 'sm' | 'md' | 'lg' } = $props();
const sizeClass = $derived(
size === 'sm' ? 'text-base' : size === 'lg' ? 'text-3xl' : 'text-lg'
);
const SET_KEY = {
track: 'track_ids',
album: 'album_ids',
artist: 'artist_ids'
} as const;
const queryClient = useQueryClient();
const queryStore = $derived(createLikedIdsQuery());
const query = $derived($queryStore);
const liked = $derived.by(() => {
const data = query?.data;
if (!data) return false;
return data[SET_KEY[entityType]].includes(entityId);
});
async function onClick(e: MouseEvent) {
e.stopPropagation();
e.preventDefault();
if (liked) {
await unlikeEntity(queryClient, entityType, entityId);
} else {
await likeEntity(queryClient, entityType, entityId);
}
}
</script>
<button
type="button"
aria-label={liked ? 'Unlike' : 'Like'}
aria-pressed={liked}
onclick={onClick}
class="rounded p-1 {sizeClass} {liked ? 'text-accent' : 'text-text-secondary hover:text-text-primary'}"
>{liked ? '♥' : '♡'}</button>