From 628e5f887fd2ecf6d8366d0a6e6c4635a9d0ed60 Mon Sep 17 00:00:00 2001 From: Olga Bulat Date: Fri, 8 Mar 2024 12:27:42 +0300 Subject: [PATCH] Extract useCollection composable Signed-off-by: Olga Bulat --- frontend/src/composables/use-collection.ts | 66 ++++++++++++++++++++++ frontend/src/pages/audio/collection.vue | 54 +++++------------- frontend/src/pages/image/collection.vue | 60 ++++++-------------- 3 files changed, 97 insertions(+), 83 deletions(-) create mode 100644 frontend/src/composables/use-collection.ts diff --git a/frontend/src/composables/use-collection.ts b/frontend/src/composables/use-collection.ts new file mode 100644 index 00000000000..4c832626144 --- /dev/null +++ b/frontend/src/composables/use-collection.ts @@ -0,0 +1,66 @@ +import { computed, ref } from "vue" + +import { useMediaStore } from "~/stores/media" +import { useSearchStore } from "~/stores/search" +import { useI18n } from "~/composables/use-i18n" +import type { DetailFromMediaType } from "~/types/media" +import type { SupportedMediaType } from "~/constants/media" + +export const useCollection = ({ + mediaType, +}: { + mediaType: T +}) => { + const mediaStore = useMediaStore() + const searchStore = useSearchStore() + + const collectionParams = computed(() => searchStore.collectionParams) + const isFetching = computed(() => mediaStore.fetchState.isFetching) + + const media = ref[]>([]) + const creatorUrl = ref() + + const i18n = useI18n() + + const collectionLabel = computed(() => { + if (!collectionParams.value) { + return "" + } + const { collection, ...params } = collectionParams.value + return i18n + .t(`collection.label.${collection}.image`, { ...params }) + .toString() + }) + + const fetchMedia = async ( + { shouldPersistMedia }: { shouldPersistMedia: boolean } = { + shouldPersistMedia: false, + } + ) => { + if (mediaStore._searchType !== mediaType) { + throw new Error( + `Search type is incorrectly set in the store to ${mediaStore._searchType} when it should be "${mediaType}"` + ) + } + media.value = (await mediaStore.fetchMedia({ + shouldPersistMedia, + })) as (typeof media)["value"] + creatorUrl.value = + media.value.length > 0 ? media.value[0].creator_url : undefined + } + + const handleLoadMore = async () => { + await fetchMedia({ shouldPersistMedia: true }) + } + + const results = computed(() => ({ type: mediaType, items: media.value })) + + return { + results, + creatorUrl, + fetchMedia, + handleLoadMore, + collectionLabel, + isFetching, + } +} diff --git a/frontend/src/pages/audio/collection.vue b/frontend/src/pages/audio/collection.vue index 8f3aec18ced..e5d6aed02f7 100644 --- a/frontend/src/pages/audio/collection.vue +++ b/frontend/src/pages/audio/collection.vue @@ -4,7 +4,7 @@ v-if="collectionParams" search-term="" :is-fetching="isFetching" - :results="{ type: 'audio', items: media }" + :results="results" :collection-label="collectionLabel" :collection-params="collectionParams" @load-more="handleLoadMore" @@ -14,15 +14,12 @@