Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Refactor search results components and media fetching (#382)
Olga Bulat91f79fdc4eec
diff --git a/nuxt.config.js b/nuxt.config.jsindex 4743f437f..23e8b114b 100644--- a/nuxt.config.js+++ b/nuxt.config.js@@ -133,7 +133,7 @@ export default {'~/components/ImageDetails','~/components/ImageGrid','~/components/MediaInfo',- '~/components/MetaSearch',+ '~/components/VMetaSearch','~/components/MediaTag','~/components/Skeleton','~/components/VPopover',diff --git a/src/components/AudioResultsList.vue b/src/components/AudioResultsList.vuedeleted file mode 100644index 196402fdc..000000000--- a/src/components/AudioResultsList.vue+++ /dev/null@@ -1,142 +0,0 @@-<template>- <section>- <div v-show="!fetchingState.isFetching" class="results-meta">- <span class="caption font-semibold">- {{ _audiosCount }}- </span>- </div>- <div class="px-6 pt-6">- <AudioTrack- v-for="(audio, index) in results.items"- :key="index"- :audio="audio"- :size="audioTrackSize"- layout="row"- />- </div>- <div v-if="!fetchingState.fetchingError" class="load-more">- <button- v-show="!fetchingState.isFetching"- class="button"- :disabled="isFinished"- @click="onLoadMoreAudios"- @keyup.enter="onLoadMoreAudios"- >- <span v-if="isFinished">{{- $t('browse-page.no-more', {- type: $t('browse-page.search-form.audio'),- })- }}</span>- <span v-else>{{ $t('browse-page.load') }}</span>- </button>- <LoadingIcon v-show="fetchingState.isFetching" />- </div>- <div- v-if="fetchingState.fetchingError"- class="m-auto w-1/2 text-center pt-6"- >- <h5>- {{- $t('browse-page.fetching-error', {- type: $t('browse-page.search-form.audio'),- })- }}- {{ fetchingState.fetchingError }}- </h5>- </div>- </section>-</template>--<script>-import { mapActions, mapGetters, mapState } from 'vuex'-import { FETCH_MEDIA } from '~/constants/action-types'-import { AUDIO } from '~/constants/media'-import { MEDIA, SEARCH } from '~/constants/store-modules'--export default {- name: 'AudioResultsList',- async fetch() {- if (!Object.keys(this.results.items).length) {- await this.fetchMedia({- ...this.query,- mediaType: AUDIO,- })- }- },- computed: {- ...mapState(SEARCH, ['query', 'isFilterVisible']),- ...mapGetters(MEDIA, ['fetchingState', 'results', 'isFinished']),- _audiosCount() {- const count = this.results.count- if (count === 0) {- return this.$t('browse-page.audio-no-results')- }- const localeCount = count.toLocaleString(this.$i18n.locale)- const i18nKey =- count >= 10000- ? 'browse-page.audio-result-count-more'- : 'browse-page.audio-result-count'- return this.$tc(i18nKey, count, { localeCount })- },- audioTrackSize() {- return this.isFilterVisible ? 'm' : 's'- },- },- methods: {- ...mapActions(MEDIA, { fetchMedia: FETCH_MEDIA }),- onLoadMoreAudios() {- const searchParams = {- page: this.results.page + 1,- shouldPersistMedia: true,- ...this.query,- }- this.$emit('onLoadMoreAudios', searchParams)- },- },-}-</script>--<style lang="scss" scoped>-.audio-track {- @apply pb-10;-}--.load-more {- text-align: center;-- button {- color: #23282d;- margin-top: 2rem;- border: 1px solid rgba(35, 40, 45, 0.2);- font-size: 1.2em;-- &:hover {- color: white;- }- &:disabled {- opacity: 1;- &:hover {- color: black;- }- }-- @include mobile {- padding: 0.5rem;-- span {- font-size: 0.9rem;- }- }- }-}--.results-meta {- @apply px-6 pt-2;-- @screen lg {- display: flex;- justify-content: space-between;- align-items: center;- }-}-</style>diff --git a/src/components/Filters/FilterDisplay.vue b/src/components/Filters/FilterDisplay.vueindex 282c3d519..ab2eacaa8 100644--- a/src/components/Filters/FilterDisplay.vue+++ b/src/components/Filters/FilterDisplay.vue@@ -1,5 +1,5 @@<template>- <div class="flex flex-wrap items-center p-4" aria-live="polite">+ <div class="flex flex-wrap items-center px-6" aria-live="polite"><span v-if="isAnyFilterApplied" class="me-2 font-semibold mb-2">{{ $t('filters.filter-by') }}</span>diff --git a/src/components/ImageDetails/RelatedImages.vue b/src/components/ImageDetails/RelatedImages.vueindex d8d13ecd3..736064c07 100644--- a/src/components/ImageDetails/RelatedImages.vue+++ b/src/components/ImageDetails/RelatedImages.vue@@ -9,9 +9,10 @@<ImageGrid:images="images":can-load-more="false"- :is-fetching="$fetchState.pending"- :fetching-error="$fetchState.error"- :error-message-text="null"+ :fetch-state="{+ isFetching: $fetchState.pending,+ fetchingError: $fetchState.error,+ }"/></aside></template>diff --git a/src/components/ImageGrid/ImageGrid.vue b/src/components/ImageGrid/ImageGrid.vueindex 33400231b..45d1df9e6 100644--- a/src/components/ImageGrid/ImageGrid.vue+++ b/src/components/ImageGrid/ImageGrid.vue@@ -4,15 +4,15 @@<ImageCell v-for="(image, index) in images" :key="index" :image="image" /></div><h5 v-if="isError" class="image-grid__notification py-4">- {{ errorMessageText }}+ {{ fetchState.fetchingError }}</h5><LoadMoreButtonv-if="canLoadMore":is-error="isError"- :is-fetching="isFetching"- :is-finished="isFinished"+ :is-fetching="fetchState.isFetching"+ :is-finished="fetchState.isFinished"data-testid="load-more"- @onLoadMore="onLoadMoreImages"+ @onLoadMore="onLoadMore"/></section></template>@@ -39,26 +39,14 @@ export default {type: Boolean,default: true,},- isFetching: {- type: Boolean,- default: false,- },- fetchingError: {- default: null,- },- errorMessageText: {- type: String,- default: '',- },- isFinished: {- type: Boolean,- default: false,+ fetchState: {+ required: true,},},computed: {isError() {- return !!this.fetchingError+ return !!this.fetchState.fetchingError},fetchingErrorHeading() {const type = this.$t('browse-page.search-form.image')@@ -66,8 +54,8 @@ export default {},},methods: {- onLoadMoreImages() {- this.$emit('onLoadMoreImages')+ onLoadMore() {+ this.$emit('load-more')},},}diff --git a/src/components/ImageGrid/LoadMoreButton.vue b/src/components/ImageGrid/LoadMoreButton.vueindex ee1bd7f12..e9e4401fe 100644--- a/src/components/ImageGrid/LoadMoreButton.vue+++ b/src/components/ImageGrid/LoadMoreButton.vue@@ -9,7 +9,7 @@><span>{{ buttonLabel }}</span></button>- <LoadingIcon :should-show="isFetching" />+ <LoadingIcon v-show="isFetching" /></div></template><script>@@ -31,10 +31,14 @@ export default {type: Boolean,default: false,},+ mediaType: {+ type: String,+ default: 'image',+ },},computed: {finishedLabel() {- const type = this.$t('browse-page.search-form.image')+ const type = this.$t(`browse-page.search-form.${this.mediaType}`)return this.$t('browse-page.no-more', { type })},buttonLabel() {diff --git a/src/components/SearchGrid.vue b/src/components/SearchGrid.vuedeleted file mode 100644index 3cb5ac149..000000000--- a/src/components/SearchGrid.vue+++ /dev/null@@ -1,26 +0,0 @@-<template>- <SearchGridManualLoad- :query="query"- :search-term="query.q"- data-testid="search-grid"- @onLoadMoreImages="onLoadMoreImages"- />-</template>--<script>-import { mapState } from 'vuex'-import { SEARCH } from '~/constants/store-modules'--export default {- name: 'SearchGrid',- props: ['searchTerm'],- computed: {- ...mapState(SEARCH, ['query']),- },- methods: {- onLoadMoreImages(searchParams) {- this.$emit('onLoadMoreImages', searchParams)- },- },-}-</script>diff --git a/src/components/SearchGridManualLoad.vue b/src/components/SearchGridManualLoad.vuedeleted file mode 100644index 97365580a..000000000--- a/src/components/SearchGridManualLoad.vue+++ /dev/null@@ -1,215 +0,0 @@-<template>- <section- ref="searchGrid"- :class="{- 'search-grid': true,- 'search-grid__contain-images': shouldContainImages,- }"- >- <div ref="gridItems" class="search-grid_ctr">- <div- v-show="!fetchingState.isFetching && includeAnalytics"- class="results-meta"- >- <span class="caption font-semibold">- {{ _imagesCount }}- </span>- <div class="hidden lg:block lg:me-auto lg:ps-6">- <SearchRating v-if="searchTerm" :search-term="searchTerm" />- </div>- <SaferBrowsing />- </div>- <div class="search-grid-cells">- <SearchGridCell- v-for="(image, index) in results.items"- :key="index"- :image="image"- />- </div>- <div- v-if="!!fetchingState.error"- class="search-grid_notification callout alert"- >- <h5>- {{- $t('browse-page.fetching-error', {- type: $t('browse-page.search-form.audio'),- })- }}- {{ fetchingState.fetchingError }}- </h5>- </div>- <div class="pb-6">- <div- v-if="!fetchingState.fetchingError && !isFinished"- class="load-more"- >- <button- v-show="!fetchingState.isFetching && includeAnalytics"- class="button"- @click="onLoadMoreImages"- @keyup.enter="onLoadMoreImages"- >- <span>{{ $t('browse-page.load') }}</span>- </button>- <LoadingIcon v-show="fetchingState.isFetching" />- </div>- <MetaSearchForm- type="image"- :noresult="!fetchingState.isFetching && results.count === 0"- :supported="true"- />- </div>- </div>- </section>-</template>--<script>-import { FETCH_MEDIA } from '~/constants/action-types'-import { RESET_MEDIA } from '~/constants/mutation-types'-import { IMAGE } from '~/constants/media'-import { mapActions, mapGetters, mapMutations, mapState } from 'vuex'-import { MEDIA, SEARCH } from '~/constants/store-modules'--export default {- name: 'SearchGridManualLoad',- props: {- useInfiniteScroll: {- default: true,- },- includeAnalytics: {- default: true,- },- includeAddToList: {- default: true,- },- searchTerm: {- default: '',- },- },- data: () => ({- isDataInitialized: false,- shouldContainImages: false,- showMetaImageSearch: false,- }),- computed: {- ...mapState(SEARCH, ['query']),- ...mapGetters(MEDIA, ['fetchingState', 'results', 'isFinished']),- _imagesCount() {- const count = this.results.count- if (count === 0) {- return this.$t('browse-page.image-no-results')- }- const localeCount = count.toLocaleString(this.$i18n.locale)- const i18nKey =- count >= 10000- ? 'browse-page.image-result-count-more'- : 'browse-page.image-result-count'- return this.$tc(i18nKey, count, { localeCount })- },- _query() {- return this.query- },- },- watch: {- _query: {- handler() {- this.searchChanged()- },- deep: true,- },- },- methods: {- ...mapMutations(MEDIA, { resetMedia: RESET_MEDIA }),- ...mapActions(MEDIA, { fetchMedia: FETCH_MEDIA }),- searchChanged() {- this.resetMedia({ mediaType: IMAGE })- },- onLoadMoreImages() {- const searchParams = {- page: this.results.page + 1,- shouldPersistMedia: true,- ...this._query,- }-- this.$emit('onLoadMoreImages', searchParams)- },- },-}-</script>--<!-- Add "scoped" attribute to limit CSS to this component only -->-<style lang="scss" scoped>-.search-grid:after {- content: '';- display: block;- clear: both;-}--.search-grid_notification {- width: 50%;- margin: auto;- font-weight: 500;- text-align: center;-}--.search-grid-cells {- display: flex;- flex-wrap: wrap;- margin: 10px;-- @include tablet {- &:after {- content: '';- flex-grow: 999999999;- }- }-}--label {- color: #333333;-}--.load-more {- text-align: center;-- button {- color: #23282d;- margin-top: 2rem;- border: 1px solid rgba(35, 40, 45, 0.2);- font-size: 1.2em;-- &:hover {- color: white;- }- &:disabled {- opacity: 1;- &:hover {- color: black;- }- }-- @include mobile {- padding: 0.5rem;-- span {- font-size: 0.9rem;- }- }- }-}--.results-meta {- @apply px-6 pt-2;-- @screen lg {- display: flex;- justify-content: space-between;- align-items: center;- }-- .button.is-text {- font-size: 0.8rem;- }-}-</style>diff --git a/src/components/Skeleton/GridSkeleton.vue b/src/components/Skeleton/GridSkeleton.vueindex 4a177ca10..30f8c3536 100644--- a/src/components/Skeleton/GridSkeleton.vue+++ b/src/components/Skeleton/GridSkeleton.vue@@ -2,7 +2,7 @@<section class="px-10 pb-16"><divv-if="isForTab == 'all'"- class="grid gap-4 tab:grid-cols-2 desk:grid-cols-5"+ class="grid gap-4 tab:grid-cols-2 lg:grid-cols-5"><VBone v-for="idx in numElems" :key="idx" class="square" /></div>diff --git a/src/components/HeroSection.vue b/src/components/VHeroSection.vuesimilarity index 92%rename from src/components/HeroSection.vuerename to src/components/VHeroSection.vueindex 3014cea7e..c95c78003 100644--- a/src/components/HeroSection.vue+++ b/src/components/VHeroSection.vue@@ -68,14 +68,19 @@</template><script>-import { UPDATE_QUERY, TOGGLE_FILTER } from '~/constants/action-types'-import { SEARCH } from '~/constants/store-modules'+import {+ UPDATE_QUERY,+ TOGGLE_FILTER,+ FETCH_MEDIA,+} from '~/constants/action-types'+import { MEDIA, SEARCH } from '~/constants/store-modules'import { mapActions, mapGetters } from 'vuex'-import HomeLicenseFilter from '~/components/HomeLicenseFilter'-import SearchTypeToggle from '~/components/SearchTypeToggle'++import HomeLicenseFilter from '~/components/HomeLicenseFilter.vue'+import SearchTypeToggle from '~/components/SearchTypeToggle.vue'export default {- name: 'HeroSection',+ name: 'VHeroSection',components: { HomeLicenseFilter, SearchTypeToggle },/*** @return {{ form: { searchTerm: string, searchType: 'image' | 'audio' }, showSearchType: boolean }}@@ -98,6 +103,7 @@ export default {setSearchTerm: UPDATE_QUERY,checkFilter: TOGGLE_FILTER,}),+ ...mapActions(MEDIA, { fetchMedia: FETCH_MEDIA }),getPath() {if (!process.env.enableAudio) return '/search/image'return `/search/${this.form.searchType}`@@ -121,6 +127,8 @@ export default {newQuery.searchType = this.form.searchType}this.setSearchTerm(newQuery)+ this.fetchMedia({})+const newPath = this.localePath({path: this.getPath(),query: this.searchQueryParams,diff --git a/src/components/MetaSearch/MetaSearchForm.vue b/src/components/VMetaSearch/VMetaSearchForm.vuesimilarity index 79%rename from src/components/MetaSearch/MetaSearchForm.vuerename to src/components/VMetaSearch/VMetaSearchForm.vueindex fd2d42d6b..9c382a307 100644--- a/src/components/MetaSearch/MetaSearchForm.vue+++ b/src/components/VMetaSearch/VMetaSearchForm.vue@@ -1,5 +1,5 @@<template>- <section :key="type" class="p-6 meta-search">+ <section :key="type" class="p-6 meta-search text-center mt-12"><header class="mb-10"><i18nv-if="!noresult"@@ -37,32 +37,31 @@</i18n></header>- <MetaSourceList :type="type" :query="metaQuery" />+ <VMetaSourceList :type="type" :query="metaQuery" />- <p class="caption font-semibold max-w-lg">+ <p class="caption font-semibold max-w-3xl my-0 mx-auto">{{ $t('meta-search.caption') }}</p></section></template><script>-import MetaSourceList from './MetaSourceList'import { AUDIO, IMAGE, VIDEO } from '~/constants/media'-import { mapState } from 'vuex'-import { SEARCH } from '~/constants/store-modules'++import VMetaSourceList from './VMetaSourceList.vue'export default {- name: 'MetaSearch',+ name: 'VMetaSearch',components: {- MetaSourceList,+ VMetaSourceList,},props: {+ query: { type: Object, required: true },type: { type: String, required: true },supported: { type: Boolean, default: false },noresult: { type: Boolean, required: true },},computed: {- ...mapState(SEARCH, ['query']),unsupportedByUsefilter() {if (this.type === AUDIO) {return 'CC Mixter, Jamendo, or Wikimedia Commons'@@ -87,15 +86,3 @@ export default {},}</script>--<style>-.meta-search {- margin-top: 3rem;- text-align: center;-}--.max-w-lg {- max-width: 48rem;- margin: 0 auto;-}-</style>diff --git a/src/components/MetaSearch/MetaSourceList.vue b/src/components/VMetaSearch/VMetaSourceList.vuesimilarity index 100%rename from src/components/MetaSearch/MetaSourceList.vuerename to src/components/VMetaSearch/VMetaSourceList.vuediff --git a/src/components/SaferBrowsing.vue b/src/components/VSaferBrowsing.vuesimilarity index 98%rename from src/components/SaferBrowsing.vuerename to src/components/VSaferBrowsing.vueindex 6d4207ad7..105e6a354 100644--- a/src/components/SaferBrowsing.vue+++ b/src/components/VSaferBrowsing.vue@@ -44,7 +44,7 @@ import { mapActions } from 'vuex'import { SEARCH } from '~/constants/store-modules'export default {- name: 'SaferBrowsing',+ name: 'VSaferBrowsing',components: {FocusTrap,},diff --git a/src/components/ScrollButton.vue b/src/components/VScrollButton.vuesimilarity index 88%rename from src/components/ScrollButton.vuerename to src/components/VScrollButton.vueindex b1920cf35..afe330a37 100644--- a/src/components/ScrollButton.vue+++ b/src/components/VScrollButton.vue@@ -1,7 +1,7 @@<template><button- v-if="showBtn":aria-label="$t('browse-page.aria.scroll')"+ type="button"class="scroll text-white bg-trans-blue hover:bg-trans-blue-action transition-all duration-100 ease-linear fixed end-4 bottom-4 w-14 h-14 hover:shadow-md rounded-full text-center"@click="scrollToTop"@keyup.enter="scrollToTop"@@ -20,12 +20,7 @@<script>export default {- name: 'ScrollButton',- props: {- showBtn: {- type: Boolean,- },- },+ name: 'VScrollButton',methods: {scrollToTop() {window.scrollTo({diff --git a/src/components/VSearchGrid.vue b/src/components/VSearchGrid.vuenew file mode 100644index 000000000..7aca05d6f--- /dev/null+++ b/src/components/VSearchGrid.vue@@ -0,0 +1,128 @@+<template>+ <section class="search-grid">+ <div+ v-if="shouldShowMeta"+ class="results-meta flex flex-col sm:flex-row items-start justify-between px-6"+ data-testid="search-meta"+ >+ <div+ class="font-semibold caption leading-10 flex flex-col sm:flex-row sm:me-auto justify-between"+ >+ <span class="pe-6">+ {{ mediaCount }}+ </span>+ <VSearchRating+ v-if="query.q"+ :search-term="query.q"+ class="leading-10"+ />+ </div>+ <VSaferBrowsing />+ </div>+ <slot name="media" />++ <VMetaSearchForm+ v-if="!fetchState.isFetching"+ :type="metaSearchFormType"+ :noresult="noresult"+ :query="query"+ :supported="isSupported"+ />+ </section>+</template>++<script>+import { computed, useContext } from '@nuxtjs/composition-api'+import { AUDIO, IMAGE } from '~/constants/media'++import VSaferBrowsing from '~/components/VSaferBrowsing.vue'+import VSearchRating from '~/components/VSearchRating.vue'+import VMetaSearchForm from '~/components/VMetaSearch/VMetaSearchForm.vue'++const i18nKeys = {+ [AUDIO]: {+ noResult: 'browse-page.audio-no-results',+ result: 'browse-page.audio-result-count',+ more: 'browse-page.audio-result-count-more',+ },+ [IMAGE]: {+ noResult: 'browse-page.image-no-results',+ result: 'browse-page.image-result-count',+ more: 'browse-page.image-result-count-more',+ },+}++export default {+ name: 'VSearchGrid',+ components: { VMetaSearchForm, VSaferBrowsing, VSearchRating },+ props: {+ supported: {+ type: Boolean,+ required: true,+ },+ query: {+ type: Object,+ required: true,+ },+ searchType: {+ type: String,+ required: true,+ },+ fetchState: {+ required: true,+ },+ resultsCount: {+ type: Number,+ required: true,+ },+ },+ setup(props) {+ const { i18n } = useContext()+ const shouldShowMeta = computed(() => {+ return (+ props.supported &&+ props.query.q.trim() !== '' &&+ !props.fetchState.isFetching+ )+ })+ /**+ * The translated string showing how many results were found for+ * this media type.+ *+ * @returns {string}+ */+ const mediaCount = computed(() => {+ if (!props.supported) return++ const count = props.resultsCount+ const countKey =+ count === 0 ? 'noResult' : count >= 10000 ? 'more' : 'result'+ const i18nKey = i18nKeys[props.query.mediaType][countKey]+ const localeCount = count.toLocaleString(i18n.locale)+ return i18n.tc(i18nKey, count, { localeCount })+ })++ const noresult = computed(() => {+ // noresult is hard-coded for search types that are not currently+ // supported by Openverse built-in search+ return props.supported+ ? props.query.q !== '' && props.resultsCount === 0+ : false+ })+ const isSupported = computed(() => {+ return props.searchType === 'all' ? true : props.supported+ })+ const metaSearchFormType = computed(() => {+ return props.searchType === 'all' ? 'image' : props.searchType+ })++ return {+ mediaCount,+ noresult,+ shouldShowMeta,+ isSupported,+ metaSearchFormType,+ }+ },+}+</script>diff --git a/src/components/SearchRating.vue b/src/components/VSearchRating.vuesimilarity index 91%rename from src/components/SearchRating.vuerename to src/components/VSearchRating.vueindex 524d4feee..063b59986 100644--- a/src/components/SearchRating.vue+++ b/src/components/VSearchRating.vue@@ -1,7 +1,7 @@<template>- <div class="caption font-semibold">+ <div><!-- eslint-disable @intlify/vue-i18n/no-raw-text -->- <div v-if="status == 'NOT_SENT'">+ <template v-if="status === 'NOT_SENT'"><span>{{ $t('browse-page.search-rating.content') }}</span><button:aria-label="$t('browse-page.aria.relevance.yes')"@@ -20,12 +20,12 @@>{{ $t('browse-page.search-rating.no') }}</button>- </div>- <div v-else-if="status == 'SENT'">+ </template>+ <template v-else-if="status === 'SENT'"><span class="thank-you">{{$t('browse-page.search-rating.feedback-thanks')}}</span>- </div>+ </template></div></template>@@ -39,7 +39,7 @@ const Statuses = {}export default {- name: 'SearchRating',+ name: 'VSearchRating',props: ['searchTerm'],data() {return {diff --git a/src/composables/use-load-more.js b/src/composables/use-load-more.jsnew file mode 100644index 000000000..90d77021e--- /dev/null+++ b/src/composables/use-load-more.js@@ -0,0 +1,28 @@+import { computed, useContext } from '@nuxtjs/composition-api'+import { FETCH_MEDIA } from '~/constants/action-types'+import { MEDIA } from '~/constants/store-modules'++/**+ * Fetches media on 'Load More' button click.+ *+ * @param {import('../pages/search/search-page.types').Props} props+ * @returns {{ onLoadMore: ((function(): Promise<void>)|void), canLoadMore: import('@nuxtjs/composition-api').ComputedRef<boolean>}}+ */+export const useLoadMore = (props) => {+ const { store } = useContext()++ const searchParams = computed(() => ({+ page: props.mediaResults.page + 1,+ shouldPersistMedia: true,+ }))++ const canLoadMore = computed(() => props.searchTerm.trim() !== '')+ const onLoadMore = async () => {+ if (canLoadMore) {+ await store.dispatch(`${MEDIA}/${FETCH_MEDIA}`, searchParams.value)+ }+ await Promise.resolve()+ }++ return { canLoadMore, onLoadMore }+}diff --git a/src/pages/index.vue b/src/pages/index.vueindex d3d9edd68..9c6bbdff2 100644--- a/src/pages/index.vue+++ b/src/pages/index.vue@@ -1,14 +1,19 @@<template>- <HeroSection />+ <VHeroSection /></template><script>import { SEARCH } from '~/constants/store-modules'import { CLEAR_FILTERS } from '~/constants/action-types'+import VHeroSection from '~/components/VHeroSection.vue'+const HomePage = {name: 'home-page',layout: 'default',+ components: {+ VHeroSection,+ },beforeMount() {this.$store.dispatch(`${SEARCH}/${CLEAR_FILTERS}`)},diff --git a/src/pages/search.vue b/src/pages/search.vueindex 8f4ae73f0..2b18d1fd6 100644--- a/src/pages/search.vue+++ b/src/pages/search.vue@@ -10,10 +10,32 @@/></Component><div class="column search-grid-ctr"><SearchGridForm @onSearchFormSubmit="onSearchFormSubmit" />- <SearchTypeTabs />+ <SearchTypeTabs class="mb-4" /><FilterDisplay v-show="shouldShowFilterTags" />- <NuxtChild :key="$route.path" @onLoadMoreItems="onLoadMoreItems" />- <ScrollButton :show-btn="showScrollButton" />+ <VSearchGrid+ :id="`tab-${searchType}`"+ role="tabpanel"+ :aria-labelledby="searchType"+ :fetch-state="fetchState"+ :query="query"+ :supported="supported"+ :search-type="searchType"+ :results-count="resultsCount"+ data-testid="search-grid"+ >+ <template #media>+ <NuxtChild+ :key="$route.path"+ :media-results="results"+ :fetch-state="fetchState"+ :is-filter-visible="isFilterVisible"+ :search-term="query.q"+ :supported="supported"+ data-testid="search-results"+ />+ </template>+ </VSearchGrid>+ <VScrollButton v-show="showScrollButton" data-testid="scroll-button" /></div></div></div>@@ -29,19 +51,26 @@ import {import { SET_FILTER_IS_VISIBLE } from '~/constants/mutation-types'import { queryStringToSearchType } from '~/utils/search-query-transform'import local from '~/utils/local'-import { ALL_MEDIA, IMAGE, VIDEO } from '~/constants/media'+import { ALL_MEDIA, AUDIO, IMAGE } from '~/constants/media'import { mapActions, mapGetters, mapMutations, mapState } from 'vuex'import { MEDIA, SEARCH } from '~/constants/store-modules'import debounce from 'lodash.debounce'-import SearchGridFilter from '~/components/Filters/SearchGridFilter.vue'+import { isScreen } from '~/composables/use-media-query.js'-import AppModal from '~/components/AppModal'++import AppModal from '~/components/AppModal.vue'+import VScrollButton from '~/components/VScrollButton.vue'+import VSearchGrid from '~/components/VSearchGrid.vue'+import SearchGridFilter from '~/components/Filters/SearchGridFilter.vue'const BrowsePage = {name: 'browse-page',layout: 'default',components: {+ AppModal,SearchGridFilter,+ VScrollButton,+ VSearchGrid,},setup() {const defaultWindow = typeof window !== 'undefined' ? window : undefined@@ -52,8 +81,12 @@ const BrowsePage = {},scrollToTop: false,async fetch() {- if (this.mediaType !== VIDEO && !Object.keys(this.results.items).length) {- await this.fetchMedia({ mediaType: this.mediaType, q: this.query.q })+ if (+ this.supported &&+ !Object.keys(this.results.items).length &&+ this.query.q.trim() !== ''+ ) {+ await this.fetchMedia({})}},data: () => ({@@ -84,7 +117,7 @@ const BrowsePage = {computed: {...mapState(SEARCH, ['query', 'isFilterVisible', 'searchType']),...mapGetters(SEARCH, ['searchQueryParams', 'isAnyFilterApplied']),- ...mapGetters(MEDIA, ['results']),+ ...mapGetters(MEDIA, ['results', 'fetchState']),mediaType() {// Default to IMAGE until media search/index is generalizedreturn this.searchType !== ALL_MEDIA ? this.searchType : IMAGE@@ -95,6 +128,13 @@ const BrowsePage = {this.isAnyFilterApplied)},+ /**+ * Number of search results. Returns 0 for unsupported types.+ * @returns {number}+ */+ resultsCount() {+ return this.supported ? this.results.count : 0+ },searchFilter() {return {classes: {@@ -103,6 +143,14 @@ const BrowsePage = {as: this.isMdScreen ? 'aside' : AppModal,}},+ supported() {+ if (this.searchType === AUDIO) {+ // Only show audio results if non-image results are supported+ return process.env.enableAudio+ } else {+ return [IMAGE, ALL_MEDIA].includes(this.searchType)+ }+ },},methods: {...mapActions(MEDIA, { fetchMedia: FETCH_MEDIA }),@@ -114,11 +162,10 @@ const BrowsePage = {...mapMutations(SEARCH, {setFilterVisibility: SET_FILTER_IS_VISIBLE,}),- async getMediaItems(params, mediaType) {- await this.fetchMedia({ ...params, mediaType })- },- onLoadMoreItems(searchParams) {- this.getMediaItems(searchParams, this.mediaType)+ async getMediaItems(params) {+ if (this.query.q.trim() !== '') {+ await this.fetchMedia({ ...params })+ }},onSearchFormSubmit({ q }) {this.updateQuery({ q })@@ -141,7 +188,9 @@ const BrowsePage = {query: this.searchQueryParams,})this.$router.push(newPath)- this.getMediaItems(this.query, this.mediaType)+ if (this.supported) {+ this.getMediaItems(this.query)+ }},},/**diff --git a/src/pages/search/audio.vue b/src/pages/search/audio.vueindex 25686e88d..5075721e6 100644--- a/src/pages/search/audio.vue+++ b/src/pages/search/audio.vue@@ -1,25 +1,70 @@-<!-- noresult is hardcoded since it does not yet support built-in audio search --><template>- <div id="tab-audio" role="tabpanel" aria-labelledby="audio">- <AudioResultsList v-if="supported" @onLoadMoreAudios="onLoadMoreAudios" />- <MetaSearchForm type="audio" :noresult="false" :supported="supported" />- </div>+ <section>+ <template v-if="supported">+ <AudioTrack+ v-for="audio in mediaResults.items"+ :key="audio.id"+ class="px-6 mb-6"+ :audio="audio"+ :size="audioTrackSize"+ layout="row"+ />++ <template v-if="isError" class="m-auto w-1/2 text-center pt-6">+ <h5>{{ errorHeader }}</h5>+ <p>{{ fetchState.fetchingError }}</p>+ </template>+ <LoadMoreButton+ v-if="canLoadMore"+ :is-error="isError"+ :is-fetching="fetchState.isFetching"+ :is-finished="fetchState.isFinished"+ media-type="audio"+ data-testid="load-more"+ @onLoadMore="onLoadMore"+ />+ </template>+ </section></template><script>-export default {+import { computed, defineComponent, useContext } from '@nuxtjs/composition-api'+import { useLoadMore } from '~/composables/use-load-more'++import AudioTrack from '~/components/AudioTrack/AudioTrack.vue'+import LoadMoreButton from '~/components/ImageGrid/LoadMoreButton.vue'++import { propTypes } from './search-page.types'++const AudioSearch = defineComponent({name: 'AudioSearch',- data() {+ components: {+ AudioTrack,+ LoadMoreButton,+ },+ props: propTypes,+ setup(props) {+ const { i18n } = useContext()++ const audioTrackSize = computed(() => (props.isFilterVisible ? 'm' : 's'))++ const isError = computed(() => !!props.fetchState.fetchingError)+ const errorHeader = computed(() => {+ const type = i18n.t('browse-page.search-form.audio')+ return i18n.t('browse-page.fetching-error', { type })+ })++ const { canLoadMore, onLoadMore } = useLoadMore(props)+return {- // Only show audio results if non-image results are supported- supported: process.env.enableAudio,+ audioTrackSize,+ isError,+ errorHeader,++ canLoadMore,+ onLoadMore,}},- methods: {- onLoadMoreAudios(searchParams) {- if (!this.supported) return- this.$emit('onLoadMoreItems', searchParams)- },- },-}+})+export default AudioSearch</script>diff --git a/src/pages/search/image.vue b/src/pages/search/image.vueindex 21db00e8f..096ded9ec 100644--- a/src/pages/search/image.vue+++ b/src/pages/search/image.vue@@ -1,19 +1,25 @@<template>- <SearchGrid- id="tab-image"- role="tabpanel"- aria-labelledby="image"- @onLoadMoreImages="onLoadMoreImages"+ <ImageGrid+ :images="mediaResults.items"+ :can-load-more="canLoadMore"+ :fetch-state="fetchState"+ @load-more="onLoadMore"/></template><script>-export default {+import { propTypes } from '~/pages/search/search-page.types'+import { defineComponent } from '@nuxtjs/composition-api'+import { useLoadMore } from '~/composables/use-load-more'++const ImageSearch = defineComponent({name: 'ImageSearch',- methods: {- onLoadMoreImages(searchParams) {- this.$emit('onLoadMoreItems', searchParams)- },+ props: propTypes,+ setup(props) {+ const { canLoadMore, onLoadMore } = useLoadMore(props)+ return { canLoadMore, onLoadMore }},-}+})++export default ImageSearch</script>diff --git a/src/pages/search/index.vue b/src/pages/search/index.vueindex 3f298d2a1..30d6cf9bc 100644--- a/src/pages/search/index.vue+++ b/src/pages/search/index.vue@@ -1,19 +1,25 @@<template>- <SearchGrid- id="tab-all"- role="tabpanel"- aria-labelledby="all"- @onLoadMoreImages="onLoadMoreImages"+ <ImageGrid+ :images="mediaResults.items"+ :can-load-more="canLoadMore"+ :fetch-state="fetchState"+ @load-more="onLoadMore"/></template><script>-export default {+import { propTypes } from '~/pages/search/search-page.types'+import { defineComponent } from '@nuxtjs/composition-api'+import { useLoadMore } from '~/composables/use-load-more'++const SearchIndex = defineComponent({name: 'SearchIndex',- methods: {- onLoadMoreImages(searchParams) {- this.$emit('onLoadMoreItems', searchParams)- },+ props: propTypes,++ setup(props) {+ const { canLoadMore, onLoadMore } = useLoadMore(props)+ return { canLoadMore, onLoadMore }},-}+})+export default SearchIndex</script>diff --git a/src/pages/search/search-page.types.js b/src/pages/search/search-page.types.jsnew file mode 100644index 000000000..ec89024f4--- /dev/null+++ b/src/pages/search/search-page.types.js@@ -0,0 +1,24 @@+export const propTypes = {+ mediaResults: {+ type: /** @type {import('../../store/types').MediaResult[]} */ (Object),+ required: true,+ },+ fetchState: {+ type: /** @type {import('../../store/types').FetchState[]} */ (Object),+ required: true,+ },+ isFilterVisible: {+ type: Boolean,+ required: false,+ },+ searchTerm: {+ type: String,+ required: true,+ },+ supported: {+ type: Boolean,+ required: false,+ },+}++/** @typedef {import('@nuxtjs/composition-api').ExtractPropTypes<typeof propTypes>} Props */diff --git a/src/pages/search/video.vue b/src/pages/search/video.vueindex 42f7b58b1..488d73818 100644--- a/src/pages/search/video.vue+++ b/src/pages/search/video.vue@@ -1,12 +1,5 @@-<!-- noresult is hardcoded since it does not yet support built-in video search --><template>- <MetaSearchForm- id="type-video"- type="video"- role="tabpanel"- :noresult="false"- aria-labelledby="video"- />+ <div /></template><script>diff --git a/src/store/media.js b/src/store/media.jsindex 739539a22..27e4d8d31 100644--- a/src/store/media.js+++ b/src/store/media.js@@ -22,7 +22,7 @@ import {SEND_RESULT_CLICKED_EVENT,SEND_SEARCH_QUERY_EVENT,} from '~/constants/usage-data-analytics-types'-import { AUDIO, IMAGE } from '~/constants/media'+import { AUDIO, IMAGE, VIDEO } from '~/constants/media'import { USAGE_DATA } from '~/constants/store-modules'import AudioService from '~/data/audio-service'import ImageService from '~/data/image-service'@@ -45,14 +45,16 @@ export const state = () => ({items: {},},},- fetchingState: {+ fetchState: {audio: {isFetching: false,fetchingError: null,+ isFinished: false,},image: {isFetching: false,fetchingError: null,+ isFinished: false,},},audio: {},@@ -63,32 +65,38 @@ export const createActions = (services) => ({/**** @param {import('vuex').ActionContext} context- * @param params+ * @param {Object} payload+ * @param {number} [payload.page] - API page to load.+ * @param {boolean} [payload.shouldPersistMedia] - whether the existing media+ * should be added to or replaced.* @return {Promise<void>}*/- async [FETCH_MEDIA]({ commit, dispatch, rootState, rootGetters }, params) {+ async [FETCH_MEDIA](+ { commit, dispatch, rootState, rootGetters },+ payload = {}+ ) {+ const { page = undefined, shouldPersistMedia = false } = payload++ const queryParams = prepareSearchQueryParams({+ ...rootGetters['search/searchQueryParams'],+ ...payload,+ })+// does not send event if user is paginating for more results- const { page, mediaType, q } = params- const sessionId = rootState.user.usageSessionIdif (!page) {+ const sessionId = rootState.user.usageSessionIdawait dispatch(`${USAGE_DATA}/${SEND_SEARCH_QUERY_EVENT}`,- { query: q, sessionId },+ { query: queryParams.q, sessionId },{ root: true })}+ const mediaType = rootState.search.query.mediaTypecommit(FETCH_START_MEDIA, { mediaType })- if (!params.page) {+ if (!page) {commit(RESET_MEDIA, { mediaType })}- const queryParams = prepareSearchQueryParams({- ...rootGetters['search/searchQueryParams'],- ...params,- })- if (!Object.keys(services).includes(mediaType)) {- throw new Error(`Cannot fetch unknown media type "${mediaType}"`)- }await services[mediaType].search(queryParams).then(({ data }) => {@@ -103,7 +111,7 @@ export const createActions = (services) => ({media: data.results,mediaCount,pageCount: data.page_count,- shouldPersistMedia: params.shouldPersistMedia,+ shouldPersistMedia,page: page,})dispatch(HANDLE_NO_MEDIA, { mediaType, mediaCount })@@ -224,45 +232,56 @@ export const getters = {* @return {import('./types').MediaStoreResult}*/results(state, getters, rootState) {- return state.results[rootState.search.query.mediaType]+ return state.results[rootState.search.query.mediaType] || null},/*** Search fetching state for selected media type.* @param {import('./types').MediaState} state* @param getters- * @param rootState- * @returns {import('./types').FetchingState}+ * @returns {import('./types').fetchState}*/- fetchingState(state, getters, rootState) {- return state.fetchingState[rootState.search.query.mediaType]+ fetchState(state, getters) {+ return (+ state.fetchState[getters.mediaType] || {+ isFetching: false,+ fetchError: false,+ isFinished: true,+ }+ )+ },+ mediaType(state, getters, rootState) {+ return rootState.search.query.mediaType},/**- * Returns true if all pages from the search result have been shown.- * @param {import('./types').MediaState} state+ * Returns true for media types that are not supported in the API: video and currently audio.+ *+ * @param state* @param getters* @param rootState* @returns {boolean}*/- isFinished(state, getters, rootState) {+ unsupportedMediaType(state, getters, rootState) {+ const mediaType = rootState.search.query.mediaTypereturn (- state.results[rootState.search.query.mediaType].page >=- state.results[rootState.search.query.mediaType].pageCount+ mediaType === VIDEO || (mediaType === AUDIO && !process.env.enableAudio))},}export const mutations = {[FETCH_START_MEDIA](_state, { mediaType }) {- _state.fetchingState[mediaType].isFetching = true- _state.fetchingState[mediaType].fetchingError = null+ _state.fetchState[mediaType].isFetching = true+ _state.fetchState[mediaType].fetchingError = null+ _state.fetchState[mediaType].isFinished = false},[FETCH_END_MEDIA](_state, { mediaType }) {- _state.fetchingState[mediaType].isFetching = false+ _state.fetchState[mediaType].isFetching = false},[FETCH_MEDIA_ERROR](_state, params) {const { mediaType, errorMessage } = params- _state.fetchingState[mediaType].isFetching = false- _state.fetchingState[mediaType].fetchingError = errorMessage+ _state.fetchState[mediaType].isFetching = false+ _state.fetchState[mediaType].fetchingError = errorMessage+ _state.fetchState[mediaType].isFinished = true},[SET_AUDIO](_state, params) {_state.audio = decodeMediaData(params.audio, AUDIO)@@ -285,10 +304,12 @@ export const mutations = {} else {mediaToSet = media}+ const mediaPage = page || 1_state.results[mediaType].items = mediaToSet_state.results[mediaType].count = mediaCount || 0- _state.results[mediaType].page = page || 1+ _state.results[mediaType].page = mediaPage_state.results[mediaType].pageCount = pageCount+ _state.fetchState[mediaType].isFinished = mediaPage >= pageCount},[MEDIA_NOT_FOUND](_state, params) {throw new Error(`Media of type ${params.mediaType} not found`)diff --git a/src/store/search.js b/src/store/search.jsindex 5c1ff07fa..f349499e8 100644--- a/src/store/search.js+++ b/src/store/search.js@@ -242,8 +242,11 @@ export const getters = {* @return {import('./types').ApiQueryParams}*/searchQueryParams: (state) => {+ const params = {}// Ensure that q filter always comes first- const params = { q: state.query.q }+ if (state.query.q.trim() !== '') {+ params.q = state.query.q.trim()+ }// Remove the mediaType parameter, and handle mature filter separatelyconst filterKeys = Object.keys(state.query).filter((key) => !['q', 'mediaType', 'mature'].includes(key)diff --git a/src/store/types.d.ts b/src/store/types.d.tsindex 87c432ef2..f62dd161d 100644--- a/src/store/types.d.ts+++ b/src/store/types.d.ts@@ -108,9 +108,10 @@ export interface Filters {mature: boolean}-export interface FetchingState {+export interface FetchState {isFetching: booleanfetchingError: null | string+ isFinished?: boolean}export interface SearchState {@@ -138,10 +139,16 @@ export interface MediaState {audio: MediaStoreResultimage: MediaStoreResult}- fetchingState: {- audio: FetchingState- image: FetchingState+ fetchState: {+ audio: FetchState+ image: FetchState}audio: Object | AudioDetailimage: Object | ImageDetail}++export interface MediaFetchState {+ isFetching: boolean+ fetchingError: string | null+ isFinished?: boolean+}diff --git a/src/utils/get-legacy-source-url.js b/src/utils/get-legacy-source-url.jsindex 40d65f157..c645e1e8c 100644--- a/src/utils/get-legacy-source-url.js+++ b/src/utils/get-legacy-source-url.js@@ -150,10 +150,9 @@ export const legacySourceMap = {return {url: 'https://commons.wikimedia.org/w/index.php',query: {- sort: 'relevance',- search: `${search.q} filetype:audio`,- title: 'Special:Search',- 'advancedSearch-current': '{"fields":{"filetype":"audio"}}',+ search: `${search.q}`,+ title: 'Special:MediaSearch',+ type: 'audio',},}},@@ -161,10 +160,9 @@ export const legacySourceMap = {return {url: 'https://commons.wikimedia.org/w/index.php',query: {- sort: 'relevance',- search: `${search.q} filetype:video`,- title: 'Special:Search',- 'advancedSearch-current': '{"fields":{"filetype":"audio"}}',+ search: `${search.q}`,+ title: 'Special:MediaSearch',+ type: 'video',},}},diff --git a/test/e2e/content-types.spec.js b/test/e2e/content-types.spec.jsnew file mode 100644index 000000000..643fd3199--- /dev/null+++ b/test/e2e/content-types.spec.js@@ -0,0 +1,164 @@+const { test, expect } = require('@playwright/test')++/**+ * Using SSR:+ * 1. Can open 'all' tab, and see Meta, image grid and Meta search form.+ * 2. Can open 'image' tab, and see Meta, image grid and Meta search form.+ * 3. Can open 'audio' tab, and see Meta, audio grid and Meta search form.+ * 4. Can open 'video' tab, and see Meta, and Meta search form.+ *+ * On client side:+ * 1. Can open 'all' tab, and see Meta, image grid and Meta search form; can load more images.+ * 2. Can open 'image' tab, and see Meta, image grid and Meta search form; can load more images.+ * 3. Can open 'audio' page, and see Meta, audio grid and Meta search form; can not (currently) load more audios.+ * 4. Can open 'video' page, and see Meta, and Meta search form; can not see load more button.+ */++test.beforeEach(async ({ context }) => {+ // Block any image or audio (jamendo.com) requests for each test in this file.+ await context.route(/\.(png|jpeg|jpg|svg)$/, (route) => route.abort())+ await context.route('**.jamendo.com**', (route) => route.abort())++ // Replace all the thumbnail requests with a single sample image+ await context.route(+ 'https://api.openverse.engineering/v1/thumbs/**',+ (route) => route.fulfill({ path: 'test/e2e/resources/sample_image.jpg' })+ )+ // Serve mock data on all image search requests+ await context.route(+ 'https://api.openverse.engineering/v1/images/**',+ (route) => route.fulfill({ path: 'test/e2e/resources/mock_data.json' })+ )+})++const contentTypes = [+ {+ id: 'all',+ name: 'All',+ url: '/search/?q=cat',+ supported: true,+ sources: 5,+ },+ {+ id: 'image',+ name: 'Image',+ url: '/search/image?q=cat',+ supported: true,+ sources: 5,+ },+ {+ id: 'audio',+ name: 'Audio',+ url: '/search/audio?q=cat',+ supported: true,+ sources: 5,+ },+ {+ id: 'video',+ name: 'Video',+ url: '/search/video?q=cat',+ supported: false,+ sources: 4,+ },+]++for (const [i, contentType] of contentTypes.entries()) {+ test(`Can open ${contentType.name} page on SSR`, async ({ page }) => {+ await page.goto(contentType.url)++ // Selected content page+ const currentTabLabel = await page+ .locator('[aria-current="page"]')+ .textContent()++ expect(currentTabLabel.trim()).toEqual(contentType.name)++ // Meta data+ if (contentType.supported) {+ const searchMetaData = await page.locator('[data-testid="search-meta"]')++ await expect(searchMetaData).toContainText(+ contentType.id === 'all' ? 'image results' : `${contentType.id} results`+ )+ await expect(searchMetaData).toContainText('Are these results relevant')+ await expect(searchMetaData).toContainText('Safer Browsing')++ const searchResult = await page.locator('[data-testid="search-results"]')+ await expect(searchResult).toBeVisible()+ await expect(searchResult).not.toBeEmpty()+ }++ // Load more+ if (contentType.supported) {+ const loadMoreSection = await page.locator('[data-testid="load-more"]')+ await expect(loadMoreSection).toHaveCount(1)+ const expectedText =+ contentType.id === 'audio' ? 'No more audio' : 'Load more'+ await expect(loadMoreSection).toContainText(expectedText)+ } else {+ await expect(page.locator('[data-testid="load-more"]')).toHaveCount(0)+ }++ // MetaSearch form+ const metaSearchFormText = contentType.supported+ ? "Not finding what you're looking for? Try additional"+ : 'Openverse does not yet support built-in '+ const metaSearchForm = await page.locator(`text=${metaSearchFormText}`)+ await expect(metaSearchForm).toHaveCount(1)++ const sourceButtons = await page.locator('.meta-search a')+ await expect(sourceButtons).toHaveCount(contentType.sources)+ })+ test(`Can open ${contentType.name} page client-side`, async ({ page }) => {+ const pageToOpen = (i + 1) % contentTypes.length+ await page.goto(contentTypes[pageToOpen].url)++ await page.click(`[role="tab"]:has-text("${contentType.name}")`)+ const urlParam = contentType.id === 'all' ? '' : contentType.id+ const expectedURL = `/search/${urlParam}?q=cat`+ await expect(page).toHaveURL(expectedURL)++ // Selected content page+ const currentTabLabel = await page+ .locator('[aria-current="page"]')+ .textContent()++ expect(currentTabLabel.trim()).toEqual(contentType.name)++ // Meta data+ if (contentType.supported) {+ const searchMetaData = await page.locator('[data-testid="search-meta"]')++ await expect(searchMetaData).toContainText(+ contentType.id === 'all' ? 'image results' : `${contentType.id} results`+ )+ await expect(searchMetaData).toContainText('Are these results relevant')+ await expect(searchMetaData).toContainText('Safer Browsing')++ const searchResult = await page.locator('[data-testid="search-results"]')+ await expect(searchResult).toBeVisible()+ await expect(searchResult).not.toBeEmpty()+ }++ // Load more+ if (contentType.supported) {+ const loadMoreSection = await page.locator('[data-testid="load-more"]')+ await expect(loadMoreSection).toHaveCount(1)+ const expectedText =+ contentType.id === 'audio' ? 'No more audio' : 'Load more'+ await expect(loadMoreSection).toContainText(expectedText)+ } else {+ await expect(page.locator('[data-testid="load-more"]')).toHaveCount(0)+ }++ // MetaSearch form+ const metaSearchFormText = contentType.supported+ ? "Not finding what you're looking for? Try additional"+ : 'Openverse does not yet support built-in '+ const metaSearchForm = await page.locator(`text=${metaSearchFormText}`)+ await expect(metaSearchForm).toHaveCount(1)++ const sourceButtons = await page.locator('.meta-search a')+ await expect(sourceButtons).toHaveCount(contentType.sources)+ })+}diff --git a/test/e2e/homepage.spec.js b/test/e2e/homepage.spec.jsindex ccc42ff81..88b046ada 100644--- a/test/e2e/homepage.spec.js+++ b/test/e2e/homepage.spec.js@@ -6,16 +6,28 @@ test('can change type and search for audio/modification from homepage', async ({}) => {// Go to http://localhost:8444/await page.goto('/')- // Click text=Audioawait page.click('text=Audio')- // Check text=Modify or adapt >> input[name="lt"]await page.check('text=Modify or adapt >> input[name="licenseType"]')- // Click [placeholder="Search all content"]await page.click('[placeholder="Search all content"]')- // Fill [placeholder="Search all content"]await page.fill('[placeholder="Search all content"]', 'cat')- // Click button:has-text("Search")await page.click('button:has-text("Search")')const expectedUrl = baseURL + '/search/audio?q=cat&license_type=modification'await expect(page).toHaveURL(expectedUrl)})++test('can search for images from homepage, and then load more results', async ({+ page,+ baseURL,+}) => {+ // Go to http://localhost:8444/+ await page.goto('/')+ await page.click('[placeholder="Search all content"]')+ await page.fill('[placeholder="Search all content"]', 'cat')+ await page.click('button:has-text("Search")')+ const expectedUrl = baseURL + '/search/image?q=cat'+ await expect(page).toHaveURL(expectedUrl)++ await expect(page.locator('img')).toHaveCount(20)+ await page.click('button:has-text("Load more")')+ await expect(page.locator('img')).toHaveCount(40)+})diff --git a/test/e2e/search.spec.js b/test/e2e/search.spec.jsindex 3560b9fe5..36741e014 100644--- a/test/e2e/search.spec.js+++ b/test/e2e/search.spec.js@@ -19,32 +19,31 @@ test.beforeEach(async ({ context }) => {)})-// TODO(obulat): Fix the search metadata before search-// This test currently passes, although everything should be the oppositetest('does not show an error message before search', async ({ page }) => {await page.goto('/search')// The search meta data under the search input, should not be shown if no// media had been fetched- await expect(page.locator('span:has-text("No image results")')).toHaveCount(1)+ await expect(page.locator('text=No image results')).not.toBeVisible()// Load more button, should not be shown if the `q` parameter is not setawait expect(page.locator('button:has-text("Load more results")'))// There should be no error messages when no search has been doneawait expect(page.locator('[data-testid="search-grid"] h4')).toHaveCount(1)- await expect(page.locator('text=No image results for')).toHaveCount(1)})test('shows search result metadata', async ({ page }) => {- await page.goto('/search/image?source=rijksmuseum&q=cat')+ await page.goto('/search/image?q=cat&source=rijksmuseum')await page.route('https://api.openverse.engineering/v1/images/**', (route) =>route.fulfill({ path: 'test/e2e/resources/last_page.json' }))// Expect results meta- // Flaky test. Is there a way to mock the first api result?- await expect(page.locator('text=41 image results')).toHaveCount(1)+ // Flaky test. Is there a way to mock the first api result when loading on the server?+ await expect(page.locator('.results-meta span.pe-6')).toContainText(+ /image results/+ )await expect(page.locator('text=Are these results relevant?')).toHaveCount(1)// Click load more button@@ -52,6 +51,9 @@ test('shows search result metadata', async ({ page }) => {await expect(loadMoreButton).toHaveCount(1)await loadMoreButton.click()+ // Click load more button+ await expect(loadMoreButton).toHaveCount(1)+ await loadMoreButton.click()// All search results have been shown, cannot load moreawait expect(loadMoreButton).toHaveCount(0)})@@ -60,7 +62,8 @@ test('navigates to the image detail page correctly', async ({ page }) => {await page.goto('/search/image?q=honey')const figure = page.locator('figure').first()const imgTitle = await figure.locator('img').getAttribute('alt')- await figure.click()++ await page.locator('figure a').first().click()await expect(page.locator('h1')).toHaveText(imgTitle)// Renders the breadcrumb linkawait expect(page.locator('text="Back to search results"')).toBeVisible()diff --git a/test/unit/specs/components/__snapshots__/filter-display.spec.js.snap b/test/unit/specs/components/__snapshots__/filter-display.spec.js.snapindex 5ece84e3a..8402e6b7a 100644--- a/test/unit/specs/components/__snapshots__/filter-display.spec.js.snap+++ b/test/unit/specs/components/__snapshots__/filter-display.spec.js.snap@@ -3,7 +3,7 @@exports[`FilterDisplay should render correct contents 1`] = `<divaria-live="polite"- class="flex flex-wrap items-center p-4"+ class="flex flex-wrap items-center px-6"><spanclass="me-2 font-semibold mb-2"diff --git a/test/unit/specs/components/hero-section.spec.js b/test/unit/specs/components/hero-section.spec.jsindex 2ffcc7670..f1ebe5b5b 100644--- a/test/unit/specs/components/hero-section.spec.js+++ b/test/unit/specs/components/hero-section.spec.js@@ -6,7 +6,7 @@ import clonedeep from 'lodash.clonedeep'import VueI18n from 'vue-i18n'import messages from '~/locales/en.json'import { IMAGE } from '~/constants/media'-import HeroSection from '~/components/HeroSection'+import VHeroSection from '~/components/VHeroSection'import VCheckbox from '~/components/VCheckbox'const i18n = new VueI18n({@@ -15,7 +15,7 @@ const i18n = new VueI18n({messages: { en: messages },})-describe('HeroSection', () => {+describe('VHeroSection', () => {let options = {}let localVuelet storeMock@@ -53,12 +53,12 @@ describe('HeroSection', () => {}})it('should render correct contents', () => {- render(HeroSection, options)+ render(VHeroSection, options)screen.getByRole('search')})it('should search when a query is entered', async () => {- render(HeroSection, options)+ render(VHeroSection, options)const searchBox = screen.getByRole('searchbox')await fireEvent.update(searchBox, 'me')diff --git a/test/unit/specs/components/image-grid.spec.js b/test/unit/specs/components/image-grid.spec.jsindex c4ee2a45b..d874fbf80 100644--- a/test/unit/specs/components/image-grid.spec.js+++ b/test/unit/specs/components/image-grid.spec.js@@ -8,6 +8,10 @@ const propsData = {{ id: 'i3', url: 'http://localhost:8080/i3.svg', title: 'image3' },],canLoadMore: false,+ fetchState: {+ isFetching: false,+ fetchingError: null,+ },}const options = {props: propsData,@@ -38,7 +42,7 @@ describe('ImageGrid', () => {it('shows LoadingIcon instead of LoadMoreButton when isFetching', async () => {options.props.canLoadMore = true- options.props.isFetching = true+ options.props.fetchState.isFetching = truerender(ImageGrid, options)// getByRole('button') does not find the buttonexpect(screen.getByText('browse-page.load')).not.toBeVisible()diff --git a/test/unit/specs/components/scroll-button.spec.js b/test/unit/specs/components/scroll-button.spec.jsindex 6e233d4e2..a22f690b2 100644--- a/test/unit/specs/components/scroll-button.spec.js+++ b/test/unit/specs/components/scroll-button.spec.js@@ -1,26 +1,11 @@-import ScrollButton from '~/components/ScrollButton'-import render from '../../test-utils/render'+import VScrollButton from '~/components/VScrollButton'+import { render, screen } from '@testing-library/vue'describe('Scroll button', () => {- let props = null- let options = null-- beforeEach(() => {- props = {- showBtn: false,- }- options = { propsData: props }- })-- it('should not be rendered at first', () => {- const wrapper = render(ScrollButton, options)- expect(wrapper.find('button').vm).not.toBeDefined()- })-- it('should be rendered when window scrolls further', () => {- options.propsData.showBtn = true- const scrollBtn = render(ScrollButton, options).find('button')- expect(scrollBtn).toBeDefined()- expect(scrollBtn.isVisible()).toBe(true)+ it('should render a scroll button', () => {+ const { container } = render(VScrollButton)+ expect(screen.getByRole('button')).toBeTruthy()+ expect(screen.getByLabelText(/scroll/i)).toBeTruthy()+ expect(container.querySelectorAll('svg').length).toEqual(1)})})diff --git a/test/unit/specs/components/search-grid-wrapper.spec.js b/test/unit/specs/components/search-grid-wrapper.spec.jsdeleted file mode 100644index fe14ea3c5..000000000--- a/test/unit/specs/components/search-grid-wrapper.spec.js+++ /dev/null@@ -1,39 +0,0 @@-import SearchGrid from '~/components/SearchGrid'-import render from '../../test-utils/render'-import { createLocalVue } from '@vue/test-utils'-import Vuex from 'vuex'--const localVue = createLocalVue()-localVue.use(Vuex)-const storeMock = new Vuex.Store({- modules: {- search: {- namespaced: true,- state: {- query: { q: 'foo' },- filters: {- licenseTypes: [- { code: 'commercial', name: 'Commercial usage' },- { code: 'modification', name: 'Allows modification' },- ],- },- },- },- },-})--const options = {- stubs: {- ScrollButton: true,- SearchGridManualLoad: true,- },- localVue,- store: storeMock,-}--describe('Search Grid Wrapper', () => {- it('renders correct content', () => {- const wrapper = render(SearchGrid, options)- expect(wrapper.find('[data-testid="search-grid"]').element).toBeDefined()- })-})diff --git a/test/unit/specs/components/search-grid.spec.js b/test/unit/specs/components/search-grid.spec.jsindex 2b3d9a5ae..f39059c70 100644--- a/test/unit/specs/components/search-grid.spec.js+++ b/test/unit/specs/components/search-grid.spec.js@@ -1,19 +1,17 @@-import SearchGrid from '~/components/SearchGridManualLoad'-import render from '../../test-utils/render'-import Vuex from 'vuex'+import { render, screen } from '@testing-library/vue'import { IMAGE } from '~/constants/media'import { createLocalVue } from '@vue/test-utils'import VueI18n from 'vue-i18n'import messages from '~/locales/en.json'-import SaferBrowsing from '~/components/SaferBrowsing'-import SearchGridCell from '~/components/SearchGridCell'-describe('SearchGrid', () => {++import VSearchGrid from '~/components/VSearchGrid'++describe('VSearchGrid', () => {let options = {}const localVue = createLocalVue()localVue.use(Vuex)localVue.use(VueI18n)- localVue.component('SearchGridCell', SearchGridCell)let storeMockconst i18n = new VueI18n({@@ -21,11 +19,6 @@ describe('SearchGrid', () => {fallbackLocale: 'en',messages: { en: messages },})- localVue.prototype.$nuxt = {- nbFetching: 0,- }- localVue.component('SaferBrowsing', SaferBrowsing)-beforeEach(() => {storeMock = new Vuex.Store({modules: {@@ -60,7 +53,7 @@ describe('SearchGrid', () => {},},getters: {- fetchingState: () => ({+ fetchState: () => ({isFetching: false,fetchingError: null,}),@@ -82,26 +75,48 @@ describe('SearchGrid', () => {stubs: {// SearchRating: true,LoadingIcon: true,- MetaSearchForm: true,+ VMetaSearchForm: true,NuxtLink: true,// SaferBrowsing: true,VLicense: true,},+ mocks: {+ $nuxt: {+ context: {+ store: storeMock,+ i18n,+ },+ nbFetching: 0,+ },+ },+ propsData: {+ supported: true,+ query: { q: 'foo', mediaType: IMAGE },+ searchType: 'image',+ fetchState: {+ isFetching: false,+ isFinished: true,+ },+ resultsCount: 40,+ },store: storeMock,localVue,i18n,}})- it('should render correct contents', () => {- const wrapper = render(SearchGrid, options)- expect(wrapper.find('section').element).toBeDefined()- expect(wrapper.find('.load-more').element).toBeDefined()- })+ it('should render correct contents', async () => {+ render(VSearchGrid, options)- it("doesn't render load more button if not loading images", () => {- const wrapper = render(SearchGrid, options)- expect(wrapper.find('.load-more').element).toBeDefined()+ // Meta information+ // Result count+ screen.getByText(/40 image results/)+ // Search rating+ screen.getByText(/search-rating.content/)+ screen.getAllByRole('button', { text: /yes/i })+ screen.getAllByRole('button', { text: /no/i })+ // Safer browsing+ screen.getAllByRole('button', { text: /safer-browsing/i })})// Fetching states should be tested with e2e tests})diff --git a/test/unit/specs/components/search-rating.spec.js b/test/unit/specs/components/search-rating.spec.jsindex 6ae7a92cf..81aba8f5a 100644--- a/test/unit/specs/components/search-rating.spec.js+++ b/test/unit/specs/components/search-rating.spec.js@@ -1,9 +1,9 @@-import SearchRating from '~/components/SearchRating'+import VSearchRating from '~/components/VSearchRating'import render from '../../test-utils/render'import { USAGE_DATA } from '~/constants/store-modules'import { SEND_SEARCH_RATING_EVENT } from '~/constants/usage-data-analytics-types'-describe('SearchRating', () => {+describe('VSearchRating', () => {let options = {}let dispatchMock = null@@ -22,19 +22,19 @@ describe('SearchRating', () => {})it('should render rating button', async () => {- const wrapper = render(SearchRating, options)+ const wrapper = render(VSearchRating, options)expect(wrapper.find('.rating').element).toBeDefined()})it('does not render rating button after clicking it', async () => {- const wrapper = render(SearchRating, options)+ const wrapper = render(VSearchRating, options)const button = wrapper.find('.rating-yes')await button.trigger('click')expect(wrapper.find('.rating-yes').element).toBeUndefined()})it('dispatches SEND_SEARCH_RATING_EVENT when clicking rating button', async () => {- const wrapper = render(SearchRating, options)+ const wrapper = render(VSearchRating, options)const button = wrapper.find('.rating')await button.trigger('click')@@ -48,7 +48,7 @@ describe('SearchRating', () => {})it('dispatches SEND_SEARCH_RATING_EVENT when clicking rating button with relevant as false', async () => {- const wrapper = render(SearchRating, options)+ const wrapper = render(VSearchRating, options)const button = wrapper.findAll('.rating').wrappers[1]await button.trigger('click')@@ -62,14 +62,14 @@ describe('SearchRating', () => {})it('should render thanks message after clicking the rating button', async () => {- const wrapper = render(SearchRating, options)+ const wrapper = render(VSearchRating, options)const button = wrapper.find('.rating')await button.trigger('click')expect(wrapper.find('.thank-you').element).toBeDefined()})it('renders neither rating button nor thanks message 1.5s after clicking rating button', async (done) => {- const wrapper = render(SearchRating, options)+ const wrapper = render(VSearchRating, options)const button = wrapper.find('.rating-no')await button.trigger('click')diff --git a/test/unit/specs/store/media-store.spec.js b/test/unit/specs/store/media-store.spec.jsindex 9700043a9..98e402f8e 100644--- a/test/unit/specs/store/media-store.spec.js+++ b/test/unit/specs/store/media-store.spec.js@@ -39,13 +39,15 @@ describe('Search Store', () => {page: undefined,pageCount: 0,})- expect(state.fetchingState.audio).toEqual({+ expect(state.fetchState.audio).toEqual({fetchingError: null,isFetching: false,+ isFinished: false,})- expect(state.fetchingState.image).toEqual({+ expect(state.fetchState.image).toEqual({fetchingError: null,isFetching: false,+ isFinished: false,})expect(state.audio).toEqual({})expect(state.image).toEqual({})@@ -63,14 +65,14 @@ describe('Search Store', () => {it('FETCH_START_MEDIA updates state', () => {mutations[FETCH_START_MEDIA](state, { mediaType: IMAGE })- expect(state.fetchingState.image.isFetching).toBeTruthy()- expect(state.fetchingState.image.fetchingError).toBeFalsy()+ expect(state.fetchState.image.isFetching).toBeTruthy()+ expect(state.fetchState.image.fetchingError).toBeFalsy()})it('FETCH_END_MEDIA updates state', () => {mutations[FETCH_END_MEDIA](state, { mediaType: IMAGE })- expect(state.fetchingState.image.isFetching).toBeFalsy()+ expect(state.fetchState.image.isFetching).toBeFalsy()})it('FETCH_MEDIA_ERROR updates state', () => {@@ -79,9 +81,9 @@ describe('Search Store', () => {errorMessage: 'error',})- expect(state.fetchingState.image.isFetching).toBeFalsy()- expect(state.fetchingState.image.fetchingError).toBeTruthy()- expect(state.fetchingState.image.fetchingError).toBe('error')+ expect(state.fetchState.image.isFetching).toBeFalsy()+ expect(state.fetchState.image.fetchingError).toBeTruthy()+ expect(state.fetchState.image.fetchingError).toBe('error')})it('SET_AUDIO updates state', () => {@@ -221,29 +223,20 @@ describe('Search Store', () => {dispatch: jest.fn(),rootState: {user: { usageSessionId: 'foo' },- search: { query: { q: 'cat' } },+ search: { query: { q: 'cat', mediaType: IMAGE } },+ },+ rootGetters: {+ search: { searchQueryParams: () => ({ q: 'cat', mediaType: IMAGE }) },},- rootGetters: { search: { searchQueryParams: () => {} } },state: state,}})- it('FETCH_MEDIA throws an error on unknown media type', async () => {- const action = createActions(services)[FETCH_MEDIA]- const params = {- mediaType: 'unknown',- page: 1,- }- await expect(action(context, params)).rejects.toThrow(- 'Cannot fetch unknown media type "unknown"'- )- })-it('FETCH_MEDIA on success', async () => {const params = {q: 'foo',page: 1,- mediaType: IMAGE,+ shouldPersistMedia: true,}const action = createActions(services)[FETCH_MEDIA]await action(context, params)@@ -285,7 +278,6 @@ describe('Search Store', () => {q: 'foo',page: 1,shouldPersistMedia: false,- mediaType: IMAGE,}const action = createActions(services)[FETCH_MEDIA]await action(context, params)