Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Use the `VMediaCollection` for search and collection results (#3835)

Olga Bulatfc38553d04cd
diff --git a/frontend/src/components/VCollectionPage.vue b/frontend/src/components/VCollectionPage.vue
deleted file mode 100644
index 7467ccc34..000000000
--- a/frontend/src/components/VCollectionPage.vue
+++ /dev/null
@@ -1,110 +0,0 @@
-<template>
- <div class="p-6 pt-0 lg:p-10 lg:pt-2">
- <VCollectionHeader
- v-if="collectionParams"
- :collection-params="collectionParams"
- :creator-url="creatorUrl"
- :media-type="mediaType"
- class="mb-2 md:mb-3"
- />
- <VAudioList
- v-if="results.type === 'audio'"
- :collection-label="collectionLabel"
- :fetch-state="fetchState"
- kind="collection"
- :results="results.items"
- />
- <VImageGrid
- v-if="results.type === 'image'"
- :image-grid-label="collectionLabel"
- :fetch-state="fetchState"
- kind="collection"
- :results="results.items"
- />
- </div>
-</template>
-<script lang="ts">
-import { computed, defineComponent, PropType } from "vue"
-
-import { useMediaStore } from "~/stores/media"
-import { useSearchStore } from "~/stores/search"
-import type { SupportedMediaType } from "~/constants/media"
-
-import { Results } from "~/types/result"
-
-import { useI18n } from "~/composables/use-i18n"
-
-import VCollectionHeader from "~/components/VCollectionHeader/VCollectionHeader.vue"
-import VAudioList from "~/components/VSearchResultsGrid/VAudioList.vue"
-import VImageGrid from "~/components/VSearchResultsGrid/VImageGrid.vue"
-
-export default defineComponent({
- name: "VCollectionPage",
- components: { VAudioList, VImageGrid, VCollectionHeader },
- props: {
- mediaType: {
- type: String as PropType<SupportedMediaType>,
- required: true,
- },
- },
- setup(props) {
- const i18n = useI18n()
- const mediaStore = useMediaStore()
-
- const fetchState = computed(() => mediaStore.fetchState)
- const results = computed<Results>(() => {
- return {
- type: props.mediaType,
- items: mediaStore.resultItems[props.mediaType],
- } as Results
- })
-
- const creatorUrl = computed(() => {
- const media = results.value.items
- return media.length > 0 ? media[0].creator_url : undefined
- })
-
- const searchStore = useSearchStore()
- const collectionParams = computed(() => searchStore.collectionParams)
-
- const collectionLabel = computed(() => {
- const collection = collectionParams.value?.collection
- switch (collection) {
- case "tag": {
- return i18n
- .t(`collection.ariaLabel.tag.${props.mediaType}`, {
- tag: collectionParams.value?.tag,
- })
- .toString()
- }
- case "source": {
- return i18n
- .t(`collection.ariaLabel.source.${props.mediaType}`, {
- source: collectionParams.value?.source,
- })
- .toString()
- }
- case "creator": {
- return i18n
- .t(`collection.ariaLabel.creator.${props.mediaType}`, {
- creator: collectionParams.value?.creator,
- source: collectionParams.value?.source,
- })
- .toString()
- }
- default: {
- return ""
- }
- }
- })
-
- return {
- fetchState,
- results,
- creatorUrl,
- collectionParams,
- collectionLabel,
- }
- },
-})
-</script>
diff --git a/frontend/src/components/VLoadMore.vue b/frontend/src/components/VLoadMore.vue
index 2d1751213..cdf8453af 100644
--- a/frontend/src/components/VLoadMore.vue
+++ b/frontend/src/components/VLoadMore.vue
@@ -5,7 +5,7 @@
class="label-bold lg:description-bold h-16 w-full lg:h-18"
variant="filled-gray"
size="disabled"
- :disabled="fetchState.isFetching"
+ :disabled="isFetching"
data-testid="load-more"
@click="onLoadMore"
>
@@ -14,16 +14,25 @@
</div>
</template>
<script lang="ts">
-import { computed, defineComponent, onMounted, ref, watch } from "vue"
+import {
+ computed,
+ defineComponent,
+ onMounted,
+ type PropType,
+ ref,
+ watch,
+} from "vue"
import { storeToRefs } from "pinia"
import { useElementVisibility } from "@vueuse/core"
-import { useRoute } from "@nuxtjs/composition-api"
+import { useContext, useRoute } from "@nuxtjs/composition-api"
-import { useAnalytics } from "~/composables/use-analytics"
import { useMediaStore } from "~/stores/media"
-import { useSearchStore } from "~/stores/search"
import { useI18n } from "~/composables/use-i18n"
+import { defineEvent } from "~/types/emits"
+
+import type { ResultKind } from "~/types/result"
+import type { SupportedSearchType } from "~/constants/media"
import VButton from "~/components/VButton.vue"
@@ -32,64 +41,70 @@ export default defineComponent({
components: {
VButton,
},
- setup() {
+ props: {
+ searchType: {
+ type: String as PropType<SupportedSearchType>,
+ required: true,
+ },
+ searchTerm: {
+ type: String,
+ required: true,
+ },
+ kind: {
+ type: String as PropType<ResultKind>,
+ required: true,
+ },
+ isFetching: {
+ type: Boolean,
+ required: true,
+ },
+ },
+ emits: {
+ "load-more": defineEvent(),
+ },
+ setup(props, { emit }) {
const loadMoreSectionRef = ref(null)
const route = useRoute()
const i18n = useI18n()
const mediaStore = useMediaStore()
- const searchStore = useSearchStore()
- const { sendCustomEvent } = useAnalytics()
-
- // Use the `_searchType` from mediaStore because it falls back to ALL_MEDIA
- // for unsupported search types.
- const { fetchState, resultCount, currentPage, _searchType } =
- storeToRefs(mediaStore)
- const { searchTerm } = storeToRefs(searchStore)
-
- const searchStarted = computed(() => {
- return searchStore.strategy === "default"
- ? searchTerm.value !== ""
- : searchStore.collectionParams !== null
+ const { $sendCustomEvent } = useContext()
+
+ const { currentPage } = storeToRefs(mediaStore)
+
+ const eventPayload = computed(() => {
+ return {
+ searchType: props.searchType,
+ query: props.searchTerm,
+ resultPage: currentPage.value || 1,
+ }
})
/**
* Whether we should show the "Load more" button.
- * If the user has entered a search term, there is at least 1 page of results,
- * there has been no fetching error, and there are more results to fetch,
- * we show the button.
+ * If the fetching for the current query has started, there is at least
+ * 1 page of results, there has been no fetching error, and there are
+ * more results to fetch, we show the button.
*/
- const canLoadMore = computed(() => {
- return Boolean(
- searchStarted.value &&
- !fetchState.value.fetchingError &&
- !fetchState.value.isFinished &&
- resultCount.value > 0
- )
- })
+ const canLoadMore = computed(() => mediaStore.canLoadMore)
const reachResultEndEventSent = ref(false)
/**
- * On button click, fetch media, persisting the existing results.
+ * On button click, send the analytics events and emit `load-more` event.
+ *
* The button is disabled when we are fetching, but we still check
* whether we are currently fetching to be sure we don't fetch multiple times.
*
*/
const onLoadMore = async () => {
- if (fetchState.value.isFetching) {
+ if (props.isFetching) {
return
}
reachResultEndEventSent.value = false
- sendCustomEvent("LOAD_MORE_RESULTS", {
- query: searchStore.searchTerm,
- searchType: searchStore.searchType,
- resultPage: currentPage.value || 1,
- })
+ $sendCustomEvent("LOAD_MORE_RESULTS", eventPayload.value)
- await mediaStore.fetchMedia({
- shouldPersistMedia: true,
- })
+ emit("load-more")
}
const sendReachResultEnd = () => {
@@ -97,15 +112,11 @@ export default defineComponent({
// currentPage is updated from 0, so we use the value or 1.
// The currentPage can never be 0 here because then the loadMore
// button would not be visible.
- sendCustomEvent("REACH_RESULT_END", {
- searchType: _searchType.value,
- query: searchTerm.value,
- resultPage: currentPage.value || 1,
- })
+ $sendCustomEvent("REACH_RESULT_END", eventPayload.value)
}
const buttonLabel = computed(() =>
- fetchState.value.isFetching
+ props.isFetching
? i18n.t("browsePage.loading")
: i18n.t("browsePage.load")
)
@@ -136,7 +147,6 @@ export default defineComponent({
return {
buttonLabel,
- fetchState,
onLoadMore,
canLoadMore,
diff --git a/frontend/src/components/VSearchResultsGrid/VAllResultsGrid.vue b/frontend/src/components/VSearchResultsGrid/VAllResultsGrid.vue
index 23f0caf8e..b4485f86f 100644
--- a/frontend/src/components/VSearchResultsGrid/VAllResultsGrid.vue
+++ b/frontend/src/components/VSearchResultsGrid/VAllResultsGrid.vue
@@ -1,42 +1,16 @@
<template>
<div>
- <div
- v-if="!noResults"
- class="results-grid mb-4 mt-2 grid grid-cols-2 gap-4 md:mt-0"
- >
- <VContentLink
- v-for="[mediaType, count] in resultCounts"
- :key="mediaType"
- :media-type="mediaType"
- :search-term="searchTerm"
- :results-count="count"
- :to="contentLinkPath(mediaType)"
- />
- </div>
- <VSnackbar size="large" :is-visible="isSnackbarVisible">
- <i18n path="allResults.snackbar.text" tag="p">
- <template #spacebar>
- <kbd class="font-sans">{{ $t(`allResults.snackbar.spacebar`) }}</kbd>
- </template>
- </i18n>
- </VSnackbar>
- <VGridSkeleton
- v-if="resultsLoading && allMedia.length === 0"
- is-for-tab="all"
- />
+ <VAudioInstructions kind="all" />
<ol
- v-else
- class="results-grid grid grid-cols-2 gap-4"
+ class="grid grid-cols-2 gap-4"
:class="
isSidebarVisible
? 'lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5'
: 'sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6'
"
- :aria-label="
- $t('browsePage.aria.results', { query: searchTerm }).toString()
- "
+ :aria-label="collectionLabel"
>
- <template v-for="item in allMedia">
+ <template v-for="item in results">
<VImageCell
v-if="isDetail.image(item)"
:key="item.id"
@@ -55,99 +29,50 @@
/>
</template>
</ol>
-
- <VLoadMore class="mb-6 mt-4 lg:mb-10" />
</div>
</template>
<script lang="ts">
-import { computed, defineComponent } from "vue"
+import { computed, defineComponent, type PropType } from "vue"
import { storeToRefs } from "pinia"
-import { useMediaStore } from "~/stores/media"
-import { useSearchStore } from "~/stores/search"
import { useUiStore } from "~/stores/ui"
-import { isDetail } from "~/types/media"
-
-import { useI18n } from "~/composables/use-i18n"
-
-import type { SupportedMediaType } from "~/constants/media"
+import { type AudioDetail, type ImageDetail, isDetail } from "~/types/media"
-import VSnackbar from "~/components/VSnackbar.vue"
import VImageCell from "~/components/VImageCell/VImageCell.vue"
import VAudioResult from "~/components/VSearchResultsGrid/VAudioResult.vue"
-import VLoadMore from "~/components/VLoadMore.vue"
-import VContentLink from "~/components/VContentLink/VContentLink.vue"
-import VGridSkeleton from "~/components/VSkeleton/VGridSkeleton.vue"
+import VAudioInstructions from "~/components/VSearchResultsGrid/VAudioInstructions.vue"
export default defineComponent({
name: "VAllResultsGrid",
components: {
- VSnackbar,
VImageCell,
VAudioResult,
- VLoadMore,
- VGridSkeleton,
- VContentLink,
+ VAudioInstructions,
+ },
+ props: {
+ searchTerm: {
+ type: String,
+ required: true,
+ },
+ results: {
+ type: Array as PropType<(AudioDetail | ImageDetail)[]>,
+ required: true,
+ },
+ collectionLabel: {
+ type: String,
+ required: true,
+ },
},
setup() {
- const i18n = useI18n()
- const mediaStore = useMediaStore()
- const searchStore = useSearchStore()
-
- const searchTerm = computed(() => searchStore.searchTerm)
-
- const resultsLoading = computed(() => {
- return (
- Boolean(mediaStore.fetchState.fetchingError) ||
- mediaStore.fetchState.isFetching ||
- !mediaStore.fetchState.hasStarted
- )
- })
-
- const contentLinkPath = (mediaType: SupportedMediaType) =>
- searchStore.getSearchPath({ type: mediaType })
-
- const allMedia = computed(() => mediaStore.allMedia)
-
- const isError = computed(() => !!mediaStore.fetchState.fetchingError)
-
- const fetchState = computed(() => mediaStore.fetchState)
-
- const errorHeader = computed(() => {
- const type = i18n.t("browsePage.searchForm.audio")
- return i18n.t("browsePage.fetchingError", { type })
- })
-
- const resultCounts = computed(() => mediaStore.resultCountsPerMediaType)
-
- const noResults = computed(
- () => fetchState.value.isFinished && allMedia.value.length === 0
- )
-
const uiStore = useUiStore()
- const {
- areInstructionsVisible: isSnackbarVisible,
- isFilterVisible: isSidebarVisible,
- } = storeToRefs(uiStore)
+ const { isFilterVisible: isSidebarVisible } = storeToRefs(uiStore)
const isSm = computed(() => uiStore.isBreakpoint("sm"))
return {
- searchTerm,
- isError,
- errorHeader,
- allMedia,
- fetchState,
- resultsLoading,
- resultCounts,
- noResults,
-
- contentLinkPath,
-
isSidebarVisible,
- isSnackbarVisible,
isSm,
isDetail,
diff --git a/frontend/src/components/VSearchResultsGrid/VAudioList.vue b/frontend/src/components/VSearchResultsGrid/VAudioList.vue
deleted file mode 100644
index fb116ecb4..000000000
--- a/frontend/src/components/VSearchResultsGrid/VAudioList.vue
+++ /dev/null
@@ -1,121 +0,0 @@
-<template>
- <section>
- <VGridSkeleton
- v-if="results && results.length === 0 && !fetchState.isFinished"
- is-for-tab="audio"
- />
- <VSnackbar size="large" :is-visible="isSnackbarVisible">
- <i18n path="audioResults.snackbar.text" tag="p">
- <template
- v-for="keyboardKey in ['spacebar', 'left', 'right']"
- #[keyboardKey]
- >
- <kbd :key="keyboardKey" class="font-sans">{{
- $t(`audioResults.snackbar.${keyboardKey}`)
- }}</kbd>
- </template>
- </i18n>
- </VSnackbar>
- <!-- Negative margin compensates for the `p-4` padding in row layout. -->
- <ol
- :aria-label="collectionLabel"
- class="-mx-2 flex flex-col md:-mx-4"
- :class="kind === 'related' ? 'gap-4' : 'gap-2 md:gap-1'"
- >
- <VAudioResult
- v-for="audio in results"
- :key="audio.id"
- :search-term="searchTerm"
- :audio="audio"
- layout="row"
- :size="audioTrackSize"
- :kind="kind"
- />
- </ol>
- <footer v-if="kind !== 'related'" class="mt-4">
- <VLoadMore />
- </footer>
- </section>
-</template>
-
-<script lang="ts">
-import { computed, defineComponent, PropType } from "vue"
-
-import type { AudioDetail } from "~/types/media"
-import type { FetchState } from "~/types/fetch-state"
-import type { ResultKind } from "~/types/result"
-import { useAudioSnackbar } from "~/composables/use-audio-snackbar"
-
-import { useSearchStore } from "~/stores/search"
-
-import { useUiStore } from "~/stores/ui"
-
-import VLoadMore from "~/components/VLoadMore.vue"
-import VGridSkeleton from "~/components/VSkeleton/VGridSkeleton.vue"
-import VSnackbar from "~/components/VSnackbar.vue"
-import VAudioResult from "~/components/VSearchResultsGrid/VAudioResult.vue"
-
-/**
- * This component shows a loading skeleton if the results are not yet loaded,
- * and then shows the list of audio, with the Load more button if needed.
- */
-export default defineComponent({
- name: "VAudioList",
- components: {
- VAudioResult,
- VSnackbar,
- VGridSkeleton,
- VLoadMore,
- },
- props: {
- results: {
- type: Array as PropType<AudioDetail[]>,
- default: () => [],
- },
- /**
- * If used for Related audio, do not show the Load more button.
- */
- kind: {
- type: String as PropType<ResultKind>,
- required: true,
- },
- fetchState: {
- type: Object as PropType<FetchState>,
- required: true,
- },
- /**
- * The label used for the list of audio for accessibility.
- */
- collectionLabel: {
- type: String,
- required: true,
- },
- },
- setup(props) {
- const { isVisible: isSnackbarVisible } = useAudioSnackbar()
-
- const uiStore = useUiStore()
-
- const audioTrackSize = computed(() => {
- if (props.kind === "related") {
- return uiStore.isBreakpoint("sm") ? "m" : "s"
- } else {
- return !uiStore.isBreakpoint("sm")
- ? "s"
- : uiStore.isBreakpoint("xl")
- ? "l"
- : "m"
- }
- })
-
- const searchStore = useSearchStore()
- const searchTerm = computed(() => searchStore.searchTerm)
-
- return {
- audioTrackSize,
- searchTerm,
- isSnackbarVisible,
- }
- },
-})
-</script>
diff --git a/frontend/src/components/VSearchResultsGrid/VCollectionResults.vue b/frontend/src/components/VSearchResultsGrid/VCollectionResults.vue
new file mode 100644
index 000000000..40b66f70f
--- /dev/null
+++ b/frontend/src/components/VSearchResultsGrid/VCollectionResults.vue
@@ -0,0 +1,76 @@
+<template>
+ <VMediaCollection
+ :results="results"
+ :is-fetching="isFetching"
+ :search-term="searchTerm"
+ :collection-label="collectionLabel"
+ kind="collection"
+ >
+ <template #header>
+ <VCollectionHeader
+ v-if="isSupportedMediaType(results.type)"
+ class="mb-2 md:mb-3"
+ :media-type="results.type"
+ :collection-params="collectionParams"
+ />
+ </template>
+
+ <template #footer>
+ <footer class="mb-6 mt-4 lg:mb-10">
+ <VLoadMore
+ :search-type="results.type"
+ kind="collection"
+ :search-term="searchTerm"
+ :is-fetching="isFetching"
+ class="mb-4"
+ @load-more="$emit('load-more')"
+ />
+ </footer>
+ </template>
+ </VMediaCollection>
+</template>
+<script lang="ts">
+import { defineComponent, type PropType } from "vue"
+
+import { isSupportedMediaType } from "~/constants/media"
+
+import type { CollectionParams } from "~/types/search"
+import type { Results } from "~/types/result"
+
+import { defineEvent } from "~/types/emits"
+
+import VCollectionHeader from "~/components/VCollectionHeader/VCollectionHeader.vue"
+import VMediaCollection from "~/components/VSearchResultsGrid/VMediaCollection.vue"
+import VLoadMore from "~/components/VLoadMore.vue"
+
+export default defineComponent({
+ name: "VCollectionResults",
+ components: { VLoadMore, VMediaCollection, VCollectionHeader },
+ props: {
+ collectionParams: {
+ type: Object as PropType<CollectionParams>,
+ required: true,
+ },
+ collectionLabel: {
+ type: String,
+ required: true,
+ },
+ results: {
+ type: Object as PropType<Results>,
+ required: true,
+ },
+ isFetching: {
+ type: Boolean,
+ required: true,
+ },
+ searchTerm: {
+ type: String,
+ required: true,
+ },
+ },
+ emits: {
+ "load-more": defineEvent(),
+ },
+ methods: { isSupportedMediaType },
+})
+</script>
diff --git a/frontend/src/components/VSearchResultsGrid/VImageGrid.vue b/frontend/src/components/VSearchResultsGrid/VImageGrid.vue
deleted file mode 100644
index bd17866eb..000000000
--- a/frontend/src/components/VSearchResultsGrid/VImageGrid.vue
+++ /dev/null
@@ -1,99 +0,0 @@
-<template>
- <section>
- <VGridSkeleton
- v-if="results && !results.length && !fetchState.isFinished"
- is-for-tab="image"
- />
- <ol class="image-grid flex flex-wrap gap-4" :aria-label="imageGridLabel">
- <VImageCell
- v-for="image in results"
- :key="image.id"
- :image="image"
- :search-term="searchTerm"
- aspect-ratio="intrinsic"
- :kind="kind"
- :related-to="relatedTo"
- />
- </ol>
- <footer v-if="kind !== 'related'" class="pt-4">
- <VLoadMore />
- </footer>
- </section>
-</template>
-
-<script lang="ts">
-/**
- * This component receives an array of images as a prop, and
- * is responsible for displaying them as a grid.
- * It can also fetch more images when 'Load More' is clicked.
- * Used to display both image search results, and related images.
- */
-import { computed, defineComponent, PropType } from "vue"
-
-import { useSearchStore } from "~/stores/search"
-import { useRelatedMediaStore } from "~/stores/media/related-media"
-
-import type { FetchState } from "~/types/fetch-state"
-import type { ImageDetail } from "~/types/media"
-import type { ResultKind } from "~/types/result"
-
-import VGridSkeleton from "~/components/VSkeleton/VGridSkeleton.vue"
-import VLoadMore from "~/components/VLoadMore.vue"
-import VImageCell from "~/components/VImageCell/VImageCell.vue"
-
-export default defineComponent({
- name: "ImageGrid",
- components: { VGridSkeleton, VLoadMore, VImageCell },
- props: {
- results: {
- type: Array as PropType<ImageDetail[]>,
- default: () => [],
- },
- /**
- * `VImageGrid` is used for the image search results, related images,
- * and the image collection page.
- * The load more button is not shown for related images.
- */
- kind: {
- type: String as PropType<ResultKind>,
- default: "search",
- },
- fetchState: {
- type: Object as PropType<FetchState>,
- required: true,
- },
- imageGridLabel: {
- type: String,
- required: true,
- },
- },
- setup(props) {
- const searchStore = useSearchStore()
-
- const searchTerm = computed(() => searchStore.searchTerm)
-
- const relatedTo = computed(() => {
- return props.kind === "related"
- ? useRelatedMediaStore().mainMediaId
- : null
- })
-
- return { searchTerm, relatedTo }
- },
-})
-</script>
-
-<style scoped>
-@screen md {
- .image-grid:after {
- /**
- * This keeps the last item in the results from expanding to fill
- * all available space, which can result in a final row with a
- * single, 100% wide image.
- */
-
- content: "";
- flex-grow: 999999999;
- }
-}
-</style>
diff --git a/frontend/src/components/VSearchResultsGrid/VMediaCollection.vue b/frontend/src/components/VSearchResultsGrid/VMediaCollection.vue
index 062e1639a..23bfda46e 100644
--- a/frontend/src/components/VSearchResultsGrid/VMediaCollection.vue
+++ b/frontend/src/components/VSearchResultsGrid/VMediaCollection.vue
@@ -15,7 +15,7 @@
:class="{ 'pt-2 sm:pt-0': results.type === 'image' }"
/>
- <slot name="footer" v-bind="{ isFetching }" />
+ <slot name="footer" />
<VScrollButton
v-show="showScrollButton"
@@ -27,9 +27,8 @@
<script lang="ts">
import { computed, defineComponent, inject, type PropType, ref } from "vue"
-import { IsSidebarVisibleKey, ShowScrollButtonKey } from "~/types/provides"
import type { Results } from "~/types/result"
-
+import { IsSidebarVisibleKey, ShowScrollButtonKey } from "~/types/provides"
import { defineEvent } from "~/types/emits"
import VGridSkeleton from "~/components/VSkeleton/VGridSkeleton.vue"
@@ -68,6 +67,10 @@ export default defineComponent({
type: String as PropType<string | null>,
default: null,
},
+ /**
+ * Overrides the value from the media store.
+ * Used for the related media which uses a different store.
+ */
isFetching: {
type: Boolean,
required: true,
diff --git a/frontend/src/components/VSearchResultsGrid/VSearchResults.vue b/frontend/src/components/VSearchResultsGrid/VSearchResults.vue
new file mode 100644
index 000000000..1205d2f16
--- /dev/null
+++ b/frontend/src/components/VSearchResultsGrid/VSearchResults.vue
@@ -0,0 +1,117 @@
+<template>
+ <VMediaCollection
+ :collection-label="collectionLabel"
+ :results="results"
+ :is-fetching="isFetching"
+ :search-term="searchTerm"
+ kind="search"
+ >
+ <template #header>
+ <header v-if="searchTerm" class="my-0 md:mb-8 md:mt-4">
+ <VSearchResultsTitle
+ :size="results.type === 'all' ? 'large' : 'default'"
+ >{{ searchTerm }}</VSearchResultsTitle
+ >
+ </header>
+
+ <div
+ v-if="results.type === 'all'"
+ class="mb-4 mt-2 grid grid-cols-2 gap-4 md:mt-0"
+ >
+ <VContentLink
+ v-for="[mediaType, count] in resultCounts"
+ :key="mediaType"
+ :media-type="mediaType"
+ :search-term="searchTerm"
+ :results-count="count"
+ :to="contentLinkPath(mediaType)"
+ />
+ </div>
+ </template>
+ <template #footer>
+ <footer class="mb-6 mt-4 lg:mb-10">
+ <VLoadMore
+ :search-type="results.type"
+ kind="search"
+ :search-term="searchTerm"
+ :is-fetching="isFetching"
+ class="mb-4"
+ @load-more="$emit('load-more')"
+ />
+ <VExternalSearchForm
+ v-if="results.type !== 'all'"
+ :search-term="searchTerm"
+ :is-supported="true"
+ :has-no-results="false"
+ />
+ </footer>
+ </template>
+ </VMediaCollection>
+</template>
+<script lang="ts">
+import { computed, defineComponent, PropType } from "vue"
+
+import { useI18n } from "~/composables/use-i18n"
+
+import { useMediaStore } from "~/stores/media"
+import { useSearchStore } from "~/stores/search"
+import { defineEvent } from "~/types/emits"
+
+import type { SupportedMediaType } from "~/constants/media"
+import type { Results } from "~/types/result"
+
+import VSearchResultsTitle from "~/components/VSearchResultsTitle.vue"
+import VMediaCollection from "~/components/VSearchResultsGrid/VMediaCollection.vue"
+import VLoadMore from "~/components/VLoadMore.vue"
+import VExternalSearchForm from "~/components/VExternalSearch/VExternalSearchForm.vue"
+import VContentLink from "~/components/VContentLink/VContentLink.vue"
+
+export default defineComponent({
+ name: "VSearchResults",
+ components: {
+ VContentLink,
+ VExternalSearchForm,
+ VLoadMore,
+ VMediaCollection,
+ VSearchResultsTitle,
+ },
+ props: {
+ searchTerm: {
+ type: String as PropType<string>,
+ required: true,
+ },
+ results: {
+ type: Object as PropType<Results>,
+ required: true,
+ },
+ isFetching: {
+ type: Boolean,
+ required: true,
+ },
+ },
+ emits: {
+ "load-more": defineEvent(),
+ },
+ setup(props) {
+ const i18n = useI18n()
+ const mediaStore = useMediaStore()
+ const searchStore = useSearchStore()
+
+ const collectionLabel = computed(() => {
+ return i18n
+ .t("browsePage.aria.results", { query: props.searchTerm })
+ .toString()
+ })
+ const contentLinkPath = (mediaType: SupportedMediaType) =>
+ searchStore.getSearchPath({ type: mediaType })
+
+ const resultCounts = computed(() => mediaStore.resultCountsPerMediaType)
+
+ return {
+ collectionLabel,
+ contentLinkPath,
+ resultCounts,
+ }
+ },
+})
+</script>
diff --git a/frontend/src/components/meta/CustomButtonComponents.stories.mdx b/frontend/src/components/meta/CustomButtonComponents.stories.mdx
index 81933fafb..d93effa84 100644
--- a/frontend/src/components/meta/CustomButtonComponents.stories.mdx
+++ b/frontend/src/components/meta/CustomButtonComponents.stories.mdx
@@ -6,7 +6,6 @@ import {
Story,
} from "@storybook/addon-docs"
import VLoadMore from "~/components/VLoadMore.vue"
-import { useSearchStore } from "~/stores/search"
import { useMediaStore } from "~/stores/media"
<Meta title="Components/CustomButtonComponents" />
@@ -17,9 +16,8 @@ export const Template = (args) => ({
`,
components: { VLoadMore },
setup() {
- const searchStore = useSearchStore()
- searchStore.setSearchTerm("cat")
const mediaStore = useMediaStore()
+ mediaStore._startFetching("image")
mediaStore.results.image.count = 1
return { args }
},
@@ -37,6 +35,12 @@ export const Template = (args) => ({
parameters={{
viewport: { defaultViewport: "sm" },
}}
+ args={{
+ kind: "search",
+ searchType: "image",
+ searchTerm: "cat",
+ isFetching: false,
+ }}
>
{Template.bind({})}
</Story>
diff --git a/frontend/src/composables/use-search-type.ts b/frontend/src/composables/use-search-type.ts
index 970b888a0..4e0d4f218 100644
--- a/frontend/src/composables/use-search-type.ts
+++ b/frontend/src/composables/use-search-type.ts
@@ -11,7 +11,6 @@ import {
SearchType,
} from "~/constants/media"
-import { useMediaStore } from "~/stores/media"
import { useSearchStore } from "~/stores/search"
import { useFeatureFlagStore } from "~/stores/feature-flag"
@@ -65,8 +64,14 @@ export default function useSearchType() {
next: searchType,
component: componentName,
})
+
+ // `setActiveType` is called after the search middleware
+ // ran and updated the search store state
+ // TODO: Figure out why
+ if (activeType.value === searchType) {
+ return
+ }
useSearchStore().setSearchType(searchType)
- useMediaStore().clearMedia()
previousSearchType.value = searchType
}
diff --git a/frontend/src/middleware/search.ts b/frontend/src/middleware/search.ts
index ba337051e..4a100a678 100644
--- a/frontend/src/middleware/search.ts
+++ b/frontend/src/middleware/search.ts
@@ -47,7 +47,7 @@ export const searchMiddleware: Middleware = async ({
const results = await mediaStore.fetchMedia()
const fetchingError = mediaStore.fetchState.fetchingError
- if (!results && fetchingError && !handledClientSide(fetchingError)) {
+ if (!results.length && fetchingError && !handledClientSide(fetchingError)) {
nuxtError(fetchingError)
}
}
diff --git a/frontend/src/pages/audio/collection.vue b/frontend/src/pages/audio/collection.vue
index 973d89cd6..5c26b87bc 100644
--- a/frontend/src/pages/audio/collection.vue
+++ b/frontend/src/pages/audio/collection.vue
@@ -1,27 +1,100 @@
<template>
- <VCollectionPage media-type="audio" />
+ <div class="p-6 pt-0 lg:p-10 lg:pt-2">
+ <VCollectionResults
+ v-if="collectionParams"
+ search-term=""
+ :is-fetching="isFetching"
+ :results="{ type: 'audio', items: media }"
+ :collection-label="collectionLabel"
+ :collection-params="collectionParams"
+ @load-more="loadMore"
+ />
+ </div>
</template>
<script lang="ts">
-import { defineComponent, useFetch } from "@nuxtjs/composition-api"
+import {
+ defineComponent,
+ useFetch,
+ useMeta,
+ useRoute,
+} from "@nuxtjs/composition-api"
+import { computed, ref, watch } from "vue"
-import { useMediaStore } from "~/stores/media"
import { collectionMiddleware } from "~/middleware/collection"
+import { useSearchStore } from "~/stores/search"
+
+import { useMediaStore } from "~/stores/media"
+import type { AudioDetail } from "~/types/media"
+import { useI18n } from "~/composables/use-i18n"
-import VCollectionPage from "~/components/VCollectionPage.vue"
+import VCollectionResults from "~/components/VSearchResultsGrid/VCollectionResults.vue"
export default defineComponent({
name: "VAudioCollectionPage",
- components: { VCollectionPage },
+ components: { VCollectionResults },
layout: "content-layout",
middleware: collectionMiddleware,
setup() {
const mediaStore = useMediaStore()
+ const searchStore = useSearchStore()
+
+ const collectionParams = computed(() => searchStore.collectionParams)
+ const isFetching = computed(() => mediaStore.fetchState.isFetching)
+
+ const media = ref<AudioDetail[]>([])
+ const creatorUrl = ref<string>()
+
+ const i18n = useI18n()
+
+ const collectionLabel = computed(() => {
+ if (!collectionParams.value) {
+ return ""
+ }
+ const { collection, ...params } = collectionParams.value
+ return i18n
+ .t(`collection.ariaLabel.${collection}.audio`, { ...params })
+ .toString()
+ })
+
+ const fetchMedia = async (
+ { shouldPersistMedia }: { shouldPersistMedia: boolean } = {
+ shouldPersistMedia: false,
+ }
+ ) => {
+ media.value = (await mediaStore.fetchMedia({
+ shouldPersistMedia,
+ })) as (typeof media)["value"]
+ creatorUrl.value =
+ media.value.length > 0 ? media.value[0].creator_url : undefined
+ }
+ const loadMore = () => {
+ fetchMedia({ shouldPersistMedia: true })
+ }
+
+ useMeta({
+ meta: [{ hid: "robots", name: "robots", content: "all" }],
+ })
useFetch(async () => {
- await mediaStore.fetchMedia()
+ await fetchMedia()
})
- return {}
+
+ // Fetch media when the route changes, e.g. when the user navigates from
+ // a creator collection page to a source collection page.
+ const route = useRoute()
+ watch(route, () => {
+ fetchMedia()
+ })
+
+ return {
+ collectionParams,
+ isFetching,
+ media,
+ collectionLabel,
+ loadMore,
+ }
},
+ head: {},
})
</script>
diff --git a/frontend/src/pages/image/collection.vue b/frontend/src/pages/image/collection.vue
index bf4028df6..dc58c0584 100644
--- a/frontend/src/pages/image/collection.vue
+++ b/frontend/src/pages/image/collection.vue
@@ -1,27 +1,100 @@
<template>
- <VCollectionPage media-type="image" />
+ <div class="p-6 pt-0 lg:p-10 lg:pt-2">
+ <VCollectionResults
+ v-if="collectionParams"
+ search-term=""
+ :is-fetching="isFetching"
+ :results="{ type: 'image', items: media }"
+ :collection-label="collectionLabel"
+ :collection-params="collectionParams"
+ @load-more="loadMore"
+ />
+ </div>
</template>
<script lang="ts">
-import { defineComponent, useFetch } from "@nuxtjs/composition-api"
+import {
+ defineComponent,
+ useFetch,
+ useMeta,
+ useRoute,
+} from "@nuxtjs/composition-api"
+import { computed, ref, watch } from "vue"
-import { useMediaStore } from "~/stores/media"
import { collectionMiddleware } from "~/middleware/collection"
+import { useMediaStore } from "~/stores/media"
+import { useSearchStore } from "~/stores/search"
+import type { ImageDetail } from "~/types/media"
+import { useI18n } from "~/composables/use-i18n"
-import VCollectionPage from "~/components/VCollectionPage.vue"
+import VCollectionResults from "~/components/VSearchResultsGrid/VCollectionResults.vue"
export default defineComponent({
name: "VImageCollectionPage",
- components: { VCollectionPage },
+ components: { VCollectionResults },
layout: "content-layout",
middleware: collectionMiddleware,
setup() {
const mediaStore = useMediaStore()
+ const searchStore = useSearchStore()
+
+ const collectionParams = computed(() => searchStore.collectionParams)
+ const isFetching = computed(() => mediaStore.fetchState.isFetching)
+
+ const media = ref<ImageDetail[]>([])
+ const creatorUrl = ref<string>()
+
+ const i18n = useI18n()
+
+ const collectionLabel = computed(() => {
+ if (!collectionParams.value) {
+ return ""
+ }
+ const { collection, ...params } = collectionParams.value
+ return i18n
+ .t(`collection.ariaLabel.${collection}.image`, { ...params })
+ .toString()
+ })
+
+ const fetchMedia = async (
+ { shouldPersistMedia }: { shouldPersistMedia: boolean } = {
+ shouldPersistMedia: false,
+ }
+ ) => {
+ media.value = (await mediaStore.fetchMedia({
+ shouldPersistMedia,
+ })) as (typeof media)["value"]
+ creatorUrl.value =
+ media.value.length > 0 ? media.value[0].creator_url : undefined
+ }
+ const loadMore = () => {
+ fetchMedia({ shouldPersistMedia: true })
+ }
+
+ useMeta({
+ meta: [{ hid: "robots", name: "robots", content: "all" }],
+ })
useFetch(async () => {
- await mediaStore.fetchMedia()
+ await fetchMedia()
})
- return {}
+
+ // Fetch media when the route changes, e.g. when the user navigates from
+ // a creator collection page to a source collection page.
+ const route = useRoute()
+ watch(route, () => {
+ fetchMedia()
+ })
+
+ return {
+ collectionParams,
+ isFetching,
+ creatorUrl,
+ collectionLabel,
+ loadMore,
+ media,
+ }
},
+ head: {},
})
</script>
diff --git a/frontend/src/pages/search.vue b/frontend/src/pages/search.vue
index b95cb25f8..29134ae2e 100644
--- a/frontend/src/pages/search.vue
+++ b/frontend/src/pages/search.vue
@@ -10,39 +10,22 @@
class="w-full py-10"
/>
<section v-else>
- <header v-if="query.q && supported" class="my-0 md:mb-8 md:mt-4">
- <VSearchResultsTitle :size="isAllView ? 'large' : 'default'">{{
- searchTerm
- }}</VSearchResultsTitle>
- </header>
<NuxtChild
:key="$route.path"
- :results="
- isSupportedMediaType(searchType) ? resultItems[searchType] : null
- "
- :fetch-state="fetchState"
- :search-term="query.q"
+ :results="searchResults"
+ :is-fetching="isFetching"
+ :search-term="searchTerm"
:supported="supported"
+ :handle-load-more="handleLoadMore"
data-testid="search-results"
/>
- <VExternalSearchForm
- v-if="!isAllView"
- :search-term="searchTerm"
- :is-supported="supported"
- :has-no-results="false"
- />
- <VScrollButton
- v-show="showScrollButton"
- :is-filter-sidebar-visible="isSidebarVisible"
- data-testid="scroll-button"
- />
</section>
</div>
</template>
<script lang="ts">
import { isShallowEqualObjects } from "@wordpress/is-shallow-equal"
-import { computed, inject, ref, watch } from "vue"
+import { computed, ref, watch } from "vue"
import { watchDebounced } from "@vueuse/core"
import { storeToRefs } from "pinia"
import {
@@ -57,33 +40,25 @@ import {
import { searchMiddleware } from "~/middleware/search"
import { useFeatureFlagStore } from "~/stores/feature-flag"
import { useMediaStore } from "~/stores/media"
-import { useSearchStore } from "~/stores/search"
-import { ALL_MEDIA, isSupportedMediaType } from "~/constants/media"
+import { isSearchTypeSupported, useSearchStore } from "~/stores/search"
+import { ALL_MEDIA } from "~/constants/media"
import { skipToContentTargetId } from "~/constants/window"
-import { IsSidebarVisibleKey, ShowScrollButtonKey } from "~/types/provides"
+import type { Results } from "~/types/result"
import { areQueriesEqual } from "~/utils/search-query-transform"
import { handledClientSide, isRetriable } from "~/utils/errors"
import VErrorSection from "~/components/VErrorSection/VErrorSection.vue"
-import VScrollButton from "~/components/VScrollButton.vue"
-import VExternalSearchForm from "~/components/VExternalSearch/VExternalSearchForm.vue"
-import VSearchResultsTitle from "~/components/VSearchResultsTitle.vue"
export default defineComponent({
name: "BrowsePage",
components: {
VErrorSection,
- VSearchResultsTitle,
- VExternalSearchForm,
- VScrollButton,
},
layout: "search-layout",
middleware: searchMiddleware,
fetchOnServer: false,
setup() {
- const showScrollButton = inject(ShowScrollButtonKey)
- const isSidebarVisible = inject(IsSidebarVisibleKey)
const featureFlagStore = useFeatureFlagStore()
const mediaStore = useMediaStore()
const searchStore = useSearchStore()
@@ -105,9 +80,7 @@ export default defineComponent({
searchTypeIsSupported: supported,
} = storeToRefs(searchStore)
- const { resultCount, fetchState, resultItems } = storeToRefs(mediaStore)
-
- const isAllView = computed(() => searchType.value === ALL_MEDIA)
+ const { resultCount, fetchState } = storeToRefs(mediaStore)
const needsFetching = computed(() =>
Boolean(supported.value && !resultCount.value && searchTerm.value !== "")
@@ -125,22 +98,41 @@ export default defineComponent({
const { error: nuxtError } = useContext()
+ const searchResults = ref<Results | null>(
+ isSearchTypeSupported(searchType.value)
+ ? ({
+ type: searchType.value,
+ items:
+ searchType.value === ALL_MEDIA
+ ? mediaStore.allMedia
+ : mediaStore.resultItems[searchType.value],
+ } as Results)
+ : null
+ )
+
const fetchMedia = async (
payload: { shouldPersistMedia?: boolean } = {}
) => {
+ if (!isSearchTypeSupported(searchType.value)) {
+ return
+ }
/**
* If the fetch has already started in the middleware,
* and there is an error status that will not change if retried, don't re-fetch.
*/
const shouldNotRefetch =
- mediaStore.fetchState.hasStarted &&
+ fetchState.value.hasStarted &&
fetchingError.value !== null &&
!isRetriable(fetchingError.value)
if (shouldNotRefetch) {
return
}
+ if (!payload.shouldPersistMedia) {
+ searchResults.value = { type: searchType.value, items: [] }
+ }
- await mediaStore.fetchMedia(payload)
+ const media = await mediaStore.fetchMedia(payload)
+ searchResults.value = { type: searchType.value, items: media } as Results
if (
fetchingError.value === null ||
@@ -151,23 +143,19 @@ export default defineComponent({
return nuxtError(fetchingError.value)
}
- const fetchingError = computed(() => mediaStore.fetchState.fetchingError)
+ const fetchingError = computed(() => fetchState.value.fetchingError)
+ const isFetching = computed(() => fetchState.value.isFetching)
/**
- * Search middleware runs when the path changes. This watcher
- * is necessary to handle the query changes.
- *
- * It updates the search store state from the URL query,
- * fetches media, and scrolls to top if necessary.
+ * The search middleware updates the search store on every path or query
+ * change.
+ * This watcher fetches media, and scrolls to top if necessary.
*/
watch(route, async (newRoute, oldRoute) => {
if (
newRoute.path !== oldRoute.path ||
!isShallowEqualObjects(newRoute.query, oldRoute.query)
) {
- const { query: urlQuery, path } = newRoute
- searchStore.setSearchStateFromUrl({ urlQuery, path })
-
/**
* By default, Nuxt only scrolls to top when the path changes.
* This is a workaround to scroll to top when the query changes.
@@ -203,23 +191,22 @@ export default defineComponent({
await fetchMedia()
}
})
+ const handleLoadMore = async () => {
+ await fetchMedia({ shouldPersistMedia: true })
+ }
return {
- showScrollButton,
searchTerm,
searchType,
supported,
query,
- isSupportedMediaType,
resultCount,
- fetchState,
- resultItems,
- needsFetching,
- isSidebarVisible,
+ searchResults,
+ isFetching,
fetchingError,
- isAllView,
+ handleLoadMore,
skipToContentTargetId,
}
diff --git a/frontend/src/pages/search/audio.vue b/frontend/src/pages/search/audio.vue
index e35bc8def..dcb5e44b8 100644
--- a/frontend/src/pages/search/audio.vue
+++ b/frontend/src/pages/search/audio.vue
@@ -1,49 +1,42 @@
<template>
- <VAudioList
+ <VSearchResults
:results="results"
+ :is-fetching="isFetching"
+ :search-term="searchTerm"
kind="search"
- :fetch-state="fetchState"
- :collection-label="collectionLabel"
+ @load-more="handleLoadMore"
/>
</template>
<script lang="ts">
-import { computed, defineComponent, PropType } from "vue"
+import { defineComponent, PropType } from "vue"
-import { useSearchStore } from "~/stores/search"
-import { useI18n } from "~/composables/use-i18n"
-import type { AudioDetail } from "~/types/media"
-import type { FetchState } from "~/types/fetch-state"
+import type { AudioResults } from "~/types/result"
-import VAudioList from "~/components/VSearchResultsGrid/VAudioList.vue"
+import VSearchResults from "~/components/VSearchResultsGrid/VSearchResults.vue"
export default defineComponent({
name: "AudioSearch",
components: {
- VAudioList,
+ VSearchResults,
},
props: {
results: {
- type: Array as PropType<AudioDetail[]>,
+ type: Object as PropType<AudioResults>,
required: true,
},
- fetchState: {
- type: Object as PropType<FetchState>,
+ isFetching: {
+ type: Boolean,
+ required: true,
+ },
+ searchTerm: {
+ type: String,
+ required: true,
+ },
+ handleLoadMore: {
+ type: Function as PropType<() => void>,
required: true,
},
- },
- setup() {
- const i18n = useI18n()
-
- const collectionLabel = computed(() => {
- const query = useSearchStore().searchTerm
-
- return i18n.t("browsePage.aria.results", { query }).toString()
- })
-
- return {
- collectionLabel,
- }
},
})
</script>
diff --git a/frontend/src/pages/search/image.vue b/frontend/src/pages/search/image.vue
index 68db33509..d6a637429 100644
--- a/frontend/src/pages/search/image.vue
+++ b/frontend/src/pages/search/image.vue
@@ -1,38 +1,40 @@
<template>
- <VImageGrid
+ <VSearchResults
:results="results"
- :fetch-state="fetchState"
+ :is-fetching="isFetching"
+ :search-term="searchTerm"
kind="search"
- :image-grid-label="
- $t('browsePage.aria.results', { query: searchTerm }).toString()
- "
+ @load-more="handleLoadMore"
/>
</template>
<script lang="ts">
import { defineComponent, PropType } from "vue"
-import type { ImageDetail } from "~/types/media"
-import type { FetchState } from "~/types/fetch-state"
+import type { ImageResults } from "~/types/result"
-import VImageGrid from "~/components/VSearchResultsGrid/VImageGrid.vue"
+import VSearchResults from "~/components/VSearchResultsGrid/VSearchResults.vue"
export default defineComponent({
name: "ImageSearch",
- components: { VImageGrid },
+ components: { VSearchResults },
props: {
results: {
- type: Array as PropType<ImageDetail[]>,
+ type: Object as PropType<ImageResults>,
required: true,
},
- fetchState: {
- type: Object as PropType<FetchState>,
+ isFetching: {
+ type: Boolean,
required: true,
},
searchTerm: {
type: String,
required: true,
},
+ handleLoadMore: {
+ type: Function as PropType<() => void>,
+ required: true,
+ },
},
})
</script>
diff --git a/frontend/src/pages/search/index.vue b/frontend/src/pages/search/index.vue
index 079473bc7..46defa4de 100644
--- a/frontend/src/pages/search/index.vue
+++ b/frontend/src/pages/search/index.vue
@@ -1,14 +1,40 @@
<template>
- <VAllResultsGrid />
+ <VSearchResults
+ :results="results"
+ :is-fetching="isFetching"
+ :search-term="searchTerm"
+ kind="search"
+ @load-more="handleLoadMore"
+ />
</template>
<script lang="ts">
-import { defineComponent } from "vue"
+import { defineComponent, type PropType } from "vue"
-import VAllResultsGrid from "~/components/VSearchResultsGrid/VAllResultsGrid.vue"
+import type { AllMediaResults } from "~/types/result"
+
+import VSearchResults from "~/components/VSearchResultsGrid/VSearchResults.vue"
export default defineComponent({
name: "SearchIndex",
- components: { VAllResultsGrid },
+ components: { VSearchResults },
+ props: {
+ results: {
+ type: Object as PropType<AllMediaResults>,
+ required: true,
+ },
+ isFetching: {
+ type: Boolean,
+ required: true,
+ },
+ searchTerm: {
+ type: String,
+ required: true,
+ },
+ handleLoadMore: {
+ type: Function as PropType<() => void>,
+ required: true,
+ },
+ },
})
</script>
diff --git a/frontend/src/stores/media/index.ts b/frontend/src/stores/media/index.ts
index 71c37fac0..5c35ee48e 100644
--- a/frontend/src/stores/media/index.ts
+++ b/frontend/src/stores/media/index.ts
@@ -24,6 +24,10 @@ import { isSearchTypeSupported, useSearchStore } from "~/stores/search"
import { useRelatedMediaStore } from "~/stores/media/related-media"
import { deepFreeze } from "~/utils/deep-freeze"
+interface SearchFetchState extends Omit<FetchState, "hasStarted"> {
+ hasStarted: boolean
+}
+
export type MediaStoreResult = {
count: number
pageCount: number
@@ -37,8 +41,8 @@ export interface MediaState {
image: MediaStoreResult
}
mediaFetchState: {
- audio: FetchState
- image: FetchState
+ audio: SearchFetchState
+ image: SearchFetchState
}
currentPage: number
}
@@ -143,12 +147,12 @@ export const useMediaStore = defineStore("media", {
* Search fetching state for selected search type. For 'All content', aggregates
* the values for supported media types.
*/
- fetchState(): FetchState {
+ fetchState(): SearchFetchState {
if (this._searchType === ALL_MEDIA) {
/**
* For all_media, we return 'All media fetching error' if all types have some kind of error.
*/
- const atLeastOne = (property: keyof FetchState) =>
+ const atLeastOne = (property: keyof SearchFetchState) =>
supportedMediaTypes.some(
(type) => this.mediaFetchState[type][property]
)
@@ -286,6 +290,15 @@ export const useMediaStore = defineStore("media", {
!this.mediaFetchState[type].isFinished
)
},
+
+ canLoadMore(): boolean {
+ return (
+ this.fetchState.hasStarted &&
+ !this.fetchState.fetchingError &&
+ !this.fetchState.isFinished &&
+ this.resultCount > 0
+ )
+ },
},
actions: {
@@ -408,26 +421,23 @@ export const useMediaStore = defineStore("media", {
async fetchMedia(payload: { shouldPersistMedia?: boolean } = {}) {
const mediaType = this._searchType
const shouldPersistMedia = Boolean(payload.shouldPersistMedia)
- if (!shouldPersistMedia) {
- this.clearMedia()
- }
const mediaToFetch = this._fetchableMediaTypes
- const resultCounts = await Promise.all(
+ await Promise.allSettled(
mediaToFetch.map((mediaType) =>
this.fetchSingleMediaType({ mediaType, shouldPersistMedia })
)
)
- const resultCount = resultCounts.includes(null)
- ? null
- : (resultCounts as number[]).reduce((a, b) => a + b, 0)
this.currentPage =
mediaType === ALL_MEDIA
? this.currentPage + 1
: this.results[mediaType].page
- return resultCount
+
+ return mediaType === ALL_MEDIA
+ ? this.allMedia
+ : this.resultItems[mediaType]
},
clearMedia() {
diff --git a/frontend/src/stores/search.ts b/frontend/src/stores/search.ts
index 8ac22e8f2..9ba0975c3 100644
--- a/frontend/src/stores/search.ts
+++ b/frontend/src/stores/search.ts
@@ -311,9 +311,6 @@ export const useSearchStore = defineStore("search", {
this.strategy = "default"
this.addRecentSearch(formattedTerm)
-
- const mediaStore = useMediaStore()
- mediaStore.clearMedia()
},
/**
* Sets the collectionParams and mediaType for the collection page.
@@ -329,7 +326,8 @@ export const useSearchStore = defineStore("search", {
this.clearFilters()
},
/**
- * Called when a /search path is server-rendered.
+ * Called before navigating to a `/search` path, and when the
+ * path after `/search` or query parameters change.
*/
setSearchStateFromUrl({
path,
@@ -343,6 +341,9 @@ export const useSearchStore = defineStore("search", {
this.strategy = "default"
this.collectionParams = null
+ const mediaStore = useMediaStore()
+ mediaStore.clearMedia()
+
this.setSearchTerm(query.q)
this.searchType = pathToSearchType(path)
diff --git a/frontend/test/unit/specs/components/v-image-grid.spec.js b/frontend/test/unit/specs/components/v-image-grid.spec.js
deleted file mode 100644
index fb2ad0d73..000000000
--- a/frontend/test/unit/specs/components/v-image-grid.spec.js
+++ /dev/null
@@ -1,37 +0,0 @@
-import { screen } from "@testing-library/vue"
-
-import { render } from "~~/test/unit/test-utils/render"
-
-import VImageGrid from "~/components/VSearchResultsGrid/VImageGrid.vue"
-
-const propsData = {
- results: [
- { id: "i1", url: "http://localhost:8080/i1.png", title: "image1" },
- { id: "i2", url: "http://localhost:8080/i2.jpg", title: "image2" },
- { id: "i3", url: "http://localhost:8080/i3.svg", title: "image3" },
- ],
- fetchState: {
- isSinglePage: true,
- isFetching: false,
- fetchingError: null,
- },
- kind: "related",
- imageGridLabel: "Image Results",
-}
-
-describe("VImageGrid", () => {
- let options
- beforeEach(() => {
- options = {
- props: propsData,
- stubs: ["VLicense"],
- }
- })
- it("renders images without load more button for related images", () => {
- const imageCount = propsData.results.length
- render(VImageGrid, options)
- expect(screen.queryAllByRole("img").length).toEqual(imageCount)
- expect(screen.queryAllByRole("figure").length).toEqual(imageCount)
- expect(screen.queryByTestId("load-more")).toBeNull()
- })
-})
diff --git a/frontend/test/unit/specs/pages/browse-page.spec.js b/frontend/test/unit/specs/pages/browse-page.spec.js
deleted file mode 100644
index 409ae111b..000000000
--- a/frontend/test/unit/specs/pages/browse-page.spec.js
+++ /dev/null
@@ -1,63 +0,0 @@
-import { screen } from "@testing-library/vue"
-import { ref } from "vue"
-
-import { render } from "~~/test/unit/test-utils/render"
-
-import { IMAGE } from "~/constants/media"
-import { useSearchStore } from "~/stores/search"
-
-import SearchIndex from "~/pages/search.vue"
-
-import {
- IsHeaderScrolledKey,
- IsSidebarVisibleKey,
- ShowScrollButtonKey,
-} from "~/types/provides"
-
-describe("SearchIndex", () => {
- let options
- const defaultProvideOptions = {
- showScrollButton: ref(false),
- [IsHeaderScrolledKey]: ref(false),
- [IsSidebarVisibleKey]: ref(false),
- [ShowScrollButtonKey]: ref(false),
- }
- let searchStore
-
- beforeEach(() => {
- options = {
- provide: defaultProvideOptions,
- mocks: {
- $router: { path: { name: "search-image" } },
- $route: { path: "/search/image" },
- },
- stubs: {
- NuxtChild: true,
- VSearchGrid: true,
- },
- }
- })
-
- it("hides the scroll button when injected value is false", () => {
- options.provide.showScrollButton.value = false
-
- render(SearchIndex, options, (localVue, options) => {
- searchStore = useSearchStore(options.pinia)
- searchStore.setSearchTerm("cat")
- searchStore.setSearchType(IMAGE)
- })
-
- expect(screen.queryByLabelText(/scroll/i)).not.toBeVisible()
- })
-
- it("shows the scroll button when injected value is true", () => {
- options.provide[ShowScrollButtonKey].value = true
- render(SearchIndex, options, (localVue, options) => {
- searchStore = useSearchStore(options.pinia)
- searchStore.setSearchTerm("cat")
- searchStore.setSearchType(IMAGE)
- })
-
- expect(screen.queryByLabelText(/scroll/i)).toBeVisible()
- })
-})