koel/resources/assets/js/components/ui/PlaylistThumbnail.vue

94 lines
2.3 KiB
Vue
Raw Normal View History

2024-02-24 15:37:01 +00:00
<template>
2024-04-04 22:20:42 +00:00
<article
2024-02-24 15:37:01 +00:00
:class="{ droppable }"
2024-04-04 22:20:42 +00:00
class="cover relative w-full aspect-square block rounded-md overflow-hidden bg-no-repeat bg-cover bg-center"
2024-02-24 15:37:01 +00:00
data-testid="playlist-thumbnail"
@dragenter.prevent="onDragEnter"
@dragleave.prevent="onDragLeave"
@drop.prevent="onDrop"
@dragover.prevent
>
<div class="pointer-events-none">
2024-03-19 22:48:12 +00:00
<slot />
2024-02-24 15:37:01 +00:00
</div>
2024-04-04 22:20:42 +00:00
</article>
2024-02-24 15:37:01 +00:00
</template>
2024-04-23 21:01:27 +00:00
<script lang="ts" setup>
import { computed, ref, toRefs } from 'vue'
import { defaultCover } from '@/utils'
import { playlistStore } from '@/stores'
import { useAuthorization, useErrorHandler, useFileReader, useKoelPlus } from '@/composables'
2024-02-24 15:37:01 +00:00
import { acceptedImageTypes } from '@/config'
const props = defineProps<{ playlist: Playlist }>()
const { playlist } = toRefs(props)
const droppable = ref(false)
const { isAdmin } = useAuthorization()
const { isPlus } = useKoelPlus()
2024-04-23 21:01:27 +00:00
const backgroundImage = computed(() => `url(${playlist.value.cover || defaultCover})`)
2024-04-04 22:20:42 +00:00
2024-02-24 15:37:01 +00:00
const allowsUpload = computed(() => isAdmin.value || isPlus.value)
const onDragEnter = () => (droppable.value = allowsUpload.value)
const onDragLeave = () => (droppable.value = false)
const validImageDropEvent = (event: DragEvent) => {
if (!event.dataTransfer || !event.dataTransfer.items) {
return false
}
if (event.dataTransfer.items.length !== 1) {
return false
}
if (event.dataTransfer.items[0].kind !== 'file') {
return false
}
return acceptedImageTypes.includes(event.dataTransfer.items[0].getAsFile()!.type)
}
const onDrop = async (event: DragEvent) => {
droppable.value = false
if (!allowsUpload.value) {
return
}
if (!validImageDropEvent(event)) {
return
}
const backupImage = playlist.value.cover
try {
2024-03-19 22:48:12 +00:00
useFileReader().readAsDataUrl(event.dataTransfer!.files[0], async url => {
// Replace the image right away to create an "instant" effect
playlist.value.cover = url
await playlistStore.uploadCover(playlist.value, url)
})
} catch (error: unknown) {
2024-02-24 15:37:01 +00:00
// restore the backup image
playlist.value.cover = backupImage
useErrorHandler().handleHttpError(error)
2024-02-24 15:37:01 +00:00
}
}
</script>
2024-04-23 21:01:27 +00:00
<style lang="postcss" scoped>
2024-04-04 22:20:42 +00:00
article {
background-image: v-bind(backgroundImage);
2024-02-24 15:37:01 +00:00
&.droppable {
2024-04-04 22:20:42 +00:00
@apply border-2 border-dotted border-white brightness-50;
2024-02-24 15:37:01 +00:00
}
.thumbnail-stack {
2024-04-04 22:20:42 +00:00
@apply pointer-events-none;
2024-02-24 15:37:01 +00:00
}
}
</style>