A self-hosted media server and file management system
Vue ffmpegfile-serverjellyfinlaravelmediamedia-playermedia-servermediabrowsermediaservermusicmusic-librarymusic-playermusicplayerself-hostedvuejs
feat: new lyrics editor and tests
aminnausin3e2d9e474dc6
diff --git a/package-lock.json b/package-lock.jsonindex e776b98b..fe06eed7 100755--- a/package-lock.json+++ b/package-lock.json@@ -23,6 +23,7 @@"devDependencies": {"@7nohe/laravel-typegen": "^0.6.1","@eslint/js": "^9.7.0",+ "@faker-js/faker": "^9.8.0","@iconify-json/cil": "^1.2.2","@iconify-json/circum": "^1.1.11","@iconify-json/formkit": "^1.2.2",@@ -891,6 +892,23 @@"node": "^18.18.0 || ^20.9.0 || >=21.1.0"}},+ "node_modules/@faker-js/faker": {+ "version": "9.8.0",+ "resolved": "https://registry.npmjs.org/@faker-js/faker/-/faker-9.8.0.tgz",+ "integrity": "sha512-U9wpuSrJC93jZBxx/Qq2wPjCuYISBueyVUGK7qqdmj7r/nxaxwW8AQDCLeRO7wZnjj94sh3p246cAYjUKuqgfg==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fakerjs"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0",+ "npm": ">=9.0.0"+ }+ },"node_modules/@humanfs/core": {"version": "0.19.1","resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz",@@ -2076,9 +2094,9 @@}},"node_modules/@vitest/pretty-format": {- "version": "3.1.4",- "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.1.4.tgz",- "integrity": "sha512-cqv9H9GvAEoTaoq+cYqUTCGscUjKqlJZC7PRwY5FMySVj5J+xOm1KQcCiYHJOEzOKRUhLH4R2pTwvFlWCEScsg==",+ "version": "3.2.1",+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.1.tgz",+ "integrity": "sha512-xBh1X2GPlOGBupp6E1RcUQWIxw0w/hRLd3XyBS6H+dMdKTAqHDNsIR2AnJwPA3yYe9DFy3VUKTe3VRTrAiQ01g==","dev": true,"license": "MIT","dependencies": {@@ -2117,6 +2135,19 @@"url": "https://opencollective.com/vitest"}},+ "node_modules/@vitest/snapshot/node_modules/@vitest/pretty-format": {+ "version": "3.1.4",+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.1.4.tgz",+ "integrity": "sha512-cqv9H9GvAEoTaoq+cYqUTCGscUjKqlJZC7PRwY5FMySVj5J+xOm1KQcCiYHJOEzOKRUhLH4R2pTwvFlWCEScsg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tinyrainbow": "^2.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },"node_modules/@vitest/spy": {"version": "3.1.4","resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.1.4.tgz",@@ -2145,6 +2176,19 @@"url": "https://opencollective.com/vitest"}},+ "node_modules/@vitest/utils/node_modules/@vitest/pretty-format": {+ "version": "3.1.4",+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.1.4.tgz",+ "integrity": "sha512-cqv9H9GvAEoTaoq+cYqUTCGscUjKqlJZC7PRwY5FMySVj5J+xOm1KQcCiYHJOEzOKRUhLH4R2pTwvFlWCEScsg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tinyrainbow": "^2.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },"node_modules/@volar/language-core": {"version": "2.4.14","resolved": "https://registry.npmjs.org/@volar/language-core/-/language-core-2.4.14.tgz",@@ -7508,9 +7552,9 @@"license": "MIT"},"node_modules/tinyglobby": {- "version": "0.2.13",- "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.13.tgz",- "integrity": "sha512-mEwzpUgrLySlveBwEVDMKk5B57bhLPYovRfPAXD5gA/98Opn0rCDj3GtLwFvCvH5RK9uPCExUROW5NjDwvqkxw==",+ "version": "0.2.14",+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz",+ "integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==","dev": true,"license": "MIT","dependencies": {@@ -7553,9 +7597,9 @@}},"node_modules/tinypool": {- "version": "1.0.2",- "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.0.2.tgz",- "integrity": "sha512-al6n+QEANGFOMf/dmUMsuS5/r9B06uwlyNjZZql/zv8J7ybHCgoihBNORZCY2mzUuAnomQa2JdhyHKzZxPCrFA==",+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.0.tgz",+ "integrity": "sha512-7CotroY9a8DKsKprEy/a14aCCm8jYVmR7aFy4fpkZM8sdpNJbKkixuNjgM50yCmip2ezc8z4N7k3oe2+rfRJCQ==","dev": true,"license": "MIT","engines": {diff --git a/package.json b/package.jsonindex b5ddff81..839caadc 100755--- a/package.json+++ b/package.json@@ -34,6 +34,7 @@"devDependencies": {"@7nohe/laravel-typegen": "^0.6.1","@eslint/js": "^9.7.0",+ "@faker-js/faker": "^9.8.0","@iconify-json/cil": "^1.2.2","@iconify-json/circum": "^1.1.11","@iconify-json/formkit": "^1.2.2",diff --git a/resources/js/components/cards/LrcLibCard.vue b/resources/js/components/cards/LrcLibCard.vuenew file mode 100644index 00000000..b37c551c--- /dev/null+++ b/resources/js/components/cards/LrcLibCard.vue@@ -0,0 +1,111 @@+<script setup lang="ts">+import type { LrcLibResult } from '@/types/types';++import { toFormattedDuration } from '@/service/util';+import { useLyricStore } from '@/stores/LyricStore';+import { storeToRefs } from 'pinia';+import { computed } from 'vue';++import ButtonIcon from '@/components/inputs/ButtonIcon.vue';+import ChipTag from '@/components/labels/ChipTag.vue';++import ProiconsEye from '~icons/proicons/eye';+import PrimeSave from '~icons/prime/save';++const { dirtyLyric } = storeToRefs(useLyricStore());++const props = defineProps<{ data: LrcLibResult }>();+const emit = defineEmits(['preview', 'select']);++const tags = computed(() => {+ return [+ {+ name: toFormattedDuration(props.data.duration),+ },+ {+ name: props.data.syncedLyrics ? 'Synced' : 'Plain',+ class: props.data.syncedLyrics ? '!bg-violet-600 dark:!bg-white dark:text-neutral-900 shadow-md' : '!bg-neutral-800 opacity-70',+ },+ ];+});+</script>+<template>+ <div+ :class="[+ 'relative flex flex-wrap justify-between items-center gap-2',+ 'rounded-lg shadow p-3 w-full transition',+ 'bg-neutral-50 dark:bg-primary-dark-800/70 dark:hover:bg-violet-700/70 hover:bg-primary-800',+ 'text-neutral-600 dark:text-neutral-100',+ `ring-[0.125rem] ${data.id === dirtyLyric?.id ? 'ring-violet-700/60' : 'ring-transparent dark:ring-neutral-700/20'}`,+ ]"+ >+ <section class="flex justify-between gap-2 w-full items-center">+ <h3 class="flex-1 truncate min-w-[30%] text-gray-900 dark:text-white" :title="data.trackName">+ {{ data.trackName }}+ </h3>+ <ButtonIcon+ class="!h-6 !w-6 ring-0 transition !p-1 rounded-md"+ type="button"+ :variant="'transparent'"+ :title="data.id === dirtyLyric?.id ? 'Already Selected' : 'Select'"+ :disabled="data.id === dirtyLyric?.id"+ @click="$emit('select')"+ >+ <template #icon>+ <PrimeSave class="w-4 h-4" />+ </template>+ </ButtonIcon>+ <ButtonIcon+ v-if="data.syncedLyrics"+ class="!h-6 !w-6 ring-0 transition !p-1 rounded-md"+ type="button"+ :variant="'transparent'"+ :title="'Preview'"+ @click="$emit('preview')"+ >+ <template #icon>+ <ProiconsEye class="w-4 h-4" />+ </template>+ </ButtonIcon>+ </section>+ <section class="flex flex-wrap justify-between gap-x-4 gap-y-2 w-full items-start text-sm">+ <span class="flex gap-2 items-center w-full flex-1">+ <span class="flex gap-1 truncate flex-1">+ <h4 class="text-nowrap text-start truncate" title="Album">+ {{ data.albumName }}+ </h4>++ <h4>-</h4>+ <h4 class="text-ellipsis text-wrap line-clamp-1 min-w-fit" title="Artist">+ {{ data.artistName }}+ </h4>+ </span>++ <span class="hidden sm:flex gap-1 max-h-[22px] justify-end overflow-clip [overflow-clip-margin:4px]">+ <ChipTag+ v-for="(tag, index) in tags"+ :key="index"+ :label="tag.name"+ :textClass="'text-xs'"+ :colour="+ tag.class ??+ 'bg-neutral-200 leading-none text-neutral-500 shadow dark:bg-neutral-900 hover:bg-violet-600 hover:text-neutral-50 hover:dark:bg-violet-600/90'+ "+ />+ </span>+ </span>++ <span class="sm:hidden w-full flex flex-wrap gap-1 overflow-clip [overflow-clip-margin:4px]">+ <ChipTag+ v-for="(tag, index) in tags"+ :key="index"+ :label="tag.name"+ :textClass="'text-xs'"+ :colour="+ tag.class ?? 'bg-neutral-200 leading-none text-neutral-500 shadow dark:bg-neutral-900 hover:bg-violet-600 hover:text-neutral-50 hover:dark:bg-violet-600/90'+ "+ />+ </span>+ </section>+ </div>+</template>diff --git a/resources/js/components/forms/EditLyrics.vue b/resources/js/components/forms/EditLyrics.vuenew file mode 100644index 00000000..86dc9842--- /dev/null+++ b/resources/js/components/forms/EditLyrics.vue@@ -0,0 +1,219 @@+<script setup lang="ts">+import type { LyricsUpdateRequest } from '@/types/requests';+import type { VideoResource } from '@/types/resources';+import type { FormField } from '@/types/types';+import type { Ref } from 'vue';++import { generateLyricsSearchQuery, updateLyrics } from '@/service/lyricsService';+import { onMounted, reactive, watch } from 'vue';+import { toFormattedDuration } from '@/service/util';+import { useContentStore } from '@/stores/ContentStore';+import { useLyricStore } from '@/stores/LyricStore';+import { storeToRefs } from 'pinia';+import { toast } from '@/service/toaster/toastService';++import FormInputNumber from '@/components/inputs/FormInputNumber.vue';+import FormInputLabel from '@/components/labels/FormInputLabel.vue';+import FormTextArea from '@/components/inputs/FormTextArea.vue';+import ButtonForm from '@/components/inputs/ButtonForm.vue';+import LrcLibCard from '@/components/cards/LrcLibCard.vue';+import DatePicker from '@/components/pinesUI/DatePicker.vue';+import FormInput from '@/components/inputs/FormInput.vue';+import useForm from '@/composables/useForm';++import SvgSpinners90RingWithBg from '~icons/svg-spinners/90-ring-with-bg';++const { isLoadingLyrics, stateLyrics, searchResults, hasSearchedForLyrics, dirtyLyric } = storeToRefs(useLyricStore());+const { handlePreviewLyrics, handleSelectLyrics, handleSearchSyncedLyrics, resetLyrics } = useLyricStore();++const emit = defineEmits(['handleFinish', 'preview']);+const props = defineProps<{ video: VideoResource }>(); // TODO: Eventually use this instead of stateVideo so that it is decoupled from state and can work alone++const fields = reactive<FormField[]>([+ {+ name: 'track',+ text: 'Track Title',+ type: 'text',+ required: true,+ value: props.video.title,+ default: props.video.title,+ max: 255,+ },+ {+ name: 'artist',+ text: 'Artist Name',+ type: 'text',+ required: true,+ placeholder: 'Use the artist name to refine your search',+ value: dirtyLyric.value?.artistName,+ max: 255,+ },+ {+ name: 'album',+ text: 'Album Name',+ type: 'text',+ required: true,+ placeholder: 'Use the album name to refine your search',+ value: dirtyLyric.value?.albumName,+ max: 255,+ },+ {+ name: 'duration',+ text: `Song Duration`,+ type: 'text',+ value: toFormattedDuration(props.video.metadata?.duration),+ disabled: !props.video.metadata?.duration,+ subtext: 'Try to match this value',+ placeholder: `No duration set`,+ },+ {+ name: 'lyrics',+ text: `Lyrics`,+ type: 'textArea',+ value: props.video.metadata?.lyrics,+ subtext: 'Format: [mm:ss] line',+ placeholder: `No lyrics yet`,+ default: '',+ },+]);++const form = useForm<LyricsUpdateRequest>({+ track: props.video.metadata?.title ?? props.video.title ?? '',+ lyrics: props.video.metadata?.lyrics ?? '',+ artist: props.video.metadata?.artist ?? '',+ album: props.video.metadata?.album ?? '',+});++const handleSubmit = async () => {+ form.submit(+ async (fields) => {+ if (!props.video.metadata?.id) {+ throw new Error('Metadata Malformed!');+ }+ return updateLyrics(props.video.metadata.id, fields);+ },+ {+ onSuccess: (response) => {+ emit('handleFinish', response?.data);+ toast.add('Success', { type: 'success', description: 'Edit submitted!', life: 3000 });+ },+ onError: () => {+ toast.add('Error', { type: 'danger', description: 'Unable to update lyrics details.', life: 3000 });+ },+ },+ );+};++const handleLoadLyricInfo = () => {+ if (!dirtyLyric.value?.id) {+ form.reset(...Object.keys(form.fields));+ return;+ }++ form.fields.album = dirtyLyric.value.albumName;+ form.fields.artist = dirtyLyric.value.artistName;+ form.fields.lyrics = stateLyrics.value;+};++onMounted(() => {+ handleLoadLyricInfo();+});++watch(+ () => dirtyLyric.value,+ () => {+ handleLoadLyricInfo();+ },+);+</script>++<template>+ <form class="flex flex-col sm:flex-row sm:justify-between flex-wrap gap-4" @submit.prevent="handleSubmit">+ <div v-for="(field, index) in fields.filter((field) => !field.disabled)" :key="index" class="w-full text-sm" :class="field.class">+ <FormInputLabel :field="field" />+ <FormInput v-if="field.name === 'duration'" :field="field" v-model="field.value" disabled title="Song Duration" />+ <FormTextArea v-else-if="field.type === 'textArea'" v-model="form.fields[field.name]" :field="field" />+ <DatePicker v-else-if="field.type === 'date'" v-model="form.fields[field.name]" :field="field" />+ <FormInputNumber v-else-if="field.type === 'number'" v-model="form.fields[field.name]" :field="field" />+ <FormInput v-else v-model="form.fields[field.name]" :field="field" />+ <ul class="text-sm text-rose-600 dark:text-rose-400">+ <li v-for="(item, index) in form.errors[field.name]" :key="index">{{ item }}</li>+ </ul>+ </div>++ <div class="flex w-full gap-4 flex-wrap xs:flex-nowrap">+ <div class="flex items-center gap-2 flex-wrap">+ <ButtonForm+ :class="'h-8 line-clamp-1 truncate !rounded-full hover:!ring-violet-400 hover:dark:!ring-violet-700 hover:ring-[0.125rem]'"+ :disabled="isLoadingLyrics"+ @click="handleSearchSyncedLyrics(generateLyricsSearchQuery(video.metadata, form.fields.track, form.fields.album, form.fields.artist))"+ >+ <template #text>Search for Lyrics</template>+ </ButtonForm>+ <ButtonForm :class="'h-8 !rounded-full hover:!ring-violet-400 hover:dark:!ring-violet-700 hover:ring-[0.125rem]'" :disabled="isLoadingLyrics" @click="resetLyrics">+ <template #text>Reset</template>+ </ButtonForm>+ </div>+ <p class="text-sm ml-auto h-8 text-nowrap items-center flex min-w-fit" v-show="hasSearchedForLyrics">Results: {{ searchResults.length }}</p>+ </div>++ <div class="flex flex-col gap-2 w-full" v-if="isLoadingLyrics || hasSearchedForLyrics || searchResults.length !== 0">+ <div class="flex gap-2 flex-col w-full">+ <LrcLibCard v-for="result in searchResults" :key="result.id" :data="result" @preview="handlePreviewLyrics(result)" @select="handleSelectLyrics(result)" />+ <div+ v-if="isLoadingLyrics || (hasSearchedForLyrics && searchResults.length === 0)"+ class="col-span-full flex items-center justify-center text-center text-gray-500 text-sm dark:text-gray-400 uppercase tracking-wider w-full gap-2"+ >+ <p>{{ isLoadingLyrics ? '...Loading' : 'No Results' }}</p>+ <SvgSpinners90RingWithBg v-show="isLoadingLyrics" />+ </div>+ </div>+ <ButtonForm+ v-show="!isLoadingLyrics && !hasSearchedForLyrics && searchResults.length !== 0"+ :class="'mx-auto h-8 !rounded-full'"+ :disabled="isLoadingLyrics"+ @click="handleSearchSyncedLyrics(generateLyricsSearchQuery(video.metadata, form.fields.track, form.fields.album, form.fields.artist))"+ >+ <template #text> show more </template>+ </ButtonForm>+ </div>++ <p class="text-sm text-rose-600 dark:text-rose-400 text-center w-full" v-if="form.fields.lyrics !== video.metadata?.lyrics && video.metadata?.lyrics">+ Overwriting Existing Lyrics!+ </p>++ <p class="text-sm text-rose-600 dark:text-rose-400 text-center w-full" v-if="form.fields.artist !== video.metadata?.artist && video.metadata?.artist">+ Overwriting Existing Artist Name!+ </p>++ <p class="text-sm text-rose-600 dark:text-rose-400 text-center w-full" v-if="form.fields.album !== video.metadata?.album && video.metadata?.album">+ Overwriting Existing Album Name!+ </p>++ <div class="relative flex flex-col-reverse sm:flex-row sm:justify-end gap-2 w-full">+ <button+ @click="+ () => {+ $emit('handleFinish');+ resetLyrics();+ }+ "+ type="button"+ class="inline-flex items-center justify-center h-10 px-4 py-2 text-sm font-medium transition-colors border dark:border-neutral-600 rounded-md focus:outline-none"+ :class="'focus:ring-1 focus:ring-neutral-100 dark:focus:ring-neutral-400 focus:ring-offset-1 hover:bg-neutral-100 dark:hover:bg-neutral-900'"+ :disabled="form.processing"+ >+ Cancel+ </button>+ <button+ @click="handleSubmit"+ type="button"+ class="inline-flex items-center justify-center h-10 px-4 py-2 text-sm font-medium text-white transition-colors border border-transparent rounded-md focus:outline-none"+ :class="'focus:ring-1 focus:ring-violet-900 focus:ring-offset-1 bg-neutral-950 hover:bg-neutral-800 dark:hover:bg-neutral-900 '"+ :disabled="form.processing"+ >+ Save Changes+ </button>+ </div>+ </form>+</template>diff --git a/resources/js/components/forms/EditVideo.vue b/resources/js/components/forms/EditVideo.vueindex 794bf4b3..1288ce81 100755--- a/resources/js/components/forms/EditVideo.vue+++ b/resources/js/components/forms/EditVideo.vue@@ -49,11 +49,12 @@ const fields = reactive<FormField[]>([},{name: 'lyrics',- text: `Embedded ${isAudio.value ? 'Lyrics' : 'Captions'}`,+ text: `Embedded Lyrics`,type: 'textArea',value: props.video?.metadata?.lyrics,subtext: 'Format: [mm:ss] line',- placeholder: `No ${isAudio.value ? 'lyrics' : 'captions'} yet.`,+ placeholder: `No lyrics yet.`,+ disabled: !isAudio.value,default: '',},{diff --git a/resources/js/components/video/VideoLyrics.vue b/resources/js/components/video/VideoLyrics.vueindex 97f5f334..b9aeb89b 100644--- a/resources/js/components/video/VideoLyrics.vue+++ b/resources/js/components/video/VideoLyrics.vue@@ -3,23 +3,27 @@ import type { VideoResource } from '@/types/resources';import type { LyricItem } from '@/types/types';import { computed, onMounted, onUnmounted, ref, useTemplateRef, watch, nextTick, type Ref } from 'vue';-import { fetchSyncedLyrics } from '@/service/metadataService';+import { toFormattedDuration } from '@/service/util';import { useContentStore } from '@/stores/ContentStore';+import { useLyricStore } from '@/stores/LyricStore';import { storeToRefs } from 'pinia';-import { toast } from '@/service/toaster/toastService';-import ChipTag from '@/components/labels/ChipTag.vue';-import VideoLyricItem from './VideoLyricItem.vue';+import VideoLyricItem from '@/components/video/VideoLyricItem.vue';+import EditLyrics from '@/components/forms/EditLyrics.vue';+import ButtonIcon from '@/components/inputs/ButtonIcon.vue';+import ModalBase from '@/components/pinesUI/ModalBase.vue';+const { stateLyrics, editLyricsModal, dirtyLyric, isLoadingLyrics } = storeToRefs(useLyricStore());const { stateVideo } = storeToRefs(useContentStore()) as unknown as { stateVideo: Ref<VideoResource> };+const { handleGenerateLyrics, handleOpenLyricsModal } = useLyricStore();+const { updateVideoData } = useContentStore();+const emit = defineEmits<{ seek: [value: number] }>();const props = defineProps<{ rawLyrics: string; timeElapsed: string | number; timeDuration: number; isPaused: boolean }>();-const localLyrics = ref<string>();-const lyricItems = ref<LyricItem[]>();const lyrics = computed(() => {- const availableLyrics = props.rawLyrics || localLyrics.value;+ const availableLyrics = stateLyrics.value;if (!availableLyrics) return [{ text: 'No lyrics yet...' }];const result = availableLyrics.split('\n').map((line) => {@@ -31,15 +35,17 @@ const lyrics = computed(() => {return { text: text.trim(), time: seconds, percentage: toPercentageTime(seconds) };});- lyricItems.value = result.filter((line) => {+ return result;+});++const lyricItems = computed(() => {+ return lyrics.value.filter((line) => {return line.time !== undefined;}) as LyricItem[];-- return result;});+const activeLyricElement = ref<HTMLElement | null>(null);const lyricsContainer = useTemplateRef<HTMLElement | null>('lyrics-container');-const $activeLyric = ref<HTMLElement | null>(null);const lyricObserver = ref<IntersectionObserver>();const activeTime = ref(0);@@ -93,7 +99,8 @@ const handleUpdate = () => {if (index < 0) return;const current = lyricItems.value[index];- if (!current || !current.time || (current.time === activeTime.value && isActiveLyricVisible.value)) return;++ if (!current || current.time === undefined || (current.time === activeTime.value && isActiveLyricVisible.value)) return;activeTime.value = current.time;@@ -107,47 +114,34 @@ const handleUpdate = () => {nextTick(() => {if (!lyricObserver.value) return;- if ($activeLyric.value) lyricObserver.value.unobserve($activeLyric.value);+ if (activeLyricElement.value) lyricObserver.value.unobserve(activeLyricElement.value);if (!target) return;- $activeLyric.value = target;- lyricObserver.value?.observe($activeLyric.value);+ activeLyricElement.value = target;+ lyricObserver.value?.observe(activeLyricElement.value);});};-const handleGenerateLyrics = async () => {- try {- if (!stateVideo.value?.metadata) {- toast.error('Data is malformed.');- return;- }- const lyrics = await fetchSyncedLyrics(stateVideo.value.metadata.id);-- if (!lyrics) {- toast.error('Lyrics not found...');- }-- localLyrics.value = lyrics;- stateVideo.value.metadata.lyrics = lyrics;- } catch (error: any) {- toast.error(`${error}`);- }-};-+// Resets scroll position and active lyric / lineconst resetComponent = () => {activeTime.value = 0;- if ($activeLyric.value && lyricObserver.value) {- lyricObserver.value.unobserve($activeLyric.value);+ if (activeLyricElement.value && lyricObserver.value) {+ lyricObserver.value.unobserve(activeLyricElement.value);}- $activeLyric.value = null;- if (localLyrics.value !== props.rawLyrics) localLyrics.value = '';+ activeLyricElement.value = null;+nextTick(() => {lyricsContainer.value?.scrollTo({ top: 0, behavior: 'smooth' });if (lyrics.value[0].percentage) activeTime.value = lyrics.value[0].percentage;});};+const handleLyricsUpdated = (data: VideoResource) => {+ editLyricsModal.value.toggleModal(false);+ updateVideoData(data);+};+onMounted(() => {if (!lyricsContainer.value) return;@@ -175,8 +169,8 @@ onMounted(() => {},);- if ($activeLyric.value) {- lyricObserver.value.observe($activeLyric.value);+ if (activeLyricElement.value) {+ lyricObserver.value.observe(activeLyricElement.value);}});@@ -187,30 +181,52 @@ onUnmounted(() => {watch(() => props.timeElapsed, handleUpdate);watch(() => props.isPaused, handleUpdate);-watch(() => props.rawLyrics, resetComponent);+watch(() => stateVideo.value, resetComponent);</script><template><section class="flex flex-col h-full w-full overflow-y-scroll scrollbar-hide text-sm sm:text-xl text-center fade-mask" ref="lyrics-container" v-show="lyrics.length > 0"><div class="shrink-0" style="height: 45%"></div><VideoLyricItemv-for="(lyric, index) in lyrics"+ :key="index"+ v-show="lyric.time || lyric.text.trim().length != 0":lyric="lyric":index="index":is-active="lyric.time === activeTime"- @clicked="lyric.time ? handleClick(`lyric-${lyric.time}`, lyric.time) : null"+ :title="lyric.time ? toFormattedDuration(lyric.time) : ''"+ @clicked="lyric.time !== undefined ? handleClick(`lyric-${lyric.time}`, lyric.time) : null"/><VideoLyricItemv-if="lyrics.length === 1 && lyrics[0].text === 'No lyrics yet...'"- :lyric="{ text: 'Magic Button...' }"+ :lyric="{ text: `${isLoadingLyrics ? 'Generating' : 'Generate with Magic'}...` }":is-active="false":index="0"+ :class="{ '!opacity-60': isLoadingLyrics }"@clicked="handleGenerateLyrics"/><div class="shrink-0" style="height: 45%"></div></section><div class="absolute top-0 left-0 right-0 h-12 pointer-events-auto" style="z-index: 6"></div><div class="absolute bottom-0 left-0 right-0 h-16 pointer-events-auto" style="z-index: 6"></div>- <ChipTag v-show="localLyrics" class="absolute top-4 right-4" :text-class="'!text-gray-900'" :colour="'bg-white/70'" :label="'preview'" />+ <div class="absolute top-4 right-4 flex gap-1" style="z-index: 7">+ <ButtonIcon+ variant="ghost"+ :class="`${dirtyLyric ? 'rounded-full opacity-90' : 'opacity-70 rounded-md bg-transparent'} px-2 pointer-events-auto hover:opacity-100 hover:text-yellow-500 hover:bg-neutral-900/30 bg-neutral-900/10 transition p-1`"+ @click="handleOpenLyricsModal"+ title="Edit Lyrics"+ >+ <template #text+ ><p class="h-4">{{ dirtyLyric ? 'preview' : 'edit' }}</p></template+ >+ </ButtonIcon>+ </div>+ <ModalBase :modalData="editLyricsModal" :useControls="false">+ <template #content>+ <div class="pt-2">+ <EditLyrics :video="stateVideo" @handleFinish="handleLyricsUpdated" />+ </div>+ </template>+ </ModalBase></template><style lang="css" scoped>diff --git a/resources/js/service/__test__/lyricsService.test.ts b/resources/js/service/__test__/lyricsService.test.tsnew file mode 100644index 00000000..2b9f1778--- /dev/null+++ b/resources/js/service/__test__/lyricsService.test.ts@@ -0,0 +1,32 @@+import { fetchSyncedLyrics, searchSyncedLyrics, updateLyrics, generateLyricsSearchQuery } from '../lyricsService';+import { API } from '../api';+import { describe, expect, it, vi } from 'vitest';++vi.mock('../api', () => ({+ API: {+ get: vi.fn(),+ patch: vi.fn(),+ },+}));++describe('lyricsService', () => {+ it('fetchSyncedLyrics should return syncedLyrics', async () => {+ (API.get as any).mockResolvedValue({ data: { lrclib: { syncedLyrics: 'abc' } } });++ const result = await fetchSyncedLyrics(1, 'track_name=abc');+ expect(result).toEqual({ syncedLyrics: 'abc' });+ expect(API.get).toHaveBeenCalledWith('/metadata/1/lyrics/import?track_name=abc');+ });++ it('searchSyncedLyrics returns array', async () => {+ (API.get as any).mockResolvedValue({ data: { lrclib: [{ id: 1 }] } });++ const result = await searchSyncedLyrics(1);+ expect(result).toEqual([{ id: 1 }]);+ });++ it('generateLyricsSearchQuery should build correct string', () => {+ const query = generateLyricsSearchQuery({ title: 'test', album: 'a', artist: 'b' } as any, 't', 'x', 'y');+ expect(query).toBe('track_name=t&album_name=x&artist_name=y');+ });+});diff --git a/resources/js/service/api.ts b/resources/js/service/api.tsindex d921263e..315f6c15 100644--- a/resources/js/service/api.ts+++ b/resources/js/service/api.ts@@ -1,5 +1,6 @@+import { toast } from '@/service/toaster/toastService';+import axios from 'axios';-import { toast } from './toaster/toastService';const handleResponse = (response: any) => {return response;diff --git a/resources/js/service/lyricsService.ts b/resources/js/service/lyricsService.tsnew file mode 100644index 00000000..190e7331--- /dev/null+++ b/resources/js/service/lyricsService.ts@@ -0,0 +1,59 @@+import type { LyricsUpdateRequest } from '@/types/requests';+import type { LrcLibResult } from '@/types/types';+import type { Metadata } from '@/types/model';++import { API } from '@/service/api';++interface LrcLibFetchResponse {+ lrclib: LrcLibResult;+ payload: LrcLibPayload;+}++interface LrcLibSearchResponse {+ lrclib: LrcLibResult[];+ payload: LrcLibPayload;+}++interface LrcLibPayload {+ artist_name: string;+ duration: number;+ track_name: string;+}++interface LrcLibResponse<T> {+ data: T;+}++export async function fetchSyncedLyrics(metadataId: number, query?: string) {+ const { data }: LrcLibResponse<LrcLibFetchResponse> = await API.get(`/metadata/${metadataId}/lyrics/import?${query ?? ''}`);++ return data.lrclib ?? null;+}++export async function searchSyncedLyrics(metadataId: number, query?: string) {+ const { data }: LrcLibResponse<LrcLibSearchResponse> = await API.get(`/metadata/${metadataId}/lyrics/search?${query ?? ''}`);++ return data.lrclib ?? [];+}++export function updateLyrics(id: number, data: LyricsUpdateRequest) {+ return API.patch(`/metadata/${id}/lyrics`, data);+}++export const generateLyricsSearchQuery = (metadata?: Metadata, track?: string, album?: string, artist?: string): string | undefined => {+ if (!metadata) return undefined;++ const params = new URLSearchParams();++ params.set('track_name', `${track ?? metadata.title}`);++ if (album && album !== metadata.album) {+ params.set('album_name', album);+ }++ if (artist && artist !== metadata.artist) {+ params.set('artist_name', artist);+ }++ return params.toString();+};diff --git a/resources/js/service/metadataService.ts b/resources/js/service/metadataService.tsdeleted file mode 100644index 4e0dc5cf..00000000--- a/resources/js/service/metadataService.ts+++ /dev/null@@ -1,11 +0,0 @@-import { API } from '@/service/api';--export async function fetchSyncedLyrics(metadataId: number, query?: string) {- const { data } = await API.get(`/metadata/${metadataId}/lyrics/import?${query ?? ''}`);- return data.lrclib?.syncedLyrics ?? null;-}--export async function searchSyncedLyrics(metadataId: number, query?: string) {- const { data } = await API.get(`/metadata/${metadataId}/lyrics/search?${query ?? ''}`);- return data.lrclib ?? null;-}diff --git a/resources/js/stores/LyricStore.ts b/resources/js/stores/LyricStore.tsnew file mode 100644index 00000000..37bfc70e--- /dev/null+++ b/resources/js/stores/LyricStore.ts@@ -0,0 +1,132 @@+import type { VideoResource } from '@/types/resources';+import type { LrcLibResult } from '@/types/types';+import type { Metadata } from '@/types/model';+import type { Ref } from 'vue';++import { fetchSyncedLyrics, searchSyncedLyrics } from '@/service/lyricsService';+import { defineStore, storeToRefs } from 'pinia';+import { computed, ref, watch } from 'vue';+import { useContentStore } from '@/stores/ContentStore';+import { toast } from '@/service/toaster/toastService';++import useModal from '@/composables/useModal';++type SelectedLyric = (LrcLibResult & { source: 'search' | 'generated' }) | null;++export const useLyricStore = defineStore('Lyric', () => {+ const { stateVideo } = storeToRefs(useContentStore()) as unknown as { stateVideo: Ref<VideoResource, VideoResource> };++ const editLyricsModal = useModal({ title: 'Edit Song Lyrics', submitText: 'Submit Changes' });++ const searchResults = ref<LrcLibResult[]>([]); // Holds search results+ const hasSearchedForLyrics = ref<boolean>(false);+ const isLoadingLyrics = ref<boolean>(false);++ const dirtyLyric = ref<SelectedLyric>(null);+ const stateLyrics = computed(() => {+ return dirtyLyric.value?.syncedLyrics ?? stateVideo.value.metadata?.lyrics ?? ''; // Holds stateVideo.lyrics (originally) and then any modifications made by user or loaded from import / search functions+ });++ const handleSelectLyrics = (result: LrcLibResult) => {+ dirtyLyric.value = { ...result, source: 'search' };+ };++ const handlePreviewLyrics = (result: LrcLibResult) => {+ if (!result.syncedLyrics) return;+ handleSelectLyrics(result);+ editLyricsModal.toggleModal(false);+ };++ const handleOpenLyricsModal = async () => {+ try {+ validateData(stateVideo.value.metadata);+ editLyricsModal.toggleModal(true);+ } catch (error: unknown) {+ if (error instanceof Error) toast.error(error.message);+ }+ };++ const handleSearchSyncedLyrics = async (query?: string) => {+ try {+ const metadata = validateData(stateVideo.value.metadata);++ searchResults.value = [];++ const results = await runLyricsRequest(() => searchSyncedLyrics(metadata.id, query));+ searchResults.value = results as LrcLibResult[];+ hasSearchedForLyrics.value = true;+ } catch (error: unknown) {+ if (error instanceof Error) toast.error(error.message);+ }+ };++ const handleGenerateLyrics = async () => {+ try {+ const metadata = validateData(stateVideo.value.metadata);+ const result = await runLyricsRequest(() => fetchSyncedLyrics(metadata.id));++ if (!result?.syncedLyrics) {+ toast.error('Lyrics not found...', { description: 'Try searching for options from the edit menu' });+ return;+ }++ searchResults.value = [result];+ dirtyLyric.value = { ...result, source: 'generated' };+ } catch (error: unknown) {+ if (error instanceof Error) toast.error(error.message);+ }+ };++ const runLyricsRequest = async <T>(requestFn: () => Promise<T>, noResultsMessage = 'Lyrics not found...'): Promise<T | null> => {+ isLoadingLyrics.value = true;++ try {+ const results = await requestFn();++ const hasResults = results !== null && results !== undefined;+ if (!hasResults) {+ toast.error(noResultsMessage);+ return null;+ }++ return results;+ } catch (error) {+ toast.error('An error occurred while fetching lyrics.');+ console.error(error);+ return null;+ } finally {+ isLoadingLyrics.value = false;+ }+ };++ const validateData = (metadata: typeof stateVideo.value.metadata): Metadata => {+ if (!metadata) {+ toast.error('Data is malformed.');+ throw new Error('Metadata is missing');+ }+ return metadata;+ };++ const resetLyrics = () => {+ dirtyLyric.value = null;+ searchResults.value = [];+ hasSearchedForLyrics.value = false;+ };++ watch(() => stateVideo.value, resetLyrics, { immediate: true });++ return {+ dirtyLyric,+ stateLyrics,+ searchResults,+ isLoadingLyrics,+ editLyricsModal,+ hasSearchedForLyrics,+ handleSelectLyrics,+ handlePreviewLyrics,+ handleOpenLyricsModal,+ handleSearchSyncedLyrics,+ handleGenerateLyrics,+ resetLyrics,+ };+});diff --git a/resources/js/stores/__tests__/LyricStore.test.ts b/resources/js/stores/__tests__/LyricStore.test.tsnew file mode 100644index 00000000..742c6310--- /dev/null+++ b/resources/js/stores/__tests__/LyricStore.test.ts@@ -0,0 +1,50 @@+// src/stores/__tests__/useLyricStore.test.ts+import { describe, beforeEach, expect, it, vi } from 'vitest';+import { setActivePinia, createPinia } from 'pinia';+import { useContentStore } from '@/stores/ContentStore';+import { useLyricStore } from '@/stores/LyricStore';+import { faker } from '@faker-js/faker';+import { ref } from 'vue';++vi.mock('@/service/lyricsService', () => ({+ fetchSyncedLyrics: vi.fn(() => Promise.resolve({ syncedLyrics: 'some lyrics' })),+ searchSyncedLyrics: vi.fn(() => Promise.resolve([{ syncedLyrics: faker.lorem }, { syncedLyrics: faker.animal.cat() }])),+}));++describe('useLyricStore', () => {+ beforeEach(() => {+ setActivePinia(createPinia());+ });++ it('resets lyrics properly', () => {+ const store = useLyricStore();+ store.searchResults = [{ syncedLyrics: 'test' } as any];+ store.dirtyLyric = {+ id: faker.number.int({ min: 1000 }),+ name: faker.music.songName(),+ trackName: faker.music.songName(),+ artistName: faker.music.artist(),+ albumName: faker.music.album(),+ duration: faker.number.int({ min: 1, max: 500 }),+ syncedLyrics: 'abc',+ source: 'search',+ };+ store.hasSearchedForLyrics = true;++ store.resetLyrics();+ expect(store.dirtyLyric).toBe(null);+ expect(store.searchResults).toEqual([]);+ expect(store.hasSearchedForLyrics).toBe(false);+ });++ it('calls fetchSyncedLyrics and updates store', async () => {+ const contentStore = useContentStore();+ contentStore.stateVideo = ref({ metadata: { id: 1, lyrics: '' } }) as any;++ const store = useLyricStore();+ await store.handleGenerateLyrics();++ expect(store.searchResults.length).toBe(1);+ expect(store.dirtyLyric?.syncedLyrics).toBe('some lyrics');+ });+});