Skip to content

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

Search and media store refactoring (#398)

Olga Bulatef53f1d557b7
diff --git a/src/components/AudioDetails/Tags.vue b/src/components/AudioDetails/Tags.vue
index ae3b66224..532a2f81c 100644
--- a/src/components/AudioDetails/Tags.vue
+++ b/src/components/AudioDetails/Tags.vue
@@ -17,9 +17,9 @@
</template>
<script>
-import { SET_Q } from '~/constants/mutation-types'
+import { UPDATE_QUERY } from '~/constants/action-types'
import { SEARCH } from '~/constants/store-modules'
-import { mapMutations } from 'vuex'
+import { mapActions } from 'vuex'
export default {
name: 'AudioTags',
@@ -30,7 +30,7 @@ export default {
},
},
methods: {
- ...mapMutations(SEARCH, { setSearchTerm: SET_Q }),
+ ...mapActions(SEARCH, { setSearchTerm: UPDATE_QUERY }),
isClarifaiTag(provider) {
return provider === 'clarifai'
},
diff --git a/src/components/AudioResultsList.vue b/src/components/AudioResultsList.vue
index 4d87c7916..fb524fbe9 100644
--- a/src/components/AudioResultsList.vue
+++ b/src/components/AudioResultsList.vue
@@ -1,22 +1,22 @@
<template>
<section>
- <div v-show="!isFetching" class="results-meta">
+ <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 in audios"
+ v-for="audio in results.items"
:key="audio.id"
:audio="audio"
:size="audioTrackSize"
layout="row"
/>
</div>
- <div v-if="!isFetchingError" class="load-more">
+ <div v-if="!fetchingState.fetchingError" class="load-more">
<button
- v-show="!isFetching"
+ v-show="!fetchingState.isFetching"
class="button"
:disabled="isFinished"
@click="onLoadMoreAudios"
@@ -29,16 +29,19 @@
}}</span>
<span v-else>{{ $t('browse-page.load') }}</span>
</button>
- <LoadingIcon v-show="isFetching" />
+ <LoadingIcon v-show="fetchingState.isFetching" />
</div>
- <div v-if="isFetchingError" class="m-auto w-1/2 text-center pt-6">
+ <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'),
})
}}
- {{ errorMessage }}
+ {{ fetchingState.fetchingError }}
</h5>
</div>
</section>
@@ -48,12 +51,12 @@
import { mapActions, mapGetters, mapState } from 'vuex'
import { FETCH_MEDIA } from '~/constants/action-types'
import { AUDIO } from '~/constants/media'
-import { FILTER, SEARCH } from '~/constants/store-modules'
+import { MEDIA, SEARCH } from '~/constants/store-modules'
export default {
name: 'AudioResultsList',
async fetch() {
- if (!this.audios.length) {
+ if (!this.results.items.length) {
await this.fetchMedia({
...this.query,
mediaType: AUDIO,
@@ -61,41 +64,29 @@ export default {
}
},
computed: {
- ...mapState(SEARCH, [
- 'audios',
- 'errorMessage',
- 'audiosCount',
- 'audioPage',
- 'pageCount',
- 'query',
- ]),
- ...mapGetters(SEARCH, ['isFetching', 'isFetchingError']),
- ...mapState(FILTER, ['isFilterVisible']),
+ ...mapState(SEARCH, ['query', 'isFilterVisible']),
+ ...mapGetters(MEDIA, ['fetchingState', 'results', 'isFinished']),
_audiosCount() {
- const count = this.audiosCount
+ const count = this.results.count
if (count === 0) {
return this.$t('browse-page.audio-no-results')
}
- return count >= 10000
- ? this.$tc('browse-page.audio-result-count-more', count, {
- localeCount: count.toLocaleString(this.$i18n.locale),
- })
- : this.$tc('browse-page.audio-result-count', count, {
- localeCount: count.toLocaleString(this.$i18n.locale),
- })
- },
- isFinished() {
- return this.audioPage >= this.pageCount.audio
+ 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(SEARCH, { fetchMedia: FETCH_MEDIA }),
+ ...mapActions(MEDIA, { fetchMedia: FETCH_MEDIA }),
onLoadMoreAudios() {
const searchParams = {
- page: this.audioPage + 1,
+ page: this.results.page + 1,
shouldPersistMedia: true,
...this.query,
}
diff --git a/src/components/EmbeddedNavSection.vue b/src/components/EmbeddedNavSection.vue
index 529582e73..fbfd41605 100644
--- a/src/components/EmbeddedNavSection.vue
+++ b/src/components/EmbeddedNavSection.vue
@@ -124,10 +124,10 @@
</template>
<script>
-import { SET_Q } from '~/constants/mutation-types'
+import { UPDATE_QUERY } from '~/constants/action-types'
import Dropdown from '~/components/Dropdown'
import { SEARCH } from '~/constants/store-modules'
-import { mapMutations } from 'vuex'
+import { mapActions } from 'vuex'
export default {
name: 'EmbeddedNavSection',
@@ -144,7 +144,7 @@ export default {
},
},
methods: {
- ...mapMutations(SEARCH, { setSearchTerm: SET_Q }),
+ ...mapActions(SEARCH, { setSearchTerm: UPDATE_QUERY }),
onSubmit() {
const q = this.form.searchTerm
this.setSearchTerm({ q })
diff --git a/src/components/Filters/FilterChecklist.vue b/src/components/Filters/FilterChecklist.vue
index 63172ed82..011076cee 100644
--- a/src/components/Filters/FilterChecklist.vue
+++ b/src/components/Filters/FilterChecklist.vue
@@ -150,7 +150,7 @@ export default {
this.licenseExplanationVisible = false
},
getFilterTypeValue(filterKey, val) {
- return this.$store.state.filter.filters[filterKey].filter((item) =>
+ return this.$store.state.search.filters[filterKey].filter((item) =>
item.code.includes(val)
)
},
diff --git a/src/components/Filters/FilterDisplay.vue b/src/components/Filters/FilterDisplay.vue
index 907dae62e..282c3d519 100644
--- a/src/components/Filters/FilterDisplay.vue
+++ b/src/components/Filters/FilterDisplay.vue
@@ -19,17 +19,17 @@
import { TOGGLE_FILTER } from '~/constants/action-types'
import FilterTag from '~/components/Filters/FilterTag'
import { mapGetters } from 'vuex'
-import { FILTER } from '~/constants/store-modules'
+import { SEARCH } from '~/constants/store-modules'
export default {
name: 'FilterDisplay',
components: { FilterTag },
computed: {
- ...mapGetters(FILTER, ['appliedFilterTags', 'isAnyFilterApplied']),
+ ...mapGetters(SEARCH, ['appliedFilterTags', 'isAnyFilterApplied']),
},
methods: {
onUpdateFilter({ code, filterType }) {
- this.$store.dispatch(`${FILTER}/${TOGGLE_FILTER}`, { code, filterType })
+ this.$store.dispatch(`${SEARCH}/${TOGGLE_FILTER}`, { code, filterType })
},
},
}
diff --git a/src/components/Filters/FiltersList.vue b/src/components/Filters/FiltersList.vue
index f69121070..352986044 100644
--- a/src/components/Filters/FiltersList.vue
+++ b/src/components/Filters/FiltersList.vue
@@ -49,11 +49,10 @@
</template>
<script>
-import { mapGetters, mapState } from 'vuex'
+import { mapGetters } from 'vuex'
import { kebabize } from '~/utils/format-strings'
-import { AUDIO, IMAGE, VIDEO } from '~/constants/media'
+import { SEARCH } from '~/constants/store-modules'
import FilterChecklist from './FilterChecklist'
-import { FILTER, SEARCH } from '~/constants/store-modules'
export default {
name: 'FiltersList',
@@ -61,25 +60,9 @@ export default {
FilterChecklist,
},
computed: {
- ...mapState(SEARCH, ['searchType']),
- ...mapGetters(FILTER, [
- 'audioFiltersForDisplay',
- 'imageFiltersForDisplay',
- 'videoFiltersForDisplay',
- 'allFiltersForDisplay',
- 'isAnyFilterApplied',
- ]),
+ ...mapGetters(SEARCH, ['mediaFiltersForDisplay', 'isAnyFilterApplied']),
filters() {
- switch (this.searchType) {
- case AUDIO:
- return this.audioFiltersForDisplay
- case IMAGE:
- return this.imageFiltersForDisplay
- case VIDEO:
- return this.videoFiltersForDisplay
- default:
- return this.allFiltersForDisplay
- }
+ return this.mediaFiltersForDisplay || {}
},
filterTypes() {
return Object.keys(this.filters)
diff --git a/src/components/Filters/SearchGridFilter.vue b/src/components/Filters/SearchGridFilter.vue
index 2120fe751..ecdebca76 100644
--- a/src/components/Filters/SearchGridFilter.vue
+++ b/src/components/Filters/SearchGridFilter.vue
@@ -16,21 +16,21 @@ import {
CLEAR_FILTERS,
} from '~/constants/mutation-types'
import { TOGGLE_FILTER } from '~/constants/action-types'
-import { FILTER } from '~/constants/store-modules'
+import { SEARCH } from '~/constants/store-modules'
import FiltersList from '~/components/Filters/FiltersList'
export default {
name: 'SearchGridFilter',
components: { FiltersList },
computed: {
- ...mapState(FILTER, ['filters', 'isFilterVisible']),
+ ...mapState(SEARCH, ['filters', 'isFilterVisible']),
},
methods: {
- ...mapActions(FILTER, {
+ ...mapActions(SEARCH, {
toggleFilter: TOGGLE_FILTER,
clearFilters: CLEAR_FILTERS,
}),
- ...mapMutations(FILTER, {
+ ...mapMutations(SEARCH, {
setFilterVisible: SET_FILTER_IS_VISIBLE,
}),
onUpdateFilter({ code, filterType }) {
diff --git a/src/components/HeroSection.vue b/src/components/HeroSection.vue
index b3564fb33..fec435caa 100644
--- a/src/components/HeroSection.vue
+++ b/src/components/HeroSection.vue
@@ -52,7 +52,7 @@
</template>
</i18n>
</div>
- <HomeLicenseFilter />
+ <HomeLicenseFilter @toggle="toggleFilter" />
</form>
</div>
<img
@@ -65,10 +65,9 @@
</template>
<script>
-import { SET_Q, SET_SEARCH_TYPE } from '~/constants/mutation-types'
-import { filtersToQueryData } from '~/utils/search-query-transform'
+import { UPDATE_QUERY, TOGGLE_FILTER } from '~/constants/action-types'
import { SEARCH } from '~/constants/store-modules'
-import { mapMutations } from 'vuex'
+import { mapActions, mapGetters } from 'vuex'
import HomeLicenseFilter from '~/components/HomeLicenseFilter'
import SearchTypeToggle from '~/components/SearchTypeToggle'
@@ -80,17 +79,21 @@ export default {
*/
data: () => ({
form: { searchTerm: '', searchType: 'image' },
- showSearchType: process.env.enableAudio,
+ filters: { commercial: false, modification: false },
+ showSearchType: process.env.enableAudio || false,
}),
+ computed: {
+ ...mapGetters(SEARCH, ['searchQueryParams']),
+ },
mounted() {
if (document.querySelector('#searchTerm')) {
document.querySelector('#searchTerm').focus()
}
},
methods: {
- ...mapMutations(SEARCH, {
- setSearchTerm: SET_Q,
- setSearchType: SET_SEARCH_TYPE,
+ ...mapActions(SEARCH, {
+ setSearchTerm: UPDATE_QUERY,
+ checkFilter: TOGGLE_FILTER,
}),
getPath() {
if (!process.env.enableAudio) return '/search/image'
@@ -99,22 +102,25 @@ export default {
getMediaType() {
return this.form.searchType
},
+ toggleFilter({ code }) {
+ this.filters[code] = !this.filters[code]
+ },
onSubmit() {
- this.setSearchTerm({ q: this.form.searchTerm })
+ const newQuery = { q: this.form.searchTerm }
+ const checkedFilters = Object.keys(this.filters).filter(
+ (filterName) => !!this.filters[filterName]
+ )
+ checkedFilters.forEach((f) => {
+ this.checkFilter({ filterType: 'licenseTypes', code: f })
+ })
if (process.env.enableAudio) {
- this.setSearchType({ searchType: this.form.searchType })
+ newQuery.searchType = this.form.searchType
}
-
+ this.setSearchTerm(newQuery)
const newPath = this.localePath({
path: this.getPath(),
- query: {
- q: this.form.searchTerm,
- ...filtersToQueryData(
- this.$store.state.filter.filters,
- this.getMediaType()
- ),
- },
+ query: this.searchQueryParams,
})
this.$router.push(newPath)
},
diff --git a/src/components/HomeLicenseFilter.vue b/src/components/HomeLicenseFilter.vue
index ba5e9bc4e..0ed0ec6e9 100644
--- a/src/components/HomeLicenseFilter.vue
+++ b/src/components/HomeLicenseFilter.vue
@@ -3,12 +3,12 @@
<legend>
{{ $t('hero.license-filter.label') }}
</legend>
- <template v-for="(licenseType, index) in licenseTypes">
+ <template v-for="(licenseType, index) in filters">
<label :key="index" class="checkbox" :for="licenseType.code">
<input
:id="licenseType.code"
+ v-model="licenseType.checked"
type="checkbox"
- :checked="licenseType.checked"
name="lt"
:value="licenseType.code"
@change="onFilterChanged(licenseType.code)"
@@ -20,25 +20,25 @@
</template>
<script>
-import { TOGGLE_FILTER } from '~/constants/action-types'
-import { FILTER } from '~/constants/store-modules'
-import { mapActions, mapState } from 'vuex'
-
export default {
name: 'LicenseFilter',
- computed: {
- ...mapState(FILTER, ['filters']),
- licenseTypes() {
- return this.filters.licenseTypes
- },
- },
+ data: () => ({
+ filters: [
+ {
+ code: 'commercial',
+ name: 'filters.license-types.commercial',
+ checked: false,
+ },
+ {
+ code: 'modification',
+ name: 'filters.license-types.modification',
+ checked: false,
+ },
+ ],
+ }),
methods: {
- ...mapActions(FILTER, { toggleFilter: TOGGLE_FILTER }),
onFilterChanged(code) {
- this.toggleFilter({
- code,
- filterType: 'licenseTypes',
- })
+ this.$emit('toggle', { code })
},
},
}
diff --git a/src/components/NavSection.vue b/src/components/NavSection.vue
index 3a979d41e..d0afe94d4 100644
--- a/src/components/NavSection.vue
+++ b/src/components/NavSection.vue
@@ -125,10 +125,10 @@
</template>
<script>
-import { SET_Q } from '~/constants/mutation-types'
+import { UPDATE_QUERY } from '~/constants/action-types'
import Dropdown from '~/components/Dropdown'
import { SEARCH } from '~/constants/store-modules'
-import { mapMutations } from 'vuex'
+import { mapActions } from 'vuex'
export default {
name: 'NavSection',
@@ -145,14 +145,12 @@ export default {
},
},
methods: {
- ...mapMutations(SEARCH, { setSearchTerm: SET_Q }),
+ ...mapActions(SEARCH, { setSearchTerm: UPDATE_QUERY }),
onSubmit() {
- const q = this.form.searchTerm
- const theArgs = { q }
- this.setSearchTerm(theArgs)
+ this.setSearchTerm({ q: this.form.searchTerm })
const newPath = this.localePath({
path: '/search',
- query: { q },
+ query: { q: this.form.searchTerm },
})
this.$router.push(newPath)
},
diff --git a/src/components/PhotoTags.vue b/src/components/PhotoTags.vue
index ca9c2daea..72f1447f9 100644
--- a/src/components/PhotoTags.vue
+++ b/src/components/PhotoTags.vue
@@ -19,9 +19,9 @@
</template>
<script>
-import { SET_Q } from '~/constants/mutation-types'
+import { UPDATE_QUERY } from '~/constants/action-types'
import { SEARCH } from '~/constants/store-modules'
-import { mapMutations } from 'vuex'
+import { mapActions } from 'vuex'
export default {
name: 'PhotoTags',
@@ -32,7 +32,7 @@ export default {
},
},
methods: {
- ...mapMutations(SEARCH, { setSearchTerm: SET_Q }),
+ ...mapActions(SEARCH, { setSearchTerm: UPDATE_QUERY }),
isClarifaiTag(provider) {
return provider === 'clarifai'
},
diff --git a/src/components/SaferBrowsing.vue b/src/components/SaferBrowsing.vue
index c655f9d91..1ef2fa152 100644
--- a/src/components/SaferBrowsing.vue
+++ b/src/components/SaferBrowsing.vue
@@ -43,7 +43,7 @@
import { FocusTrap } from 'focus-trap-vue'
import { TOGGLE_FILTER } from '~/constants/action-types'
import { mapActions } from 'vuex'
-import { FILTER } from '~/constants/store-modules'
+import { SEARCH } from '~/constants/store-modules'
export default {
name: 'SaferBrowsing',
@@ -57,11 +57,11 @@ export default {
},
computed: {
mature() {
- return this.$store.state.filter.filters.mature
+ return this.$store.state.search.filters.mature
},
},
methods: {
- ...mapActions(FILTER, { toggleFilter: TOGGLE_FILTER }),
+ ...mapActions(SEARCH, { toggleFilter: TOGGLE_FILTER }),
toggleShowForm() {
this.showForm = !this.showForm
},
diff --git a/src/components/SearchGridForm.vue b/src/components/SearchGridForm.vue
index 9adc5634a..99e0c624c 100644
--- a/src/components/SearchGridForm.vue
+++ b/src/components/SearchGridForm.vue
@@ -63,14 +63,14 @@
import { SET_FILTER_IS_VISIBLE } from '~/constants/mutation-types'
import { queryStringToSearchType } from '~/utils/search-query-transform'
import { VIDEO } from '~/constants/media'
-import { FILTER, SEARCH } from '~/constants/store-modules'
+import { SEARCH } from '~/constants/store-modules'
import { mapMutations, mapState } from 'vuex'
export default {
name: 'SearchGridForm',
data: () => ({ searchTermsModel: null }),
computed: {
- ...mapState(FILTER, ['isFilterVisible']),
+ ...mapState(SEARCH, ['isFilterVisible']),
...mapState(SEARCH, ['query']),
searchTerms() {
return this.query.q
@@ -93,12 +93,12 @@ export default {
this.setFormInput()
},
methods: {
- ...mapMutations(FILTER, { setFilterIsVisible: SET_FILTER_IS_VISIBLE }),
+ ...mapMutations(SEARCH, { setFilterIsVisible: SET_FILTER_IS_VISIBLE }),
onSubmit(e) {
e.preventDefault()
if (this.searchTermsModel) {
this.$emit('onSearchFormSubmit', {
- query: { q: this.searchTermsModel },
+ q: this.searchTermsModel,
})
this.$refs.search.blur()
}
@@ -107,7 +107,7 @@ export default {
this.searchTermsModel = e.target.value
if (this.activeTab === VIDEO) {
this.$emit('onSearchFormSubmit', {
- query: { q: this.searchTermsModel },
+ q: this.searchTermsModel,
})
}
},
diff --git a/src/components/SearchGridManualLoad.vue b/src/components/SearchGridManualLoad.vue
index 81bf16168..97365580a 100644
--- a/src/components/SearchGridManualLoad.vue
+++ b/src/components/SearchGridManualLoad.vue
@@ -7,7 +7,10 @@
}"
>
<div ref="gridItems" class="search-grid_ctr">
- <div v-show="!isFetching && includeAnalytics" class="results-meta">
+ <div
+ v-show="!fetchingState.isFetching && includeAnalytics"
+ class="results-meta"
+ >
<span class="caption font-semibold">
{{ _imagesCount }}
</span>
@@ -18,13 +21,13 @@
</div>
<div class="search-grid-cells">
<SearchGridCell
- v-for="(image, index) in images"
+ v-for="(image, index) in results.items"
:key="index"
:image="image"
/>
</div>
<div
- v-if="isFetchingError"
+ v-if="!!fetchingState.error"
class="search-grid_notification callout alert"
>
<h5>
@@ -33,24 +36,27 @@
type: $t('browse-page.search-form.audio'),
})
}}
- {{ errorMessage }}
+ {{ fetchingState.fetchingError }}
</h5>
</div>
<div class="pb-6">
- <div v-if="!isFetchingError && !isFinished" class="load-more">
+ <div
+ v-if="!fetchingState.fetchingError && !isFinished"
+ class="load-more"
+ >
<button
- v-show="!isFetching && includeAnalytics"
+ v-show="!fetchingState.isFetching && includeAnalytics"
class="button"
@click="onLoadMoreImages"
@keyup.enter="onLoadMoreImages"
>
<span>{{ $t('browse-page.load') }}</span>
</button>
- <LoadingIcon v-show="isFetching" />
+ <LoadingIcon v-show="fetchingState.isFetching" />
</div>
<MetaSearchForm
type="image"
- :noresult="imagesCount === 0"
+ :noresult="!fetchingState.isFetching && results.count === 0"
:supported="true"
/>
</div>
@@ -60,10 +66,10 @@
<script>
import { FETCH_MEDIA } from '~/constants/action-types'
-import { SET_MEDIA } from '~/constants/mutation-types'
+import { RESET_MEDIA } from '~/constants/mutation-types'
import { IMAGE } from '~/constants/media'
import { mapActions, mapGetters, mapMutations, mapState } from 'vuex'
-import { SEARCH } from '~/constants/store-modules'
+import { MEDIA, SEARCH } from '~/constants/store-modules'
export default {
name: 'SearchGridManualLoad',
@@ -86,42 +92,24 @@ export default {
shouldContainImages: false,
showMetaImageSearch: false,
}),
- async fetch() {
- if (!this.images.length) {
- await this.fetchMedia({
- ...this.query,
- mediaType: IMAGE,
- })
- }
- },
computed: {
- ...mapState(SEARCH, [
- 'imagesCount',
- 'imagePage',
- 'errorMessage',
- 'images',
- 'query',
- ]),
- ...mapGetters(SEARCH, ['isFetching', 'isFetchingError']),
+ ...mapState(SEARCH, ['query']),
+ ...mapGetters(MEDIA, ['fetchingState', 'results', 'isFinished']),
_imagesCount() {
- const count = this.imagesCount
+ const count = this.results.count
if (count === 0) {
return this.$t('browse-page.image-no-results')
}
- return count >= 10000
- ? this.$tc('browse-page.image-result-count-more', count, {
- localeCount: count.toLocaleString(this.$i18n.locale),
- })
- : this.$tc('browse-page.image-result-count', count, {
- localeCount: count.toLocaleString(this.$i18n.locale),
- })
+ 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
},
- isFinished() {
- return this.imagePage >= this.$store.state.search.pageCount.images
- },
},
watch: {
_query: {
@@ -132,14 +120,14 @@ export default {
},
},
methods: {
- ...mapMutations(SEARCH, { setMedia: SET_MEDIA }),
- ...mapActions(SEARCH, { fetchMedia: FETCH_MEDIA }),
+ ...mapMutations(MEDIA, { resetMedia: RESET_MEDIA }),
+ ...mapActions(MEDIA, { fetchMedia: FETCH_MEDIA }),
searchChanged() {
- this.setMedia({ media: [], page: 1 })
+ this.resetMedia({ mediaType: IMAGE })
},
onLoadMoreImages() {
const searchParams = {
- page: this.imagePage + 1,
+ page: this.results.page + 1,
shouldPersistMedia: true,
...this._query,
}
diff --git a/src/constants/action-types.js b/src/constants/action-types.js
index 185a03010..ccbf8be69 100644
--- a/src/constants/action-types.js
+++ b/src/constants/action-types.js
@@ -9,9 +9,10 @@ export const CONVERT_AB_TEST_EXPERIMENT = 'CONVERT_AB_TEST_EXPERIMENT'
export const HANDLE_MEDIA_ERROR = 'HANDLE_MEDIA_ERROR'
export const TOGGLE_FILTER = 'TOGGLE_FILTER'
export const SEND_CONTENT_REPORT = 'SEND_CONTENT_REPORT'
-export const SET_SEARCH_TYPE_FROM_URL = 'SET_SEARCH_TYPE_FROM_URL'
export const UPDATE_SEARCH_TYPE = 'UPDATE_SEARCH_TYPE'
export const HANDLE_NO_MEDIA = 'HANDLE_NO_MEDIA'
export const NOTIFICATION_ACTION = 'NOTIFICATION_ACTION'
export const UPDATE_QUERY = 'UPDATE_QUERY'
-export const SET_FILTERS_FROM_URL = 'SET_FILTERS_FROM_URL'
+export const UPDATE_QUERY_FROM_FILTERS = 'UPDATE_QUERY_FROM_FILTERS'
+export const SET_SEARCH_STATE_FROM_URL = 'SET_SEARCH_STATE_FROM_URL'
+export const SET_MEDIA_TYPE = 'SET_MEDIA_TYPE'
diff --git a/src/constants/mutation-types.js b/src/constants/mutation-types.js
index 7940d5810..456229588 100644
--- a/src/constants/mutation-types.js
+++ b/src/constants/mutation-types.js
@@ -10,11 +10,9 @@ export const CLEAR_FILTERS = 'CLEAR_FILTERS'
export const SET_FILTER_IS_VISIBLE = 'SET_FILTER_IS_VISIBLE'
export const SET_AUDIO = 'SET_AUDIO'
export const SET_IMAGE = 'SET_IMAGE'
-export const SET_IMAGE_PAGE = 'SET_IMAGE_PAGE'
export const SET_MEDIA_PROVIDERS = 'SET_MEDIA_PROVIDERS'
export const SET_PROVIDERS_FILTERS = 'SET_PROVIDERS_FILTERS'
export const SET_MEDIA = 'SET_MEDIA'
-export const SET_QUERY = 'SET_QUERY'
export const REPORT_BUG_START = 'REPORT_BUG_START'
export const REPORT_BUG_END = 'REPORT_BUG_END'
export const REPORT_BUG_FAILED = 'REPORT_BUG_FAILED'
@@ -28,11 +26,10 @@ export const SET_SHOW_NOTIFICATION = 'SET_SHOW_NOTIFICATION'
export const SET_EMBEDDED = 'SET_EMBEDDED'
export const SET_REFERRED = 'SET_REFERRED'
export const SET_SEARCH_TYPE = 'SET_SEARCH_TYPE'
-export const UPDATE_FILTERS = 'UPDATE_FILTERS'
+export const CLEAR_OTHER_MEDIA_TYPE_FILTERS = 'CLEAR_OTHER_MEDIA_TYPE_FILTERS'
export const SET_ACTIVE_MEDIA_ITEM = 'SET_ACTIVE_MEDIA_ITEM'
export const PAUSE_ACTIVE_MEDIA_ITEM = 'PAUSE_ACTIVE_MEDIA_ITEM'
export const EJECT_ACTIVE_MEDIA_ITEM = 'EJECT_ACTIVE_MEDIA_ITEM'
export const RESET_MEDIA = 'RESET_MEDIA'
export const REPLACE_FILTERS = 'REPLACE_FILTERS'
-export const REPLACE_QUERY = 'REPLACE_QUERY'
-export const SET_Q = 'SET_Q'
+export const SET_QUERY = 'SET_QUERY'
diff --git a/src/constants/store-modules.js b/src/constants/store-modules.js
index 5a2f94d9c..593f6e6ba 100644
--- a/src/constants/store-modules.js
+++ b/src/constants/store-modules.js
@@ -7,6 +7,6 @@ export const NAV = 'nav'
export const NOTIFICATION = 'notification'
export const REPORT_CONTENT = 'report-content'
export const USAGE_DATA = 'usage-data'
-export const FILTER = 'filter'
export const SEARCH = 'search'
+export const MEDIA = 'media'
export const BUG_REPORT = 'bug-report'
diff --git a/src/pages/audio/_id.vue b/src/pages/audio/_id.vue
index 211cccf75..da2619719 100644
--- a/src/pages/audio/_id.vue
+++ b/src/pages/audio/_id.vue
@@ -29,7 +29,7 @@ import iframeHeight from '~/mixins/iframe-height'
import { AUDIO } from '~/constants/media'
import attributionHtml from '~/utils/attribution-html'
import { getFullLicenseName } from '~/utils/license'
-import { SEARCH } from '~/constants/store-modules'
+import { MEDIA } from '~/constants/store-modules'
const AudioDetailPage = {
name: 'AudioDetailPage',
@@ -48,7 +48,7 @@ const AudioDetailPage = {
}
},
computed: {
- ...mapState(SEARCH, ['audio']),
+ ...mapState(MEDIA, ['audio']),
fullLicenseName() {
return getFullLicenseName(this.audio.license, this.audio.license_version)
},
@@ -63,7 +63,7 @@ const AudioDetailPage = {
},
async asyncData({ env, store, route, error, app }) {
try {
- await store.dispatch(`${SEARCH}/${FETCH_AUDIO}`, { id: route.params.id })
+ await store.dispatch(`${MEDIA}/${FETCH_AUDIO}`, { id: route.params.id })
return {
thumbnailURL: `${env.apiUrl}thumbs/${route.params.id}`,
id: route.params.id,
diff --git a/src/pages/index.vue b/src/pages/index.vue
index bf6800904..fb00be534 100644
--- a/src/pages/index.vue
+++ b/src/pages/index.vue
@@ -3,7 +3,7 @@
</template>
<script>
-import { FILTER } from '~/constants/store-modules'
+import { SEARCH } from '~/constants/store-modules'
import { CLEAR_FILTERS } from '~/constants/mutation-types'
const HomePage = {
@@ -12,7 +12,7 @@ const HomePage = {
return store.state.nav.isEmbedded ? 'embedded' : 'default'
},
beforeMount() {
- this.$store.dispatch(`${FILTER}/${CLEAR_FILTERS}`)
+ this.$store.dispatch(`${SEARCH}/${CLEAR_FILTERS}`)
},
}
diff --git a/src/pages/photos/_id.vue b/src/pages/photos/_id.vue
index bf33273d8..3a7350121 100644
--- a/src/pages/photos/_id.vue
+++ b/src/pages/photos/_id.vue
@@ -18,7 +18,7 @@
import axios from 'axios'
import { mapActions, mapState } from 'vuex'
import { FETCH_IMAGE } from '~/constants/action-types'
-import { SEARCH } from '~/constants/store-modules'
+import { MEDIA } from '~/constants/store-modules'
const PhotoDetailPage = {
name: 'PhotoDetailPage',
@@ -40,7 +40,7 @@ const PhotoDetailPage = {
}
},
computed: {
- ...mapState(SEARCH, ['image']),
+ ...mapState(MEDIA, ['image']),
},
async asyncData({ env, route }) {
return {
@@ -73,7 +73,7 @@ const PhotoDetailPage = {
})
},
methods: {
- ...mapActions(SEARCH, { fetchImage: FETCH_IMAGE }),
+ ...mapActions(MEDIA, { fetchImage: FETCH_IMAGE }),
onImageLoaded(event) {
this.imageWidth = event.target.naturalWidth
this.imageHeight = event.target.naturalHeight
diff --git a/src/pages/search.vue b/src/pages/search.vue
index 1b01808a4..75f7b3d41 100644
--- a/src/pages/search.vue
+++ b/src/pages/search.vue
@@ -15,7 +15,7 @@
<div class="column search-grid-ctr">
<SearchGridForm @onSearchFormSubmit="onSearchFormSubmit" />
<SearchTypeTabs />
- <FilterDisplay v-if="shouldShowFilterTags" />
+ <FilterDisplay v-show="shouldShowFilterTags" />
<NuxtChild :key="$route.path" @onLoadMoreItems="onLoadMoreItems" />
<ScrollButton
data-testid="scroll-button"
@@ -28,20 +28,17 @@
<script>
import {
FETCH_MEDIA,
- SET_FILTERS_FROM_URL,
- SET_SEARCH_TYPE_FROM_URL,
+ UPDATE_QUERY,
+ SET_SEARCH_STATE_FROM_URL,
UPDATE_SEARCH_TYPE,
} from '~/constants/action-types'
-import { SET_QUERY, SET_FILTER_IS_VISIBLE } from '~/constants/mutation-types'
-import {
- queryStringToQueryData,
- queryStringToSearchType,
-} from '~/utils/search-query-transform'
+import { SET_FILTER_IS_VISIBLE } from '~/constants/mutation-types'
+import { queryStringToSearchType } from '~/utils/search-query-transform'
import local from '~/utils/local'
import { screenWidth } from '~/utils/get-browser-info'
-import { ALL_MEDIA, IMAGE } from '~/constants/media'
-import { mapActions, mapMutations, mapState } from 'vuex'
-import { FILTER, SEARCH } from '~/constants/store-modules'
+import { ALL_MEDIA, IMAGE, VIDEO } from '~/constants/media'
+import { mapActions, mapGetters, mapMutations, mapState } from 'vuex'
+import { MEDIA, SEARCH } from '~/constants/store-modules'
import debounce from 'lodash.debounce'
const BrowsePage = {
@@ -51,19 +48,21 @@ const BrowsePage = {
},
scrollToTop: false,
async fetch() {
- const url = this.$route.fullPath
- if (process.server) {
- const query = queryStringToQueryData(url)
- this.setQuery({ query })
+ if (this.mediaType !== VIDEO && this.results.items.length === 0) {
+ await this.fetchMedia({ mediaType: this.mediaType, q: this.query.q })
}
- await this.setSearchTypeFromUrl({ url })
- await this.setFiltersFromUrl({ url })
},
data: () => ({
showScrollButton: false,
}),
- created() {
+ async created() {
this.debounceScrollHandling = debounce(this.checkScrollLength, 100)
+ if (process.server) {
+ await this.setSearchStateFromUrl({
+ path: this.$route.path,
+ query: this.$route.query,
+ })
+ }
},
mounted() {
const localFilterState = () =>
@@ -83,66 +82,70 @@ const BrowsePage = {
window.removeEventListener('scroll', this.debounceScrollHandling)
},
computed: {
- ...mapState(SEARCH, ['query', 'searchType']),
- ...mapState(FILTER, ['isFilterVisible']),
+ ...mapState(SEARCH, ['query', 'isFilterVisible', 'searchType']),
+ ...mapGetters(SEARCH, ['searchQueryParams', 'isAnyFilterApplied']),
+ ...mapGetters(MEDIA, ['results']),
mediaType() {
// Default to IMAGE until media search/index is generalized
return this.searchType !== ALL_MEDIA ? this.searchType : IMAGE
},
+ shouldShowFilterTags() {
+ return (
+ ['/search/', '/search/image'].includes(this.$route.path) &&
+ this.isAnyFilterApplied
+ )
+ },
},
methods: {
+ ...mapActions(MEDIA, { fetchMedia: FETCH_MEDIA }),
...mapActions(SEARCH, {
- fetchMedia: FETCH_MEDIA,
- setSearchTypeFromUrl: SET_SEARCH_TYPE_FROM_URL,
- setFiltersFromUrl: SET_FILTERS_FROM_URL,
+ setSearchStateFromUrl: SET_SEARCH_STATE_FROM_URL,
updateSearchType: UPDATE_SEARCH_TYPE,
- }),
- ...mapActions(FILTER, {
- setFiltersFromUrl: SET_FILTERS_FROM_URL,
+ updateQuery: UPDATE_QUERY,
}),
...mapMutations(SEARCH, {
- setQuery: SET_QUERY,
- }),
- ...mapMutations(FILTER, {
setFilterVisibility: SET_FILTER_IS_VISIBLE,
}),
- getMediaItems(params, mediaType) {
- this.fetchMedia({ ...params, mediaType })
+ async getMediaItems(params, mediaType) {
+ await this.fetchMedia({ ...params, mediaType })
},
onLoadMoreItems(searchParams) {
this.getMediaItems(searchParams, this.mediaType)
},
- onSearchFormSubmit(searchParams) {
- this.setQuery(searchParams)
+ onSearchFormSubmit({ q }) {
+ this.updateQuery({ q })
},
onToggleSearchGridFilter() {
this.setFilterVisibility({
isFilterVisible: !this.isFilterVisible,
})
},
- shouldShowFilterTags() {
- return (
- this.$route.path === '/search/' || this.$route.path === '/search/image'
- )
- },
checkScrollLength() {
this.showScrollButton = window.scrollY > 70
},
},
watch: {
- query(newQuery) {
- if (newQuery) {
+ query: {
+ deep: true,
+ handler() {
const newPath = this.localePath({
path: this.$route.path,
- query: newQuery,
+ query: this.searchQueryParams,
})
this.$router.push(newPath)
- this.getMediaItems(newQuery, this.mediaType)
- }
+ this.getMediaItems(this.query, this.mediaType)
+ },
},
- $route(route) {
- const searchType = queryStringToSearchType(route.path)
- this.updateSearchType({ searchType })
+ /**
+ * Updates the search type only if the route's path changes.
+ * @param newRoute
+ * @param oldRoute
+ */
+ $route(newRoute, oldRoute) {
+ if (newRoute.path !== oldRoute.path) {
+ const searchType = queryStringToSearchType(newRoute.path)
+ this.updateSearchType({ searchType })
+ }
},
},
}
diff --git a/src/store/filter.js b/src/store/filter.js
deleted file mode 100644
index 6c1501d35..000000000
--- a/src/store/filter.js
+++ /dev/null
@@ -1,380 +0,0 @@
-import findIndex from 'lodash.findindex'
-import clonedeep from 'lodash.clonedeep'
-
-import local from '~/utils/local'
-import { queryToFilterData } from '~/utils/search-query-transform'
-import {
- ALL_MEDIA,
- AUDIO,
- IMAGE,
- VIDEO,
- supportedMediaTypes,
-} from '~/constants/media'
-import {
- SET_FILTERS_FROM_URL,
- TOGGLE_FILTER,
- UPDATE_QUERY,
-} from '~/constants/action-types'
-import {
- SET_FILTER,
- SET_PROVIDERS_FILTERS,
- CLEAR_FILTERS,
- SET_FILTER_IS_VISIBLE,
- UPDATE_FILTERS,
- REPLACE_FILTERS,
-} from '~/constants/mutation-types'
-import { SEARCH } from '~/constants/store-modules'
-
-// The order of the keys here is the same as in the side filter display
-export const mediaFilterKeys = {
- image: [
- 'licenses',
- 'licenseTypes',
- 'imageCategories',
- 'imageExtensions',
- 'aspectRatios',
- 'sizes',
- 'imageProviders',
- 'searchBy',
- 'mature',
- ],
- audio: process.env.enableAudio
- ? [
- 'licenses',
- 'licenseTypes',
- 'audioCategories',
- 'audioExtensions',
- 'durations',
- 'audioProviders',
- 'searchBy',
- 'mature',
- ]
- : [],
- video: [],
- all: ['licenses', 'licenseTypes', 'searchBy', 'mature'],
-}
-export const mediaSpecificFilters = {
- all: ['licenses', 'licenseTypes', 'searchBy', 'mature'],
- image: [
- 'imageCategories',
- 'imageExtensions',
- 'aspectRatios',
- 'sizes',
- 'imageProviders',
- ],
- audio: process.env.enableAudio
- ? ['audioCategories', 'audioExtensions', 'durations', 'audioProviders']
- : [],
- video: [],
-}
-
-export const filterData = {
- licenses: [
- { code: 'cc0', name: 'filters.licenses.cc0', checked: false },
- { code: 'pdm', name: 'filters.licenses.pdm', checked: false },
- { code: 'by', name: 'filters.licenses.by', checked: false },
- { code: 'by-sa', name: 'filters.licenses.by-sa', checked: false },
- { code: 'by-nc', name: 'filters.licenses.by-nc', checked: false },
- { code: 'by-nd', name: 'filters.licenses.by-nd', checked: false },
- { code: 'by-nc-sa', name: 'filters.licenses.by-nc-sa', checked: false },
- { code: 'by-nc-nd', name: 'filters.licenses.by-nc-nd', checked: false },
- ],
- licenseTypes: [
- {
- code: 'commercial',
- name: 'filters.license-types.commercial',
- checked: false,
- },
- {
- code: 'modification',
- name: 'filters.license-types.modification',
- checked: false,
- },
- ],
- audioCategories: [
- {
- code: 'music',
- name: 'filters.audio-categories.music',
- checked: false,
- },
- {
- code: 'soundEffects',
- name: 'filters.audio-categories.sound-effects',
- checked: false,
- },
- {
- code: 'podcast',
- name: 'filters.audio-categories.podcast',
- checked: false,
- },
- ],
- imageCategories: [
- {
- code: 'photograph',
- name: 'filters.image-categories.photograph',
- checked: false,
- },
- {
- code: 'illustration',
- name: 'filters.image-categories.illustration',
- checked: false,
- },
- {
- code: 'digitized_artwork',
- name: 'filters.image-categories.digitized-artwork',
- checked: false,
- },
- ],
- audioExtensions: [
- { code: 'mp3', name: 'filters.audio-extensions.mp3', checked: false },
- { code: 'ogg', name: 'filters.audio-extensions.ogg', checked: false },
- { code: 'flac', name: 'filters.audio-extensions.flac', checked: false },
- ],
- imageExtensions: [
- { code: 'jpg', name: 'filters.image-extensions.jpg', checked: false },
- { code: 'png', name: 'filters.image-extensions.png', checked: false },
- { code: 'gif', name: 'filters.image-extensions.gif', checked: false },
- { code: 'svg', name: 'filters.image-extensions.svg', checked: false },
- ],
- aspectRatios: [
- { code: 'tall', name: 'filters.aspect-ratios.tall', checked: false },
- { code: 'wide', name: 'filters.aspect-ratios.wide', checked: false },
- { code: 'square', name: 'filters.aspect-ratios.square', checked: false },
- ],
- durations: [
- { code: 'short', name: 'filters.durations.short', checked: false },
- { code: 'medium', name: 'filters.durations.medium', checked: false },
- { code: 'long', name: 'filters.durations.long', checked: false },
- ],
- sizes: [
- { code: 'small', name: 'filters.sizes.small', checked: false },
- { code: 'medium', name: 'filters.sizes.medium', checked: false },
- { code: 'large', name: 'filters.sizes.large', checked: false },
- ],
- audioProviders: [],
- imageProviders: [],
- searchBy: [
- { code: 'creator', name: 'filters.searchBy.creator', checked: false },
- ],
- mature: false,
-}
-
-/**
- * Returns true if any of the filters' checked property is true
- * except for `mature` filter, as it is not displayed as a tag
- * @param filters
- * @returns {boolean}
- */
-// eslint-disable-next-line no-unused-vars
-const anyFilterApplied = (filters) =>
- Object.keys(filters).some((filterKey) => {
- if (filterKey === 'mature') {
- return false
- } // this is hardcoded to "false" because we do not show mature in `FilterDisplay.vue` like the other filters
-
- return (
- filters[filterKey] && filters[filterKey].some((filter) => filter.checked)
- )
- })
-
-export const state = () => ({
- filters: clonedeep(filterData),
- isFilterVisible: false,
-})
-
-export const getters = {
- /**
- * Returns all applied filters in unified format
- * Mature filter is not returned because it is not displayed
- * as a filter tag
- * @param state
- * @param getters
- * @param rootState
- * @returns {{code: string, name: string, filterType: string}[]}
- */
- appliedFilterTags: (state, getters, rootState) => {
- let appliedFilters = []
- const filterKeys = mediaFilterKeys[rootState.search.searchType]
- filterKeys.forEach((filterType) => {
- if (filterType !== 'mature') {
- const newFilters = state.filters[filterType]
- .filter((f) => f.checked)
- .map((f) => {
- return {
- code: f.code,
- name: f.name,
- filterType: filterType,
- }
- })
- appliedFilters = [...appliedFilters, ...newFilters]
- }
- })
- return appliedFilters
- },
- isAnyFilterApplied: (state, getters, rootState) => {
- return anyFilterApplied(
- getMediaTypeFilters(state, { mediaType: rootState.search.searchType })
- )
- },
- allFiltersForDisplay: (state) => {
- return getMediaTypeFilters(state, {
- mediaType: ALL_MEDIA,
- includeMature: false,
- })
- },
- audioFiltersForDisplay: (state) => {
- return getMediaTypeFilters(state, {
- mediaType: AUDIO,
- includeMature: false,
- })
- },
- imageFiltersForDisplay: (state) => {
- return getMediaTypeFilters(state, {
- mediaType: IMAGE,
- includeMature: false,
- })
- },
- videoFiltersForDisplay: (state) => {
- return getMediaTypeFilters(state, {
- mediaType: VIDEO,
- includeMature: false,
- })
- },
-}
-
-const actions = {
- [TOGGLE_FILTER]({ commit, dispatch, state }, params) {
- const { filterType, code } = params
- const filters = state.filters[filterType]
- const codeIdx = findIndex(filters, (f) => f.code === code)
-
- commit(SET_FILTER, { codeIdx, ...params })
- dispatch(`${SEARCH}/${UPDATE_QUERY}`, null, { root: true })
- },
- [CLEAR_FILTERS]({ commit, dispatch, state }) {
- const initialFilters = clonedeep(filterData)
-
- const resetProviders = (mediaType) => {
- return state.filters[`${mediaType}Providers`].map((provider) => ({
- ...provider,
- checked: false,
- }))
- }
- const newFilterData = {
- ...initialFilters,
- audioProviders: resetProviders(AUDIO),
- imageProviders: resetProviders(IMAGE),
- }
- commit(REPLACE_FILTERS, { newFilterData })
- dispatch(`${SEARCH}/${UPDATE_QUERY}`, null, { root: true })
- },
- [SET_FILTERS_FROM_URL]({ commit }, { url }) {
- const newFilterData = queryToFilterData(url)
- commit(REPLACE_FILTERS, { newFilterData })
- },
-}
-
-function getMediaTypeFilters(state, { mediaType, includeMature = false }) {
- let filterKeys = mediaFilterKeys[mediaType]
- if (!includeMature) {
- filterKeys = filterKeys.filter((filterKey) => filterKey !== 'mature')
- }
- const mediaTypeFilters = {}
- filterKeys.forEach((filterKey) => {
- mediaTypeFilters[filterKey] = state.filters[filterKey]
- })
- return mediaTypeFilters
-}
-
-// Make sure when redirecting after applying a filter, we stick to the right tab (i.e, "/search/video", "/search/audio", etc.)
-const mutations = {
- /**
- * After a search type is changed, unchecks all the filters that are not
- * applicable for this Media type.
- * @param state
- * @param searchType
- */
- [UPDATE_FILTERS](state, { searchType }) {
- const mediaTypesToClear = supportedMediaTypes.filter(
- (media) => media !== searchType
- )
-
- let filterKeysToClear = []
- mediaTypesToClear.forEach((mediaType) => {
- const filterKeys = mediaSpecificFilters[mediaType]
- filterKeysToClear = [...filterKeysToClear, ...filterKeys]
- })
-
- Object.keys(state.filters).forEach((filterType) => {
- if (filterKeysToClear.includes(filterType)) {
- state.filters[filterType] = state.filters[filterType].map((f) => ({
- ...f,
- checked: false,
- }))
- }
- })
- },
- [REPLACE_FILTERS](state, { newFilterData }) {
- Object.keys(state.filters).forEach((filterType) => {
- if (filterType === 'mature') {
- state.filters.mature = newFilterData.mature
- } else if (['audioProviders', 'imageProviders'].includes(filterType)) {
- newFilterData[filterType].forEach((provider) => {
- const idx = state.filters[filterType].findIndex(
- (p) => p.code === provider.code
- )
- if (idx > -1) {
- state.filters[filterType][idx].checked = provider.checked
- }
- })
- } else {
- state.filters[filterType] = newFilterData[filterType]
- }
- })
- },
- [SET_FILTER](state, params) {
- const { filterType, codeIdx } = params
- if (filterType === 'mature') {
- state.filters.mature = !state.filters.mature
- } else {
- const filters = state.filters[filterType]
- filters[codeIdx].checked = !filters[codeIdx].checked
- }
- },
- [SET_PROVIDERS_FILTERS](state, params) {
- const { mediaType, providers } = params
- // merge providers from API response with the filters that came from the
- // browse URL search query string and match the checked properties
- // in the store
- const providersKey = `${mediaType}Providers`
- const currentProviders = [...state.filters[providersKey]]
- state.filters[providersKey] = providers.map((provider) => {
- const existingProviderFilterIdx = findIndex(
- currentProviders,
- (p) => p.code === provider.source_name
- )
-
- const checked =
- existingProviderFilterIdx >= 0
- ? currentProviders[existingProviderFilterIdx].checked
- : false
-
- return {
- code: provider.source_name,
- name: provider.display_name,
- checked,
- }
- })
- },
- [SET_FILTER_IS_VISIBLE](state, params) {
- state.isFilterVisible = params.isFilterVisible
- local.set(process.env.filterStorageKey, params.isFilterVisible)
- },
-}
-
-export default {
- state,
- getters,
- actions,
- mutations,
-}
diff --git a/src/store/media.js b/src/store/media.js
new file mode 100644
index 000000000..7103b3ab3
--- /dev/null
+++ b/src/store/media.js
@@ -0,0 +1,314 @@
+import findIndex from 'lodash.findindex'
+import prepareSearchQueryParams from '~/utils/prepare-search-query-params'
+import decodeMediaData from '~/utils/decode-media-data'
+import {
+ FETCH_AUDIO,
+ FETCH_IMAGE,
+ FETCH_MEDIA,
+ HANDLE_MEDIA_ERROR,
+ HANDLE_NO_MEDIA,
+} from '~/constants/action-types'
+import {
+ FETCH_END_MEDIA,
+ FETCH_MEDIA_ERROR,
+ FETCH_START_MEDIA,
+ MEDIA_NOT_FOUND,
+ RESET_MEDIA,
+ SET_AUDIO,
+ SET_IMAGE,
+ SET_MEDIA,
+} from '~/constants/mutation-types'
+import {
+ SEND_RESULT_CLICKED_EVENT,
+ SEND_SEARCH_QUERY_EVENT,
+} from '~/constants/usage-data-analytics-types'
+import { AUDIO, IMAGE } from '~/constants/media'
+import { USAGE_DATA } from '~/constants/store-modules'
+import AudioService from '~/data/audio-service'
+import ImageService from '~/data/image-service'
+
+/**
+ * @return {import('./types').MediaState}
+ */
+export const state = () => ({
+ results: {
+ audio: {
+ count: 0,
+ page: undefined,
+ pageCount: 0,
+ items: [],
+ },
+ image: {
+ count: 0,
+ page: undefined,
+ pageCount: 0,
+ items: [],
+ },
+ },
+ fetchingState: {
+ audio: {
+ isFetching: false,
+ fetchingError: null,
+ },
+ image: {
+ isFetching: false,
+ fetchingError: null,
+ },
+ },
+ audio: {},
+ image: {},
+})
+
+export const createActions = (services) => ({
+ /**
+ *
+ * @param {import('vuex').ActionContext} context
+ * @param params
+ * @return {Promise<void>}
+ */
+ async [FETCH_MEDIA]({ commit, dispatch, rootState, rootGetters }, params) {
+ // does not send event if user is paginating for more results
+ const { page, mediaType, q } = params
+ const sessionId = rootState.user.usageSessionId
+ if (!page) {
+ await dispatch(
+ `${USAGE_DATA}/${SEND_SEARCH_QUERY_EVENT}`,
+ { query: q, sessionId },
+ { root: true }
+ )
+ }
+
+ commit(FETCH_START_MEDIA, { mediaType })
+ if (!params.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 }) => {
+ commit(FETCH_END_MEDIA, { mediaType })
+ const mediaCount = data.result_count
+ commit(SET_MEDIA, {
+ mediaType,
+ media: data.results,
+ mediaCount,
+ pageCount: data.page_count,
+ shouldPersistMedia: params.shouldPersistMedia,
+ page: page,
+ })
+ dispatch(HANDLE_NO_MEDIA, { mediaType, mediaCount })
+ })
+ .catch((error) => {
+ dispatch(HANDLE_MEDIA_ERROR, { mediaType, error })
+ })
+ },
+ /**
+ *
+ * @param {import('vuex').ActionContext} context
+ * @param params
+ * @return {Promise<void>}
+ */
+ async [FETCH_AUDIO]({ commit, dispatch, state, rootState }, params) {
+ await dispatch(
+ `${USAGE_DATA}/${SEND_RESULT_CLICKED_EVENT}`,
+ {
+ query: rootState.search.query.q,
+ resultUuid: params.id,
+ resultRank: findIndex(
+ state.results.audio.items,
+ (item) => item.id === params.id
+ ),
+ sessionId: rootState.user.usageSessionId,
+ },
+ { root: true }
+ )
+ commit(SET_AUDIO, { audio: {} })
+ await services[AUDIO].getMediaDetail(params)
+ .then(({ data }) => {
+ commit(SET_AUDIO, { audio: data })
+ })
+ .catch((error) => {
+ if (error.response && error.response.status === 404) {
+ commit(MEDIA_NOT_FOUND, { mediaType: AUDIO })
+ } else {
+ dispatch(HANDLE_MEDIA_ERROR, { mediaType: AUDIO, error })
+ }
+ })
+ },
+ /**
+ *
+ * @param {import('vuex').ActionContext} context
+ * @param params
+ * @return {Promise<void>}
+ */
+ async [FETCH_IMAGE]({ commit, dispatch, state, rootState }, params) {
+ await dispatch(
+ `${USAGE_DATA}/${SEND_RESULT_CLICKED_EVENT}`,
+ {
+ query: rootState.search.query.q,
+ resultUuid: params.id,
+ resultRank: findIndex(
+ state.results.image.items,
+ (img) => img.id === params.id
+ ),
+ sessionId: rootState.user.usageSessionId,
+ },
+ { root: true }
+ )
+
+ commit(SET_IMAGE, { image: {} })
+ await services[IMAGE].getMediaDetail(params)
+ .then(({ data }) => {
+ commit(SET_IMAGE, { image: data })
+ })
+ .catch((error) => {
+ if (error.response && error.response.status === 404) {
+ commit(MEDIA_NOT_FOUND, { mediaType: IMAGE })
+ } else {
+ throw new Error(`Error fetching the image: ${error.message}`)
+ }
+ })
+ },
+ /**
+ *
+ * @param {import('vuex').ActionContext} context
+ * @param {'audio'|'image'} mediaType
+ * @param error
+ * @return {Promise<void>}
+ */
+ async [HANDLE_MEDIA_ERROR]({ commit }, { mediaType, error }) {
+ let errorMessage
+ if (error.response) {
+ errorMessage =
+ error.response.status === 500
+ ? 'There was a problem with our servers'
+ : error.response.message
+ commit(FETCH_MEDIA_ERROR, { mediaType, errorMessage })
+ } else {
+ commit(FETCH_MEDIA_ERROR, { mediaType, errorMessage: error.message })
+ throw new Error(error)
+ }
+ },
+ /**
+ *
+ * @param {import('vuex').ActionContext} context
+ * @param {number} mediaCount
+ * @param {'audio'|'image'} mediaType
+ */
+ [HANDLE_NO_MEDIA]({ commit }, { mediaCount, mediaType }) {
+ if (!mediaCount) {
+ commit(FETCH_MEDIA_ERROR, {
+ errorMessage: `No ${mediaType} found for this query`,
+ })
+ }
+ },
+})
+
+export const getters = {
+ /**
+ * Returns the search result data related for selected media.
+ * @param {import('./types').MediaState} state
+ * @param getters
+ * @param rootState
+ * @return {import('./types').MediaStoreResult}
+ */
+ results(state, getters, rootState) {
+ return state.results[rootState.search.query.mediaType]
+ },
+ /**
+ * Search fetching state for selected media type.
+ * @param {import('./types').MediaState} state
+ * @param getters
+ * @param rootState
+ * @returns {import('./types').FetchingState}
+ */
+ fetchingState(state, getters, rootState) {
+ return state.fetchingState[rootState.search.query.mediaType]
+ },
+ /**
+ * Returns true if all pages from the search result have been shown.
+ * @param {import('./types').MediaState} state
+ * @param getters
+ * @param rootState
+ * @returns {boolean}
+ */
+ isFinished(state, getters, rootState) {
+ return (
+ state.results[rootState.search.query.mediaType].page >=
+ state.results[rootState.search.query.mediaType].pageCount
+ )
+ },
+}
+
+export const mutations = {
+ [FETCH_START_MEDIA](_state, { mediaType }) {
+ _state.fetchingState[mediaType].isFetching = true
+ _state.fetchingState[mediaType].fetchingError = null
+ },
+ [FETCH_END_MEDIA](_state, { mediaType }) {
+ _state.fetchingState[mediaType].isFetching = false
+ },
+ [FETCH_MEDIA_ERROR](_state, params) {
+ const { mediaType, errorMessage } = params
+ _state.fetchingState[mediaType].isFetching = false
+ _state.fetchingState[mediaType].fetchingError = errorMessage
+ },
+ [SET_AUDIO](_state, params) {
+ _state.audio = decodeMediaData(params.audio, AUDIO)
+ },
+ [SET_IMAGE](_state, params) {
+ _state.image = decodeMediaData(params.image)
+ },
+ [SET_MEDIA](_state, params) {
+ const {
+ mediaType,
+ media,
+ mediaCount,
+ page,
+ pageCount,
+ shouldPersistMedia,
+ } = params
+ let mediaToSet
+ mediaToSet = media.map((item) => decodeMediaData(item))
+ if (shouldPersistMedia) {
+ mediaToSet = _state.results[mediaType].items.concat(media)
+ }
+ _state.results[mediaType].items = mediaToSet
+ _state.results[mediaType].count = mediaCount || 0
+ _state.results[mediaType].page = page || 1
+ _state.results[mediaType].pageCount = pageCount
+ },
+ [MEDIA_NOT_FOUND](_state, params) {
+ throw new Error(`Media of type ${params.mediaType} not found`)
+ },
+ [RESET_MEDIA](_state, params) {
+ let mediaTypes
+ if (params && params.mediaType) {
+ mediaTypes = [params.mediaType]
+ } else {
+ mediaTypes = [AUDIO, IMAGE]
+ }
+ mediaTypes.forEach((mediaType) => {
+ _state.results[mediaType].items = []
+ _state.results[mediaType].count = 0
+ _state.results[mediaType].page = undefined
+ _state.results[mediaType].pageCount = 0
+ })
+ },
+}
+
+const mediaServices = { [AUDIO]: AudioService, [IMAGE]: ImageService }
+const actions = createActions(mediaServices)
+
+export default {
+ state,
+ getters,
+ actions,
+ mutations,
+}
diff --git a/src/store/provider.js b/src/store/provider.js
index 6225ea45c..d3500350e 100644
--- a/src/store/provider.js
+++ b/src/store/provider.js
@@ -14,7 +14,7 @@ import {
SET_MEDIA_PROVIDERS,
SET_PROVIDERS_FILTERS,
} from '~/constants/mutation-types'
-import { FILTER } from '~/constants/store-modules'
+import { SEARCH } from '~/constants/store-modules'
const AudioProviderService = MediaProviderService(AUDIO)
const ImageProviderService = MediaProviderService(IMAGE)
@@ -73,7 +73,7 @@ export const createActions = (services) => ({
providers: sortedProviders,
})
commit(
- `${FILTER}/${SET_PROVIDERS_FILTERS}`,
+ `${SEARCH}/${SET_PROVIDERS_FILTERS}`,
{
mediaType,
providers: sortedProviders,
diff --git a/src/store/search.js b/src/store/search.js
index a751e8ad6..2feff6c2e 100644
--- a/src/store/search.js
+++ b/src/store/search.js
@@ -1,319 +1,597 @@
import findIndex from 'lodash.findindex'
-import prepareSearchQueryParams from '~/utils/prepare-search-query-params'
-import decodeMediaData from '~/utils/decode-media-data'
+import clonedeep from 'lodash.clonedeep'
+
+import local from '~/utils/local'
+import {
+ filtersToQueryData,
+ queryStringToSearchType,
+ queryToFilterData,
+} from '~/utils/search-query-transform'
+import {
+ ALL_MEDIA,
+ AUDIO,
+ IMAGE,
+ supportedMediaTypes,
+ VIDEO,
+} from '~/constants/media'
import {
- FETCH_AUDIO,
- FETCH_IMAGE,
- FETCH_MEDIA,
- HANDLE_MEDIA_ERROR,
- HANDLE_NO_MEDIA,
- SET_SEARCH_TYPE_FROM_URL,
UPDATE_QUERY,
+ SET_MEDIA_TYPE,
+ SET_SEARCH_STATE_FROM_URL,
+ TOGGLE_FILTER,
+ UPDATE_QUERY_FROM_FILTERS,
UPDATE_SEARCH_TYPE,
} from '~/constants/action-types'
import {
- FETCH_END_MEDIA,
- FETCH_MEDIA_ERROR,
- FETCH_START_MEDIA,
- MEDIA_NOT_FOUND,
- REPLACE_QUERY,
- RESET_MEDIA,
- SET_AUDIO,
- SET_IMAGE,
- SET_IMAGE_PAGE,
- SET_MEDIA,
- SET_Q,
+ SET_FILTER,
+ SET_PROVIDERS_FILTERS,
+ CLEAR_FILTERS,
+ SET_FILTER_IS_VISIBLE,
+ CLEAR_OTHER_MEDIA_TYPE_FILTERS,
+ REPLACE_FILTERS,
SET_QUERY,
SET_SEARCH_TYPE,
- UPDATE_FILTERS,
} from '~/constants/mutation-types'
-import {
- SEND_RESULT_CLICKED_EVENT,
- SEND_SEARCH_QUERY_EVENT,
-} from '~/constants/usage-data-analytics-types'
-import {
- filtersToQueryData,
- queryStringToSearchType,
-} from '~/utils/search-query-transform'
-import { ALL_MEDIA, AUDIO, IMAGE } from '~/constants/media'
-import { FILTER, USAGE_DATA } from '~/constants/store-modules'
-import AudioService from '~/data/audio-service'
-import ImageService from '~/data/image-service'
+
+// The order of the keys here is the same as in the side filter display
+export const mediaFilterKeys = {
+ image: [
+ 'licenses',
+ 'licenseTypes',
+ 'imageCategories',
+ 'imageExtensions',
+ 'aspectRatios',
+ 'sizes',
+ 'imageProviders',
+ 'searchBy',
+ 'mature',
+ ],
+ audio: process.env.enableAudio
+ ? [
+ 'licenses',
+ 'licenseTypes',
+ 'audioCategories',
+ 'audioExtensions',
+ 'durations',
+ 'audioProviders',
+ 'searchBy',
+ 'mature',
+ ]
+ : [],
+ video: [],
+ all: ['licenses', 'licenseTypes', 'searchBy', 'mature'],
+}
+
+export const mediaSpecificFilters = {
+ all: ['licenses', 'licenseTypes', 'searchBy', 'mature'],
+ image: [
+ 'imageCategories',
+ 'imageExtensions',
+ 'aspectRatios',
+ 'sizes',
+ 'imageProviders',
+ ],
+ audio: process.env.enableAudio
+ ? ['audioCategories', 'audioExtensions', 'durations', 'audioProviders']
+ : [],
+ video: [],
+}
+
+/** @type {import('./types').Filters} */
+export const filterData = {
+ licenses: [
+ { code: 'cc0', name: 'filters.licenses.cc0', checked: false },
+ { code: 'pdm', name: 'filters.licenses.pdm', checked: false },
+ { code: 'by', name: 'filters.licenses.by', checked: false },
+ { code: 'by-sa', name: 'filters.licenses.by-sa', checked: false },
+ { code: 'by-nc', name: 'filters.licenses.by-nc', checked: false },
+ { code: 'by-nd', name: 'filters.licenses.by-nd', checked: false },
+ { code: 'by-nc-sa', name: 'filters.licenses.by-nc-sa', checked: false },
+ { code: 'by-nc-nd', name: 'filters.licenses.by-nc-nd', checked: false },
+ ],
+ licenseTypes: [
+ {
+ code: 'commercial',
+ name: 'filters.license-types.commercial',
+ checked: false,
+ },
+ {
+ code: 'modification',
+ name: 'filters.license-types.modification',
+ checked: false,
+ },
+ ],
+ audioCategories: [
+ {
+ code: 'music',
+ name: 'filters.audio-categories.music',
+ checked: false,
+ },
+ {
+ code: 'soundEffects',
+ name: 'filters.audio-categories.sound-effects',
+ checked: false,
+ },
+ {
+ code: 'podcast',
+ name: 'filters.audio-categories.podcast',
+ checked: false,
+ },
+ ],
+ imageCategories: [
+ {
+ code: 'photograph',
+ name: 'filters.image-categories.photograph',
+ checked: false,
+ },
+ {
+ code: 'illustration',
+ name: 'filters.image-categories.illustration',
+ checked: false,
+ },
+ {
+ code: 'digitized_artwork',
+ name: 'filters.image-categories.digitized-artwork',
+ checked: false,
+ },
+ ],
+ audioExtensions: [
+ { code: 'mp3', name: 'filters.audio-extensions.mp3', checked: false },
+ { code: 'ogg', name: 'filters.audio-extensions.ogg', checked: false },
+ { code: 'flac', name: 'filters.audio-extensions.flac', checked: false },
+ ],
+ imageExtensions: [
+ { code: 'jpg', name: 'filters.image-extensions.jpg', checked: false },
+ { code: 'png', name: 'filters.image-extensions.png', checked: false },
+ { code: 'gif', name: 'filters.image-extensions.gif', checked: false },
+ { code: 'svg', name: 'filters.image-extensions.svg', checked: false },
+ ],
+ aspectRatios: [
+ { code: 'tall', name: 'filters.aspect-ratios.tall', checked: false },
+ { code: 'wide', name: 'filters.aspect-ratios.wide', checked: false },
+ { code: 'square', name: 'filters.aspect-ratios.square', checked: false },
+ ],
+ durations: [
+ { code: 'short', name: 'filters.durations.short', checked: false },
+ { code: 'medium', name: 'filters.durations.medium', checked: false },
+ { code: 'long', name: 'filters.durations.long', checked: false },
+ ],
+ sizes: [
+ { code: 'small', name: 'filters.sizes.small', checked: false },
+ { code: 'medium', name: 'filters.sizes.medium', checked: false },
+ { code: 'large', name: 'filters.sizes.large', checked: false },
+ ],
+ audioProviders: [],
+ imageProviders: [],
+ searchBy: [
+ { code: 'creator', name: 'filters.searchBy.creator', checked: false },
+ ],
+ mature: false,
+}
+const supportedTabTypes = [AUDIO, IMAGE]
+if (process.env.enableAudio) {
+ supportedTabTypes.unshift(ALL_MEDIA)
+}
+const searchTabToMediaType = process.env.enableAudio
+ ? {
+ [ALL_MEDIA]: IMAGE,
+ [AUDIO]: AUDIO,
+ [IMAGE]: IMAGE,
+ [VIDEO]: null,
+ }
+ : {
+ [ALL_MEDIA]: IMAGE,
+ [AUDIO]: null,
+ [IMAGE]: IMAGE,
+ [VIDEO]: null,
+ }
+/**
+ * Returns true if any of the filters' checked property is true
+ * except for `mature` filter, as it is not displayed as a tag
+ * @param filters
+ * @returns {boolean}
+ */
+const anyFilterApplied = (filters = {}) =>
+ Object.keys(filters).some((filterKey) => {
+ if (filterKey === 'mature') {
+ return false
+ } // this is hardcoded to "false" because we do not show mature in `FilterDisplay.vue` like the other filters
+
+ return (
+ filters[filterKey] && filters[filterKey].some((filter) => filter.checked)
+ )
+ })
/**
- * @type {{ audios: import('./types').AudioDetail[],
- * audiosCount: number, audioPage:number,
- * images: import('../store/types').ImageDetail[],
- * imagePage: number, imagesCount: number, query: {},
- * pageCount: {images: number, audios: number},
- * isFetching: {images: boolean, audios: boolean},
- * isFetchingError: {images: boolean, audios: boolean},
- * errorMessage: null, searchType: string, }}
+ * Search type is the media tab that is currently open in the UI. Some types
+ * are not supported by the API (video), or default to a different type (all - image).
+ * The media type that is actually queried is saved as `query.mediaType`, and can
+ * be null for unsupported type.
+ * `query` has the API request parameters for search filtering. Locally, some filters
+ * have different names, and some query parameters correspond to different filter parameters
+ * depending on the media type. For example, `extension` query parameter can be `audioExtension`
+ * or `imageExtension`, with different values for each.
+ *
+ * @return {import('./types').SearchState}
*/
export const state = () => ({
- audios: [],
- audiosCount: 0,
- audioPage: 1,
- images: [],
- imagesCount: 0,
- imagePage: 1,
- pageCount: {
- images: 0,
- audios: 0,
- },
- isFetching: {
- audios: false,
- images: false,
- },
- isFetchingError: {
- audios: true,
- images: true,
+ filters: clonedeep(filterData),
+ isFilterVisible: false,
+ searchType: IMAGE,
+ query: {
+ q: '',
+ mediaType: IMAGE,
+ license: '',
+ license_type: '',
+ categories: '',
+ extension: '',
+ duration: '',
+ aspect_ratio: '',
+ size: '',
+ source: '',
+ searchBy: '',
+ mature: false,
},
- errorMessage: null,
- searchType: ALL_MEDIA,
- query: {},
- audio: {},
- image: {},
})
-export const createActions = (services) => ({
- async [FETCH_MEDIA]({ commit, dispatch, rootState }, params) {
- // does not send event if user is paginating for more results
- const { page, mediaType, q } = params
- const sessionId = rootState.user.usageSessionId
- if (!page) {
- dispatch(
- `${USAGE_DATA}/${SEND_SEARCH_QUERY_EVENT}`,
- { query: q, sessionId },
- { root: true }
- )
- }
-
- commit(FETCH_START_MEDIA, { mediaType })
- if (!params.page) {
- commit(RESET_MEDIA, { mediaType })
- }
- const queryParams = prepareSearchQueryParams(params)
- if (!Object.keys(services).includes(mediaType)) {
- throw new Error(`Cannot fetch unknown media type "${mediaType}"`)
+export const getters = {
+ /**
+ * Returns the search query parameters for API request:
+ * drops `mediaType` parameter, and all parameters with blank values.
+ * @param {import('./types').SearchState} state
+ * @return {import('./types').ApiQueryParams}
+ */
+ searchQueryParams: (state) => {
+ // Ensure that q filter always comes first
+ const params = { q: state.query.q }
+ // Remove the mediaType parameter, and handle mature filter separately
+ const filterKeys = Object.keys(state.query).filter(
+ (key) => !['q', 'mediaType', 'mature'].includes(key)
+ )
+ filterKeys.forEach((key) => {
+ if (state.query[key].length) {
+ params[key] = state.query[key]
+ }
+ })
+ if (state.query.mature === true) {
+ params.mature = true
}
- await services[mediaType]
- .search(queryParams)
- .then(({ data }) => {
- commit(FETCH_END_MEDIA, { mediaType })
- const mediaCount = data.result_count
- commit(SET_MEDIA, {
- mediaType,
- media: data.results,
- mediaCount,
- pageCount: data.page_count,
- shouldPersistMedia: params.shouldPersistMedia,
- page: page,
- })
- dispatch(HANDLE_NO_MEDIA, { mediaType, mediaCount })
- })
- .catch((error) => {
- dispatch(HANDLE_MEDIA_ERROR, { mediaType, error })
- })
+ return params
},
- async [FETCH_AUDIO]({ commit, dispatch, state, rootState }, params) {
- dispatch(
- `${USAGE_DATA}/${SEND_RESULT_CLICKED_EVENT}`,
- {
- query: state.query.q,
- resultUuid: params.id,
- resultRank: findIndex(state.audios, (img) => img.id === params.id),
- sessionId: rootState.user.usageSessionId,
- },
- { root: true }
- )
- commit(SET_AUDIO, { audio: {} })
- await services[AUDIO].getMediaDetail(params)
- .then(({ data }) => {
- commit(SET_AUDIO, { audio: data })
- })
- .catch((error) => {
- if (error.response && error.response.status === 404) {
- commit(MEDIA_NOT_FOUND, { mediaType: AUDIO })
- } else {
- dispatch(HANDLE_MEDIA_ERROR, { mediaType: AUDIO, error })
+ /**
+ * Returns all applied filters in unified format
+ * Mature filter is not returned because it is not displayed
+ * as a filter tag.
+ *
+ * @param {import('./types').SearchState} state
+ * @returns {{code: string, name: string, filterType: string}[]}
+ */
+ appliedFilterTags: (state) => {
+ let appliedFilters = []
+ if (state.query.mediaType) {
+ const filterKeys = mediaFilterKeys[state.query.mediaType]
+ filterKeys.forEach((filterType) => {
+ if (filterType !== 'mature') {
+ const newFilters = state.filters[filterType]
+ .filter((f) => f.checked)
+ .map((f) => {
+ return {
+ code: f.code,
+ name: f.name,
+ filterType: filterType,
+ }
+ })
+ appliedFilters = [...appliedFilters, ...newFilters]
}
})
+ }
+ return appliedFilters
},
- async [FETCH_IMAGE]({ commit, dispatch, state, rootState }, params) {
- dispatch(
- `${USAGE_DATA}/${SEND_RESULT_CLICKED_EVENT}`,
- {
- query: state.query.q,
- resultUuid: params.id,
- resultRank: findIndex(state.images, (img) => img.id === params.id),
- sessionId: rootState.user.usageSessionId,
- },
- { root: true }
- )
-
- commit(SET_IMAGE, { image: {} })
- await services[IMAGE].getMediaDetail(params)
- .then(({ data }) => {
- commit(SET_IMAGE, { image: data })
- })
- .catch((error) => {
- if (error.response && error.response.status === 404) {
- commit(MEDIA_NOT_FOUND, { mediaType: IMAGE })
- } else {
- throw new Error(`Error fetching the image: ${error.message}`)
- }
+ /**
+ * Returns true if any filter except `mature` is applied.
+ *
+ * @param {import('./types').SearchState} state
+ * @return {boolean}
+ */
+ isAnyFilterApplied: (state) => {
+ return anyFilterApplied(
+ getMediaTypeFilters({
+ filters: state.filters,
+ mediaType: state.query.mediaType,
})
+ )
},
- async [HANDLE_MEDIA_ERROR]({ commit }, { mediaType, error }) {
- let errorMessage
- if (error.response) {
- errorMessage =
- error.response.status === 500
- ? 'There was a problem with our servers'
- : error.response.message
- commit(FETCH_MEDIA_ERROR, { mediaType, errorMessage })
- } else {
- commit(FETCH_MEDIA_ERROR, { mediaType, errorMessage: error.message })
- throw new Error(error)
- }
+ /**
+ * Returns the array of the filters applicable for current search type
+ * for display on the Filter sidebar.
+ * @param {import('./types').SearchState} state
+ * @return {{}}
+ */
+ mediaFiltersForDisplay: (state) => {
+ return getMediaTypeFilters({
+ filters: state.filters,
+ mediaType: state.query.mediaType,
+ includeMature: false,
+ })
},
- [HANDLE_NO_MEDIA]({ commit }, { mediaCount, mediaType }) {
- if (!mediaCount) {
- commit(FETCH_MEDIA_ERROR, {
- errorMessage: `No ${mediaType} found for this query`,
- })
+}
+
+const actions = {
+ /**
+ * Called when `q` search term or `searchType` (ie. the search tab in the UI)
+ * are changed.
+ * We avoid adding changes to `q` or `searchType` separately, because every
+ * change to the state `query` object causes an API call.
+ * @param {import('vuex').ActionContext} context
+ * @param {import('vuex').ActionPayload} params
+ * @param {string} [params.q]
+ * @param {('all'|'audio'|'image'|'video')} [params.searchType]
+ * @return {Promise<void>}
+ */
+ async [UPDATE_QUERY]({ commit, dispatch, state }, params = {}) {
+ const { q, searchType } = params
+ /** @type {{ q: string?, mediaType: string? }} */
+ const queryParams = {}
+ if (q) {
+ queryParams.q = q.trim()
}
+ if (searchType && searchType !== state.searchType) {
+ commit(SET_SEARCH_TYPE, { searchType })
+ const newMediaType = searchTabToMediaType[searchType]
+ if (newMediaType !== state.query.mediaType) {
+ queryParams.mediaType = newMediaType
+ }
+ commit(CLEAR_OTHER_MEDIA_TYPE_FILTERS, { searchType })
+ }
+ await dispatch(UPDATE_QUERY_FROM_FILTERS, queryParams)
},
- [SET_SEARCH_TYPE_FROM_URL]({ commit }, params) {
- const searchType = queryStringToSearchType(params.url)
- commit(SET_SEARCH_TYPE, { searchType })
- commit(`${FILTER}/${UPDATE_FILTERS}`, { searchType }, { root: true })
+ /**
+ * Toggles a filter's checked parameter
+ * @param {import('vuex').ActionContext} context
+ * @param params
+ */
+ async [TOGGLE_FILTER]({ commit, dispatch, state }, params) {
+ const { filterType, code } = params
+ const filters = state.filters[filterType]
+ const codeIdx = findIndex(filters, (f) => f.code === code)
+
+ commit(SET_FILTER, { codeIdx, ...params })
+ await dispatch(UPDATE_QUERY_FROM_FILTERS)
},
- [UPDATE_SEARCH_TYPE]({ commit }, { searchType }) {
- commit(SET_SEARCH_TYPE, { searchType })
- commit(`${FILTER}/${UPDATE_FILTERS}`, { searchType }, { root: true })
+
+ /**
+ * Resets all filters to initial values.
+ * Provider filters are not in the initial filters, so they need to be
+ * handled separately.
+ * @param {import('vuex').ActionContext} context
+ */
+ async [CLEAR_FILTERS]({ commit, dispatch, state }) {
+ const initialFilters = clonedeep(filterData)
+ const resetProviders = (mediaType) => {
+ return state.filters[`${mediaType}Providers`].map((provider) => ({
+ ...provider,
+ checked: false,
+ }))
+ }
+ const newFilterData = {
+ ...initialFilters,
+ audioProviders: resetProviders(AUDIO),
+ imageProviders: resetProviders(IMAGE),
+ }
+ commit(REPLACE_FILTERS, { newFilterData })
+ await dispatch(UPDATE_QUERY_FROM_FILTERS, { q: '' })
},
- [UPDATE_QUERY]({ commit, state, rootState }) {
- const query = filtersToQueryData(rootState.filter.filters, state.searchType)
- commit(REPLACE_QUERY, {
- query: {
- q: state.query.q,
- ...query,
- },
+
+ /**
+ * Called when a /search path is server-rendered.
+ * @param {import('vuex').ActionContext} context
+ * @param {string} path
+ * @param {Object} query
+ */
+ async [SET_SEARCH_STATE_FROM_URL](
+ { commit, dispatch, state },
+ { path, query }
+ ) {
+ const searchType = queryStringToSearchType(path)
+ const mediaType = searchTabToMediaType[searchType]
+ const queryParams = { mediaType }
+ if (query.q) {
+ queryParams.q = query.q
+ }
+ const newFilterData = queryToFilterData({
+ query,
+ searchType,
+ defaultFilters: state.filters,
})
+ commit(REPLACE_FILTERS, { newFilterData })
+ commit(SET_SEARCH_TYPE, { searchType: searchType })
+ await dispatch(UPDATE_QUERY_FROM_FILTERS, queryParams)
},
-})
-export const getters = {
- isFetching(state) {
- return state.isFetching[state.searchType]
+ /**
+ * On selecting a search tab, updates the search type and
+ * sets the filters that are applicable for this media type.
+ * @param {import('vuex').ActionContext} context
+ * @param {'all'|'audio'|'image'|'video'} searchType
+ */
+ async [UPDATE_SEARCH_TYPE]({ commit, state }, { searchType }) {
+ if (state.searchType !== searchType) {
+ commit(SET_SEARCH_TYPE, { searchType })
+ commit(CLEAR_OTHER_MEDIA_TYPE_FILTERS, { searchType })
+
+ const newMediaType = searchTabToMediaType[searchType]
+ if (state.query.mediaType !== newMediaType) {
+ commit(SET_MEDIA_TYPE, { mediaType: newMediaType })
+ }
+ }
},
- isFetchingError(state) {
- return state.isFetchingError[state.searchType]
+ /**
+ * After a change in filters, updates the query.
+ * @param {import('vuex').ActionContext} context
+ * @param {Object} params
+ * @param {string} [params.q]
+ * @param {'audio'|'image'} [params.mediaType]
+ */
+ async [UPDATE_QUERY_FROM_FILTERS]({ state, commit }, params = {}) {
+ const queryFromFilters = filtersToQueryData(
+ state.filters,
+ params.mediaType || state.query.mediaType,
+ false
+ )
+ const query = { ...queryFromFilters }
+ query.q = params?.q || state.query.q
+ query.mediaType = params?.mediaType || state.query.mediaType
+
+ commit(SET_QUERY, { query })
},
}
-export const mutations = {
- [FETCH_START_MEDIA](_state, { mediaType }) {
- const mediaPlural = `${mediaType}s`
- _state.isFetching[mediaPlural] = true
- _state.isFetchingError[mediaPlural] = false
- },
- [FETCH_END_MEDIA](_state, { mediaType }) {
- const mediaPlural = `${mediaType}s`
- _state.isFetching[mediaPlural] = false
- },
- [FETCH_MEDIA_ERROR](_state, params) {
- const { mediaType, errorMessage } = params
- const mediaPlural = `${mediaType}s`
- _state.isFetching[mediaPlural] = false
- _state.isFetchingError[mediaPlural] = true
- _state.errorMessage = errorMessage
- },
- [SET_AUDIO](_state, params) {
- _state.audio = decodeMediaData(params.audio, AUDIO)
- },
- [SET_IMAGE](_state, params) {
- _state.image = decodeMediaData(params.image)
+function getMediaTypeFilters({ filters, mediaType, includeMature = false }) {
+ if (![ALL_MEDIA, AUDIO, IMAGE, VIDEO].includes(mediaType)) {
+ mediaType = ALL_MEDIA
+ }
+ let filterKeys = mediaFilterKeys[mediaType]
+ if (!includeMature) {
+ filterKeys = filterKeys.filter((filterKey) => filterKey !== 'mature')
+ }
+ const mediaTypeFilters = {}
+ filterKeys.forEach((filterKey) => {
+ mediaTypeFilters[filterKey] = filters[filterKey]
+ })
+ return mediaTypeFilters
+}
+
+// Make sure when redirecting after applying a filter, we stick to the right tab (i.e, "/search/video", "/search/audio", etc.)
+const mutations = {
+ /**
+ * After a search type is changed, unchecks all the filters that are not
+ * applicable for this Media type.
+ * @param {import('./types').SearchState} state
+ * @param {'all'|'audio'|'image'|'video'} searchType
+ */
+ [CLEAR_OTHER_MEDIA_TYPE_FILTERS](state, { searchType }) {
+ const mediaTypesToClear = supportedMediaTypes.filter(
+ (media) => media !== searchType
+ )
+
+ let filterKeysToClear = []
+ mediaTypesToClear.forEach((mediaType) => {
+ const filterKeys = mediaSpecificFilters[mediaType]
+ filterKeysToClear = [...filterKeysToClear, ...filterKeys]
+ })
+
+ Object.keys(state.filters).forEach((filterType) => {
+ if (filterKeysToClear.includes(filterType)) {
+ state.filters[filterType] = state.filters[filterType].map((f) => ({
+ ...f,
+ checked: false,
+ }))
+ }
+ })
},
- [SET_IMAGE_PAGE](_state, params) {
- _state.imagePage = params.imagePage
+ /**
+ * Replaces filters with the newFilterData parameter, making sure that
+ * audio/image provider filters are handled correctly.
+ *
+ * @param {import('./types').SearchState} state
+ * @param {import('./types').Filters} newFilterData
+ */
+ [REPLACE_FILTERS](state, { newFilterData }) {
+ Object.keys(state.filters).forEach((filterType) => {
+ if (filterType === 'mature') {
+ state.filters.mature = newFilterData.mature
+ } else if (['audioProviders', 'imageProviders'].includes(filterType)) {
+ newFilterData[filterType].forEach((provider) => {
+ const idx = state.filters[filterType].findIndex(
+ (p) => p.code === provider.code
+ )
+ if (idx > -1) {
+ state.filters[filterType][idx].checked = provider.checked
+ }
+ })
+ } else {
+ state.filters[filterType] = newFilterData[filterType]
+ }
+ })
},
- [SET_MEDIA](_state, params) {
- const {
- mediaType,
- media,
- mediaCount,
- page,
- pageCount,
- shouldPersistMedia,
- } = params
- const mediaPlural = `${mediaType}s`
- let mediaToSet
- if (shouldPersistMedia) {
- mediaToSet = _state[`${mediaType}s`].concat(media)
+ /**
+ * Toggles the filter's checked value.
+ *
+ * @param {import('./types').SearchState} state
+ * @param {import('vuex').MutationPayload} params
+ * @param {string} params.filterType
+ * @param {number} params.codeIdx
+ */
+ [SET_FILTER](state, params) {
+ const { filterType, codeIdx } = params
+ if (filterType === 'mature') {
+ state.filters.mature = !state.filters.mature
} else {
- mediaToSet = media
+ const filters = state.filters[filterType]
+ filters[codeIdx].checked = !filters[codeIdx].checked
}
- mediaToSet = mediaToSet.map((item) => decodeMediaData(item))
- _state[mediaPlural] = mediaToSet
- _state[`${mediaPlural}Count`] = mediaCount || 0
- _state[`${mediaType}Page`] = page || 1
- _state.pageCount[mediaPlural] = pageCount
+ },
+ [SET_PROVIDERS_FILTERS](state, params) {
+ const { mediaType, providers } = params
+ // merge providers from API response with the filters that came from the
+ // browse URL search query string and match the checked properties
+ // in the store
+ const providersKey = `${mediaType}Providers`
+ const currentProviders = [...state.filters[providersKey]]
+ state.filters[providersKey] = providers.map((provider) => {
+ const existingProviderFilterIdx = findIndex(
+ currentProviders,
+ (p) => p.code === provider.source_name
+ )
+
+ const checked =
+ existingProviderFilterIdx >= 0
+ ? currentProviders[existingProviderFilterIdx].checked
+ : false
+
+ return {
+ code: provider.source_name,
+ name: provider.display_name,
+ checked,
+ }
+ })
+ },
+ [SET_FILTER_IS_VISIBLE](state, params) {
+ state.isFilterVisible = params.isFilterVisible
+ local.set(process.env.filterStorageKey, params.isFilterVisible)
},
/**
- * Merges the query object from parameters with the existing
- * query object. Used on 'Search' button click.
- * @param _state
- * @param {object} query
+ * Sets the searchType (tab in the UI).
+ * @param {import('./types').SearchState} state
+ * @param {'all'|'image'|'audio'|'video'} searchType
*/
- [SET_QUERY](_state, { query }) {
- _state.query = Object.assign({}, _state.query, query)
- _state.images = []
- _state.audios = []
+ [SET_SEARCH_TYPE](state, { searchType }) {
+ state.searchType = searchType
},
/**
- * When a new search term is searched for, sets the `q`
- * parameter for the API request query and resets the media.
- * Leaves other query parameters for filters as before.
- * @param _state
- * @param {string} q
+ * Sets the query mediaType: the actual media type that is used in the API call.
+ * @param {import('./types').SearchState} state
+ * @param {'image'|'audio'} mediaType
*/
- [SET_Q](_state, { q }) {
- _state.query.q = q
- _state.images = []
- _state.audios = []
+ [SET_MEDIA_TYPE](state, { mediaType }) {
+ state.query.mediaType = mediaType
},
/**
- * Replaces the query object completely and resets all the
- * media. Called when filters are updated.
- * @param _state
- * @param {object} query
+ * Replaces the query object that is used for API calls.
+ * @param {import('./types').SearchState} state
+ * @param {Object} query
*/
- [REPLACE_QUERY](_state, { query }) {
- _state.query = query
- _state.images = []
- _state.audios = []
- },
- [MEDIA_NOT_FOUND](_state, params) {
- throw new Error(`Media of type ${params.mediaType} not found`)
- },
- [SET_SEARCH_TYPE](_state, params) {
- _state.searchType = params.searchType
- },
- [RESET_MEDIA](_state, params) {
- const { mediaType } = params
- _state[`${mediaType}s`] = []
- _state[`${mediaType}sCount`] = 0
- _state[`${mediaType}Page`] = undefined
- _state.pageCount[`${mediaType}s`] = 0
+ [SET_QUERY](state, { query }) {
+ if (!query.mediaType) {
+ query = {
+ ...query,
+ mediaType: state.query.mediaType,
+ }
+ }
+ state.query = query
},
}
-const mediaServices = { [AUDIO]: AudioService, [IMAGE]: ImageService }
-const actions = createActions(mediaServices)
-
export default {
state,
getters,
diff --git a/src/store/types.d.ts b/src/store/types.d.ts
index 8c3ced50e..87c432ef2 100644
--- a/src/store/types.d.ts
+++ b/src/store/types.d.ts
@@ -8,6 +8,35 @@ export interface MediaResult<T> {
results: T
}
+export type Query = {
+ mediaType: 'audio' | 'image'
+ q: string
+ license: string
+ license_type: string
+ extension: string
+ size: string
+ aspect_ratio: string
+ searchBy: string
+ categories: string
+ source: string
+ duration: string
+ mature: boolean
+}
+
+export type ApiQueryParams = {
+ q: string
+ license?: string
+ license_type?: string
+ extension?: string
+ size?: string
+ aspect_ratio?: string
+ searchBy?: string
+ categories?: string
+ source?: string
+ duration?: string
+ mature?: string
+}
+
/**
* Audio Properties returned by the API
*/
@@ -57,8 +86,62 @@ export type ImageDetail = {
fields_matched?: string[]
}
+export interface FilterItem {
+ code: string
+ name: string
+ checked: boolean
+}
+
+export interface Filters {
+ licenses: FilterItem[]
+ licenseTypes: FilterItem[]
+ audioCategories: FilterItem[]
+ imageCategories: FilterItem[]
+ audioExtensions: FilterItem[]
+ imageExtensions: FilterItem[]
+ aspectRatios: FilterItem[]
+ durations: FilterItem[]
+ sizes: FilterItem[]
+ audioProviders: FilterItem[]
+ imageProviders: FilterItem[]
+ searchBy: FilterItem[]
+ mature: boolean
+}
+
+export interface FetchingState {
+ isFetching: boolean
+ fetchingError: null | string
+}
+
+export interface SearchState {
+ isFilterVisible: boolean
+ searchType: 'all' | 'audio' | 'image' | 'video'
+ query: Query
+ filters: Filters
+}
+
export interface ActiveMediaState {
type: 'image' | 'audio' | null
id: string | null
status: 'ejected' | 'playing' | 'paused' // 'ejected' means player is closed
}
+
+export interface MediaStoreResult {
+ count: number
+ page?: number
+ pageCount: number
+ items: AudioDetail[] | ImageDetail[]
+}
+
+export interface MediaState {
+ results: {
+ audio: MediaStoreResult
+ image: MediaStoreResult
+ }
+ fetchingState: {
+ audio: FetchingState
+ image: FetchingState
+ }
+ audio: Object | AudioDetail
+ image: Object | ImageDetail
+}
diff --git a/src/styles/results-page.scss b/src/styles/results-page.scss
deleted file mode 100644
index 76b11d49c..000000000
--- a/src/styles/results-page.scss
+++ /dev/null
@@ -1,28 +0,0 @@
-.search {
- margin: 0;
-}
-
-.search-grid-ctr {
- padding: 0;
- background-color: $color-wp-gray-0;
- min-height: 600px;
-
- @include mobile {
- width: 100%;
- flex: none;
- }
-}
-
-.grid-sidebar {
- padding: 0;
- background-color: #fff;
- border-right: 1px solid $color-transition-gray;
- max-width: 100%;
- width: 21.875rem;
-
- @include touch {
- position: relative;
- width: 0;
- height: 0;
- }
-}
diff --git a/src/utils/get-legacy-source-url.js b/src/utils/get-legacy-source-url.js
index 1d7aeeda2..40d65f157 100644
--- a/src/utils/get-legacy-source-url.js
+++ b/src/utils/get-legacy-source-url.js
@@ -32,7 +32,7 @@ export const legacySourceMap = {
let query = `${search.q} AND RIGHTS:*creative*` // search cc licensed works
if (search.filters && search.filters.commercial) {
- if (search.filters.comercial) query = `${query} AND NOT RIGHTS:*nc*`
+ if (search.filters.commercial) query = `${query} AND NOT RIGHTS:*nc*`
if (search.filters.modify) query = `${query} AND NOT RIGHTS:*nd*`
}
diff --git a/src/utils/prepare-search-query-params.js b/src/utils/prepare-search-query-params.js
index fcad6ed51..127297faa 100644
--- a/src/utils/prepare-search-query-params.js
+++ b/src/utils/prepare-search-query-params.js
@@ -19,6 +19,10 @@ export default function prepareSearchQueryParams(searchParams) {
params[params.searchBy] = params.q
delete params.q
}
-
+ Object.keys(params).forEach((key) => {
+ if (params[key] === '' || params[key] === false) {
+ delete params[key]
+ }
+ })
return params
}
diff --git a/src/utils/search-query-transform.js b/src/utils/search-query-transform.js
index b69120088..925336d85 100644
--- a/src/utils/search-query-transform.js
+++ b/src/utils/search-query-transform.js
@@ -1,6 +1,5 @@
import clonedeep from 'lodash.clonedeep'
-import findIndex from 'lodash.findindex'
-import { filterData, mediaSpecificFilters } from '~/store/filter'
+import { mediaSpecificFilters } from '~/store/search'
import getParameterByName from './get-parameter-by-name'
import { ALL_MEDIA, IMAGE } from '~/constants/media'
@@ -85,23 +84,6 @@ export const filtersToQueryData = (
return queryDataObject
}
-const parseQueryString = (
- queryString,
- queryStringParamKey,
- filterKey,
- data
-) => {
- const queryStringFilters = getParameterByName(
- queryStringParamKey,
- queryString
- ).split(',')
- data[filterKey].forEach((filter) => {
- if (findIndex(queryStringFilters, (f) => f === filter.code) >= 0) {
- filter.checked = true
- }
- })
-}
-
/**
* Extract search type from the url. Returns the the last part
* of the path between `/search/` and query, or `all` by default.
@@ -155,14 +137,18 @@ const getMediaTypeApiFilters = (filterParameter, parameterFilters) => {
/**
* converts the browser filter query string into the internal filter store data format
- * @param {string} queryString browser filter query string
+ * @param {Object} query browser filter query
+ * @param {'all'|'audio'|'image'|'video'} searchType
* @param {Object} defaultFilters default filters for testing purposes
*/
-export const queryToFilterData = (queryString, defaultFilters = null) => {
- const filters = defaultFilters
- ? clonedeep(defaultFilters)
- : clonedeep(filterData)
- const searchType = queryStringToSearchType(queryString)
+export const queryToFilterData = ({
+ query,
+ searchType = 'image',
+ defaultFilters,
+}) => {
+ // The default filterData object from search store doesn't contain provider filters,
+ // so we can't use it.
+ const filters = clonedeep(defaultFilters)
const filterTypes = getMediaFilterTypes(searchType)
const differentFiltersWithSameApiParams = [
'audioProviders',
@@ -174,23 +160,29 @@ export const queryToFilterData = (queryString, defaultFilters = null) => {
]
filterTypes.forEach((filterDataKey) => {
if (differentFiltersWithSameApiParams.includes(filterDataKey)) {
- const parameter = getParameterByName(
- filterPropertyMappings[filterDataKey],
- queryString
- )
- filters[filterDataKey] = getMediaTypeApiFilters(
- parameter,
- filters[filterDataKey]
- )
+ const parameter = query[filterPropertyMappings[filterDataKey]]
+ if (parameter) {
+ filters[filterDataKey] = getMediaTypeApiFilters(
+ parameter,
+ filters[filterDataKey]
+ )
+ }
} else if (filterDataKey !== 'mature') {
const queryDataKey = filterPropertyMappings[filterDataKey]
- parseQueryString(queryString, queryDataKey, filterDataKey, filters)
+ if (query[queryDataKey]) {
+ const filterValues = query[queryDataKey].split(',')
+ filterValues.forEach((val) => {
+ const idx = filters[filterDataKey].findIndex((f) => f.code === val)
+ if (idx >= 0) {
+ filters[filterDataKey][idx].checked = true
+ }
+ })
+ }
}
})
- const mature = getParameterByName('mature', queryString)
- if (mature) {
- filters.mature = mature.toLowerCase() === 'true'
+ if (query.mature) {
+ filters.mature = query.mature.toLowerCase() === 'true'
}
return filters
diff --git a/test/e2e/homepage.spec.js b/test/e2e/homepage.spec.js
index 0105821d0..5b224aeb5 100644
--- a/test/e2e/homepage.spec.js
+++ b/test/e2e/homepage.spec.js
@@ -2,9 +2,10 @@ const { test, expect } = require('@playwright/test')
test('can change type and search for audio/modification from homepage', async ({
page,
+ context,
}) => {
- // Go to http://localhost:8443/
- await page.goto('http://localhost:8443/')
+ // Go to http://localhost:8444/
+ await page.goto('/')
// Click text=Audio
await page.click('text=Audio')
// Check text=Modify or adapt >> input[name="lt"]
@@ -15,7 +16,7 @@ test('can change type and search for audio/modification from homepage', async ({
await page.fill('[placeholder="Search all content"]', 'cat')
// Click button:has-text("Search")
await page.click('button:has-text("Search")')
- await expect(page).toHaveURL(
- 'http://localhost:8443/search/audio?q=cat&license_type=modification'
- )
+ const BASE_URL = context._options.baseURL
+ const expectedUrl = BASE_URL + '/search/audio?q=cat&license_type=modification'
+ await expect(page).toHaveURL(expectedUrl)
})
diff --git a/test/e2e/search-query-client.spec.js b/test/e2e/search-query-client.spec.js
index 1d2fef485..8db198903 100644
--- a/test/e2e/search-query-client.spec.js
+++ b/test/e2e/search-query-client.spec.js
@@ -2,11 +2,13 @@ const { test, expect } = require('@playwright/test')
/**
* When navigating to the search page on the client side:
- * 1. `q` parameter is set as the search input value and url parameter
- * 2. Selecting 'audio' on homepage sets the search page path and search tab
- * 3. Selecting filters on the homepage sets the search query and url parameter
+ * 1. `q` parameter is set as the search input value and url parameter.
+ * 2. Selecting 'audio' on homepage sets the search page path and search tab.
+ * 3. Selecting filters on the homepage sets the search query and url parameter.
* 4. Query parameters (filter types or filter values) that are not used for
- * current media type are discarded
+ * current media type are discarded.
+ * 5. Can change the `q` parameter by typing into the search input and clicking on
+ * the Search button.
* All of these tests test search page on the client
*/
@@ -98,3 +100,10 @@ test.skip('url filter types not used by current mediaType are discarded', async
await page.click('[role="tab"]:has-text("Audio")')
await expect(page).toHaveURL('/search/audio?q=cat')
})
+
+test('can search for a different term', async ({ page }) => {
+ await page.goto('/search/image?q=cat')
+ await page.fill('input[type="search"]', 'dog')
+ await page.keyboard.press('Enter')
+ await expect(page).toHaveURL('/search/image?q=dog')
+})
diff --git a/test/unit/specs/components/filter-display.spec.js b/test/unit/specs/components/filter-display.spec.js
index 9ee71cd99..3340fdeca 100644
--- a/test/unit/specs/components/filter-display.spec.js
+++ b/test/unit/specs/components/filter-display.spec.js
@@ -16,9 +16,6 @@ describe('FilterDisplay', () => {
q: 'foo',
},
},
- },
- filter: {
- namespaced: true,
getters: {
isAnyFilterApplied: () => true,
appliedFilterTags: () => [
diff --git a/test/unit/specs/components/hero-section.spec.js b/test/unit/specs/components/hero-section.spec.js
index 745c1f7d4..cea521655 100644
--- a/test/unit/specs/components/hero-section.spec.js
+++ b/test/unit/specs/components/hero-section.spec.js
@@ -1,12 +1,13 @@
+import Vuex from 'vuex'
import HeroSection from '~/components/HeroSection'
import { fireEvent, render, screen } from '@testing-library/vue'
-import filterStore, { filterData } from '~/store/filter'
-import store from '~/store/search'
+import searchStore, { filterData } from '~/store/search'
+import mediaStore from '~/store/media'
import { createLocalVue } from '@vue/test-utils'
-import Vuex from 'vuex'
import clonedeep from 'lodash.clonedeep'
import VueI18n from 'vue-i18n'
import messages from '~/locales/en.json'
+import { IMAGE } from '~/constants/media'
const i18n = new VueI18n({
locale: 'en',
@@ -28,18 +29,19 @@ describe('HeroSection', () => {
filters = clonedeep(filterData)
storeMock = new Vuex.Store({
modules: {
- filter: {
+ search: {
namespaced: true,
- ...filterStore,
+ ...mediaStore,
+ ...searchStore,
state: {
+ query: {
+ q: 'me',
+ mediaType: IMAGE,
+ },
isFilterVisible: true,
filters,
},
},
- search: {
- namespaced: true,
- ...store,
- },
},
})
options = {
diff --git a/test/unit/specs/components/home-license-filter.spec.js b/test/unit/specs/components/home-license-filter.spec.js
index e00708098..661f8a926 100644
--- a/test/unit/specs/components/home-license-filter.spec.js
+++ b/test/unit/specs/components/home-license-filter.spec.js
@@ -1,7 +1,6 @@
import HomeLicenseFilter from '~/components/HomeLicenseFilter'
import { render, screen } from '@testing-library/vue'
import { TOGGLE_FILTER } from '~/constants/action-types'
-import { FILTER } from '~/constants/store-modules'
import { createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
@@ -20,7 +19,7 @@ describe('HomeLicenseFilter', () => {
localVue.use(Vuex)
storeMock = new Vuex.Store({
modules: {
- filter: {
+ search: {
namespaced: true,
actions: {
// Without this action, we get '[vuex] unknown local action type' error
@@ -47,24 +46,20 @@ describe('HomeLicenseFilter', () => {
const checkboxes = screen.queryAllByRole('checkbox')
expect(checkboxes.length).toEqual(2)
- const commercialCheckbox = screen.queryByLabelText('Commercial usage')
+ const commercialCheckbox = screen.queryByLabelText(/commercial/i)
expect(commercialCheckbox).toBeTruthy()
- const modificationCheckbox = screen.queryByLabelText('Allows modification')
+ const modificationCheckbox = screen.queryByLabelText(/modification/i)
expect(modificationCheckbox).toBeTruthy()
})
it('dispatches `TOGGLE_FILTER` when checkboxes selected', async () => {
storeMock.dispatch = dispatchMock
render(HomeLicenseFilter, options)
- const commercialCheckbox = screen.queryByLabelText('Commercial usage')
+ const commercialCheckbox = screen.queryByLabelText(/commercial/i)
await commercialCheckbox.click()
const checked = screen.queryAllByRole('checkbox', { checked: true })
expect(checked.length).toEqual(1)
- expect(dispatchMock).toHaveBeenCalledWith(`${FILTER}/${TOGGLE_FILTER}`, {
- code: 'commercial',
- filterType: 'licenseTypes',
- })
})
})
diff --git a/test/unit/specs/components/nav-section.spec.js b/test/unit/specs/components/nav-section.spec.js
index 6b47a2274..3c0232a1d 100644
--- a/test/unit/specs/components/nav-section.spec.js
+++ b/test/unit/specs/components/nav-section.spec.js
@@ -1,8 +1,8 @@
-import NavSection from '~/components/NavSection'
-import { SET_Q } from '~/constants/mutation-types'
+import Vuex from 'vuex'
import render from '../../test-utils/render'
import { createLocalVue } from '@vue/test-utils'
-import Vuex from 'vuex'
+import NavSection from '~/components/NavSection'
+import { UPDATE_QUERY } from '~/constants/action-types'
describe('NavSection', () => {
it('should render correct contents', () => {
@@ -10,16 +10,16 @@ describe('NavSection', () => {
expect(wrapper.find('nav').vm).toBeDefined()
})
- it('commits a mutation when the form is submitted', async () => {
+ it('dispatches an action when the form is submitted', async () => {
const localVue = createLocalVue()
localVue.use(Vuex)
- const commitMock = jest.fn()
+ const dispatchMock = jest.fn()
const storeMock = new Vuex.Store({
modules: {
search: {
namespaced: true,
- mutations: {
- [SET_Q]: commitMock,
+ actions: {
+ [UPDATE_QUERY]: dispatchMock,
},
},
},
@@ -43,7 +43,7 @@ describe('NavSection', () => {
path: '/search',
query: { q: 'foo' },
})
- // The first parameter should be the commit type, but because of the way it's mocked, it's {}
- expect(commitMock).toHaveBeenLastCalledWith({}, { q: 'foo' })
+ const dispatchArgs = dispatchMock.mock.calls[0][1]
+ expect(dispatchArgs).toEqual({ q: 'foo' })
})
})
diff --git a/test/unit/specs/components/photo-tags.spec.js b/test/unit/specs/components/photo-tags.spec.js
index 25b1707b4..c92dd0958 100644
--- a/test/unit/specs/components/photo-tags.spec.js
+++ b/test/unit/specs/components/photo-tags.spec.js
@@ -1,8 +1,8 @@
import Vuex from 'vuex'
-import { SET_Q } from '~/constants/mutation-types'
import render from '../../test-utils/render'
import { createLocalVue } from '@vue/test-utils'
import PhotoTags from '~/components/PhotoTags'
+import { UPDATE_QUERY } from '~/constants/action-types'
describe('PhotoTags', () => {
let options = null
@@ -41,13 +41,13 @@ describe('PhotoTags', () => {
expect(wrapper.find('.photo_tags').element).toBeUndefined()
})
- it('commits a mutation when a tag is clicked', () => {
- const commitMock = jest.fn()
+ it('dispatches an action when a tag is clicked', () => {
+ const dispatchMock = jest.fn()
const localVue = createLocalVue()
localVue.use(Vuex)
const storeMock = new Vuex.Store({
modules: {
- search: { namespaced: true, mutations: { [SET_Q]: commitMock } },
+ search: { namespaced: true, actions: { [UPDATE_QUERY]: dispatchMock } },
},
})
const opts = {
@@ -60,7 +60,7 @@ describe('PhotoTags', () => {
const wrapper = render(PhotoTags, opts)
wrapper.find('.tag').trigger('click')
const tagName = wrapper.find('.tag').text()
- // When mocking the module's mutation, the mutation type comes as `{}`
- expect(commitMock).toHaveBeenCalledWith({}, { q: tagName })
+ const dispatchArgs = dispatchMock.mock.calls[0][1]
+ expect(dispatchArgs).toEqual({ q: tagName })
})
})
diff --git a/test/unit/specs/components/search-grid-cell.spec.js b/test/unit/specs/components/search-grid-cell.spec.js
index c80f3eb5e..eafeffe5f 100644
--- a/test/unit/specs/components/search-grid-cell.spec.js
+++ b/test/unit/specs/components/search-grid-cell.spec.js
@@ -49,7 +49,6 @@ describe('SearchGridCell', () => {
const wrapper = render(SearchGridCell, {
propsData: props,
mocks: { localeRoute: localeRouteMock },
- stubs: { nuxtLink: true },
})
const link = wrapper.find('.search-grid_image-ctr')
await link.trigger('click')
diff --git a/test/unit/specs/components/search-grid-filter.spec.js b/test/unit/specs/components/search-grid-filter.spec.js
index fd8aa04c0..872119152 100644
--- a/test/unit/specs/components/search-grid-filter.spec.js
+++ b/test/unit/specs/components/search-grid-filter.spec.js
@@ -1,11 +1,10 @@
+import clonedeep from 'lodash.clonedeep'
import Vuex from 'vuex'
import { fireEvent, render, screen } from '@testing-library/vue'
import { createLocalVue } from '@vue/test-utils'
-import SearchGridFilter from '~/components/Filters/SearchGridFilter'
-import { UPDATE_QUERY } from '~/constants/action-types'
import { IMAGE } from '~/constants/media'
-import store from '~/store/filter'
-import clonedeep from 'lodash.clonedeep'
+import store from '~/store/search'
+import SearchGridFilter from '~/components/Filters/SearchGridFilter'
const initialFilters = {
licenseTypes: [
@@ -38,21 +37,25 @@ describe('SearchGridFilter', () => {
filters = clonedeep(initialFilters)
storeMock = new Vuex.Store({
modules: {
- filter: {
+ search: {
namespaced: true,
state: {
+ searchType: IMAGE,
isFilterVisible: true,
filters,
+ query: {
+ q: '',
+ mediaType: IMAGE,
+ },
},
mutations: store.mutations,
actions: store.actions,
getters: store.getters,
},
- search: {
+ media: {
namespaced: true,
- state: { searchType: IMAGE },
- actions: {
- [UPDATE_QUERY]: jest.fn(),
+ state: {
+ imagesCount: 2,
},
},
},
@@ -67,14 +70,14 @@ describe('SearchGridFilter', () => {
})
it('should show search filters when isFilterVisible is true', async () => {
- storeMock.state.filter.isFilterVisible = true
+ storeMock.state.search.isFilterVisible = true
await render(SearchGridFilter, options)
expect(screen.getByTestId('filters-list')).toBeVisible()
expect(screen.getByTestId('filters-list')).toHaveClass('block')
})
it('should not show search filters when isFilterVisible is false', async () => {
- storeMock.state.filter.isFilterVisible = false
+ storeMock.state.search.isFilterVisible = false
await render(SearchGridFilter, options)
// not.toBeVisible does not work
@@ -94,7 +97,7 @@ describe('SearchGridFilter', () => {
})
it('clears filters', async () => {
- storeMock.state.filter.filters.licenses[0].checked = true
+ storeMock.state.search.filters.licenses[0].checked = true
await render(SearchGridFilter, options)
// if no checked checkboxes were found, this would raise an error
screen.getByRole('checkbox', { checked: true })
diff --git a/test/unit/specs/components/search-grid-form.spec.js b/test/unit/specs/components/search-grid-form.spec.js
index 0a9f60fea..22cb84fce 100644
--- a/test/unit/specs/components/search-grid-form.spec.js
+++ b/test/unit/specs/components/search-grid-form.spec.js
@@ -7,13 +7,9 @@ const localVue = createLocalVue()
localVue.use(Vuex)
const storeMock = new Vuex.Store({
modules: {
- filter: {
- namespaced: true,
- state: { isFilterVisible: true },
- },
search: {
namespaced: true,
- state: { query: { q: 'foo' } },
+ state: { query: { q: 'foo' }, isFilterVisible: true },
},
},
})
diff --git a/test/unit/specs/components/search-grid-wrapper.spec.js b/test/unit/specs/components/search-grid-wrapper.spec.js
index 080be613f..fe14ea3c5 100644
--- a/test/unit/specs/components/search-grid-wrapper.spec.js
+++ b/test/unit/specs/components/search-grid-wrapper.spec.js
@@ -7,9 +7,10 @@ const localVue = createLocalVue()
localVue.use(Vuex)
const storeMock = new Vuex.Store({
modules: {
- filter: {
+ search: {
namespaced: true,
state: {
+ query: { q: 'foo' },
filters: {
licenseTypes: [
{ code: 'commercial', name: 'Commercial usage' },
@@ -18,10 +19,6 @@ const storeMock = new Vuex.Store({
},
},
},
- search: {
- namespaced: true,
- state: { query: { q: 'foo' } },
- },
},
})
diff --git a/test/unit/specs/components/search-grid.spec.js b/test/unit/specs/components/search-grid.spec.js
index 97cce1b5f..faf7d6d20 100644
--- a/test/unit/specs/components/search-grid.spec.js
+++ b/test/unit/specs/components/search-grid.spec.js
@@ -1,70 +1,95 @@
import SearchGrid from '~/components/SearchGridManualLoad'
import render from '../../test-utils/render'
-import { SET_MEDIA } from '~/constants/mutation-types'
-import filterStore from '~/store/filter'
-import searchStore from '~/store/search'
import Vuex from 'vuex'
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', () => {
let options = {}
- let commitMock = null
+ const localVue = createLocalVue()
+ localVue.use(Vuex)
+ localVue.use(VueI18n)
+ localVue.component('SearchGridCell', SearchGridCell)
let storeMock
- let searchStoreMock
+
+ const i18n = new VueI18n({
+ locale: 'en',
+ fallbackLocale: 'en',
+ messages: { en: messages },
+ })
+ localVue.prototype.$nuxt = {
+ nbFetching: 0,
+ }
+ localVue.component('SaferBrowsing', SaferBrowsing)
beforeEach(() => {
- commitMock = jest.fn()
- searchStoreMock = {
- state: {
- images: [{ id: 'foo', title: 'image1.jpg' }],
- imagesCount: 1,
- imagePage: 1,
- isFetching: {
- images: false,
- },
- isFetchingError: {
- images: false,
- },
- pageCount: {
- images: 2,
- },
- searchType: IMAGE,
- },
- getters: searchStore.getters,
- actions: searchStore.actions,
- mutations: {
- ...searchStore.mutations,
- [SET_MEDIA]: commitMock,
- },
- }
storeMock = new Vuex.Store({
modules: {
- filter: {
+ search: {
namespaced: true,
- ...filterStore,
+ state: {
+ query: { q: 'foo', mediaType: IMAGE },
+ filters: {
+ licenseTypes: [
+ { code: 'commercial', name: 'Commercial usage' },
+ { code: 'modification', name: 'Allows modification' },
+ ],
+ },
+ },
+ getters: {
+ isSearchTabSupported: () => true,
+ },
},
- search: {
+ media: {
namespaced: true,
- ...searchStoreMock,
+ state: {
+ results: {
+ image: {
+ count: 40,
+ page: 1,
+ pageCount: 2,
+ items: [
+ { id: 'image1', url: 'https://wp.org/image1.jpg' },
+ { id: 'image2', url: 'https://wp.org/image2.svg' },
+ ],
+ },
+ },
+ },
+ getters: {
+ fetchingState: () => ({
+ isFetching: false,
+ fetchingError: null,
+ }),
+ isFinished: () => false,
+ results: () => ({
+ count: 40,
+ page: 1,
+ pageCount: 2,
+ items: [
+ { id: 'image1', url: 'https://wp.org/image1.jpg' },
+ { id: 'image2', url: 'https://wp.org/image2.svg' },
+ ],
+ }),
+ },
},
},
})
options = {
- store: storeMock,
stubs: {
- SaferBrowsing: true,
+ // SearchRating: true,
LoadingIcon: true,
MetaSearchForm: true,
- SearchGridCell: true,
- SearchRating: true,
- },
- propsData: {
- includeAnalytics: true,
- },
- mocks: {
- $store: storeMock,
- store: storeMock,
+ NuxtLink: true,
+ // SaferBrowsing: true,
+ LicenseIcons: true,
},
+ store: storeMock,
+ localVue,
+ i18n,
}
})
@@ -78,41 +103,5 @@ describe('SearchGrid', () => {
const wrapper = render(SearchGrid, options)
expect(wrapper.find('.load-more').element).toBeDefined()
})
-
- it("doesn't render load more button if is loading images", () => {
- options.mocks.$store.state.search.isFetching.images = true
- const wrapper = render(SearchGrid, options)
- expect(wrapper.find('.load-more').vm).not.toBeDefined()
- })
-
- it('shows loading icon if is loading images', () => {
- options.mocks.$store.state.search.isFetching.images = true
-
- const wrapper = render(SearchGrid, options)
- expect(wrapper.findComponent({ name: 'LoadingIcon' })).toBeDefined()
- })
-
- it("doesn't render load more button if not loading images", async () => {
- const wrapper = render(SearchGrid, options)
- const button = wrapper.find('.button')
- await button.trigger('click')
-
- expect(wrapper.emitted('onLoadMoreImages')[0]).toEqual([
- {
- page: 2,
- shouldPersistMedia: true,
- ...options.propsData.query,
- },
- ])
- })
- // TODO: SearchGrid should be replaced with ImageGrid, and tested with testing library
- // it('sets image to empty array on search changed', () => {
- // const wrapper = render(SearchGrid, options)
- // wrapper.vm.searchChanged()
- //
- // expect(commitMock).toHaveBeenLastCalledWith(`${SEARCH}/${SET_MEDIA}`, {
- // media: [],
- // page: 1,
- // })
- // })
+ // Fetching states should be tested with e2e tests
})
diff --git a/test/unit/specs/pages/browse-page.spec.js b/test/unit/specs/pages/browse-page.spec.js
index 46d9b8068..980dace82 100644
--- a/test/unit/specs/pages/browse-page.spec.js
+++ b/test/unit/specs/pages/browse-page.spec.js
@@ -16,13 +16,11 @@ describe('Search Grid Wrapper', () => {
namespaced: true,
state: {
query: { q: 'foo' },
- },
- },
- filter: {
- namespaced: true,
- state: {
isFilterVisible: false,
},
+ mutations: {
+ SET_FILTER_IS_VISIBLE: jest.fn(),
+ },
},
},
})
diff --git a/test/unit/specs/store/filter-store.spec.js b/test/unit/specs/store/filter-store.spec.js
deleted file mode 100644
index 6ef6eb47f..000000000
--- a/test/unit/specs/store/filter-store.spec.js
+++ /dev/null
@@ -1,623 +0,0 @@
-import store, { filterData } from '~/store/filter'
-import {
- SET_FILTERS_FROM_URL,
- TOGGLE_FILTER,
- UPDATE_QUERY,
-} from '~/constants/action-types'
-import {
- SET_FILTER,
- SET_PROVIDERS_FILTERS,
- CLEAR_FILTERS,
- SET_FILTER_IS_VISIBLE,
- REPLACE_FILTERS,
-} from '~/constants/mutation-types'
-import { SEARCH } from '~/constants/store-modules'
-
-describe('Filter Store', () => {
- describe('state', () => {
- it('state contains licenses', () => {
- const defaultState = store.state()
-
- expect(defaultState.filters.licenses).toEqual(filterData.licenses)
- })
-
- it('state contains license types', () => {
- const defaultState = store.state()
-
- expect(defaultState.filters.licenseTypes).toEqual(filterData.licenseTypes)
- })
-
- it('state contains image types', () => {
- const defaultState = store.state()
-
- expect(defaultState.filters.imageCategories).toEqual(
- filterData.imageCategories
- )
- })
-
- it('state contains imageExtensions', () => {
- const defaultState = store.state()
-
- expect(defaultState.filters.imageExtensions).toEqual(
- filterData.imageExtensions
- )
- })
-
- it('state contains empty providers list', () => {
- const defaultState = store.state()
-
- expect(defaultState.filters.imageProviders).toEqual([])
- })
-
- it('state contains search by author', () => {
- const defaultState = store.state()
-
- expect(defaultState.filters.searchBy.author).toEqual(
- filterData.searchBy.author
- )
- })
-
- it('state contains mature', () => {
- const defaultState = store.state()
-
- expect(defaultState.filters.mature).toEqual(filterData.mature)
- })
-
- it('state has filter hidden', () => {
- const defaultState = store.state()
-
- expect(defaultState.isFilterVisible).toBeFalsy()
- })
-
- it('isFilterVisible should be false when innerWidth property is undefined', () => {
- window.innerWidth = undefined
- const state = store.state()
- expect(state.isFilterVisible).toBeFalsy()
- })
- it('isFilterVisible should be false when window width is less then 800', () => {
- window.innerWidth = 500
- const state = store.state()
- expect(state.isFilterVisible).toBeFalsy()
- })
- })
-
- describe('mutations', () => {
- let state = null
- let mutations = null
- let getters = null
-
- beforeEach(() => {
- state = {
- search: {
- searchType: 'image',
- query: { q: 'foo' },
- },
- ...store.state(),
- }
- mutations = store.mutations
- getters = store.getters
- })
-
- it('SET_FILTER updates license state', () => {
- mutations[SET_FILTER](state, { filterType: 'licenses', codeIdx: 0 })
-
- expect(state.filters.licenses[0].checked).toBeTruthy()
- })
-
- it('SET_FILTER updates license type state', () => {
- mutations[SET_FILTER](state, { filterType: 'licenseTypes', codeIdx: 0 })
-
- expect(state.filters.licenseTypes[0].checked).toBeTruthy()
- })
-
- it('SET_FILTER updates imageExtensions state', () => {
- mutations[SET_FILTER](state, {
- filterType: 'imageExtensions',
- codeIdx: 0,
- })
-
- expect(state.filters.imageExtensions[0].checked).toBeTruthy()
- })
-
- it('SET_FILTER updates image types state', () => {
- mutations[SET_FILTER](state, {
- filterType: 'imageCategories',
- codeIdx: 0,
- })
-
- expect(state.filters.imageCategories[0].checked).toBeTruthy()
- })
-
- it('SET_FILTER updates search by creator', () => {
- mutations[SET_FILTER](state, { filterType: 'searchBy', codeIdx: 0 })
-
- expect(state.filters.searchBy[0].checked).toBeTruthy()
- })
-
- it('SET_FILTER updates mature', () => {
- mutations[SET_FILTER](state, { filterType: 'mature' })
-
- expect(state.filters.mature).toBeTruthy()
- })
-
- it('SET_FILTER toggles mature', () => {
- state.filters.mature = true
- mutations[SET_FILTER](state, { filterType: 'mature' })
-
- expect(state.filters.mature).toBeFalsy()
- })
-
- it('SET_FILTER updates aspect ratio', () => {
- mutations[SET_FILTER](state, { filterType: 'aspectRatios', codeIdx: 0 })
-
- expect(state.filters.aspectRatios[0].checked).toBeTruthy()
- })
-
- it('SET_FILTER updates size', () => {
- mutations[SET_FILTER](state, { filterType: 'sizes', codeIdx: 0 })
-
- expect(state.filters.sizes[0].checked).toBeTruthy()
- })
-
- it('SET_FILTER updates isFilterApplied with provider', () => {
- state.filters.imageProviders = [{ code: 'met', checked: false }]
- mutations[SET_FILTER](state, { filterType: 'imageProviders', codeIdx: 0 })
-
- expect(getters.isAnyFilterApplied).toBeTruthy()
- })
-
- it('SET_FILTER updates isFilterApplied with license type', () => {
- mutations[SET_FILTER](state, { filterType: 'licenseTypes', codeIdx: 0 })
-
- expect(getters.isAnyFilterApplied).toBeTruthy()
- })
-
- it('SET_FILTER updates mature', () => {
- mutations[SET_FILTER](state, { filterType: 'mature' })
-
- expect(state.filters.mature).toBeTruthy()
- })
-
- it('SET_PROVIDERS_FILTERS merges with existing provider filters', () => {
- const existingProviderFilters = [{ code: 'met', checked: true }]
-
- const providers = [
- { source_name: 'met', display_name: 'Metropolitan' },
- { source_name: 'flickr', display_name: 'Flickr' },
- ]
-
- state.filters.imageProviders = existingProviderFilters
-
- mutations[SET_PROVIDERS_FILTERS](state, {
- mediaType: 'image',
- providers: providers,
- })
-
- expect(state.filters.imageProviders).toEqual([
- { code: 'met', name: 'Metropolitan', checked: true },
- { code: 'flickr', name: 'Flickr', checked: false },
- ])
- })
-
- it('SET_FILTER_IS_VISIBLE updates state', () => {
- const params = { isFilterVisible: 'bar' }
- mutations[SET_FILTER_IS_VISIBLE](state, params)
-
- expect(state.isFilterVisible).toBe(params.isFilterVisible)
- })
- })
-
- describe('actions', () => {
- let state = null
- let commitMock = null
- let dispatchMock = null
- let actions = null
-
- beforeEach(() => {
- state = store.state()
- commitMock = jest.fn()
- dispatchMock = jest.fn()
- actions = store.actions
- })
-
- it('SET_FILTERS_FROM_URL', () => {
- const url =
- 'https://wp.org/openverse/search/image?q=cat&license=cc0,by&searchBy=creator&extension=jpg&mature=true&source=met'
- actions[SET_FILTERS_FROM_URL](
- {
- commit: commitMock,
- dispatch: dispatchMock,
- state,
- },
- { url }
- )
- expect(commitMock).toHaveBeenCalledWith(REPLACE_FILTERS, {
- newFilterData: {
- aspectRatios: [
- {
- checked: false,
- code: 'tall',
- name: 'filters.aspect-ratios.tall',
- },
- {
- checked: false,
- code: 'wide',
- name: 'filters.aspect-ratios.wide',
- },
- {
- checked: false,
- code: 'square',
- name: 'filters.aspect-ratios.square',
- },
- ],
- audioCategories: [
- {
- checked: false,
- code: 'music',
- name: 'filters.audio-categories.music',
- },
- {
- checked: false,
- code: 'soundEffects',
- name: 'filters.audio-categories.sound-effects',
- },
- {
- checked: false,
- code: 'podcast',
- name: 'filters.audio-categories.podcast',
- },
- ],
- audioExtensions: [
- {
- checked: false,
- code: 'mp3',
- name: 'filters.audio-extensions.mp3',
- },
- {
- checked: false,
- code: 'ogg',
- name: 'filters.audio-extensions.ogg',
- },
- {
- checked: false,
- code: 'flac',
- name: 'filters.audio-extensions.flac',
- },
- ],
- audioProviders: [],
- durations: [
- { checked: false, code: 'short', name: 'filters.durations.short' },
- {
- checked: false,
- code: 'medium',
- name: 'filters.durations.medium',
- },
- { checked: false, code: 'long', name: 'filters.durations.long' },
- ],
- imageCategories: [
- {
- checked: false,
- code: 'photograph',
- name: 'filters.image-categories.photograph',
- },
- {
- checked: false,
- code: 'illustration',
- name: 'filters.image-categories.illustration',
- },
- {
- checked: false,
- code: 'digitized_artwork',
- name: 'filters.image-categories.digitized-artwork',
- },
- ],
- imageExtensions: [
- {
- checked: true,
- code: 'jpg',
- name: 'filters.image-extensions.jpg',
- },
- {
- checked: false,
- code: 'png',
- name: 'filters.image-extensions.png',
- },
- {
- checked: false,
- code: 'gif',
- name: 'filters.image-extensions.gif',
- },
- {
- checked: false,
- code: 'svg',
- name: 'filters.image-extensions.svg',
- },
- ],
- imageProviders: [],
- licenseTypes: [
- {
- checked: false,
- code: 'commercial',
- name: 'filters.license-types.commercial',
- },
- {
- checked: false,
- code: 'modification',
- name: 'filters.license-types.modification',
- },
- ],
- licenses: [
- { checked: true, code: 'cc0', name: 'filters.licenses.cc0' },
- { checked: false, code: 'pdm', name: 'filters.licenses.pdm' },
- { checked: true, code: 'by', name: 'filters.licenses.by' },
- { checked: false, code: 'by-sa', name: 'filters.licenses.by-sa' },
- { checked: false, code: 'by-nc', name: 'filters.licenses.by-nc' },
- { checked: false, code: 'by-nd', name: 'filters.licenses.by-nd' },
- {
- checked: false,
- code: 'by-nc-sa',
- name: 'filters.licenses.by-nc-sa',
- },
- {
- checked: false,
- code: 'by-nc-nd',
- name: 'filters.licenses.by-nc-nd',
- },
- ],
- mature: true,
- searchBy: [
- {
- checked: true,
- code: 'creator',
- name: 'filters.searchBy.creator',
- },
- ],
- sizes: [
- { checked: false, code: 'small', name: 'filters.sizes.small' },
- { checked: false, code: 'medium', name: 'filters.sizes.medium' },
- { checked: false, code: 'large', name: 'filters.sizes.large' },
- ],
- },
- })
- })
- it('CLEAR_FILTERS resets filters to initial state', async () => {
- state.filters.licenses = [
- { code: 'by', checked: true },
- { code: 'by-nc', checked: true },
- { code: 'by-nd', checked: true },
- ]
- actions[CLEAR_FILTERS]({
- commit: commitMock,
- dispatch: dispatchMock,
- state,
- })
- expect(commitMock).toHaveBeenCalledWith(REPLACE_FILTERS, {
- newFilterData: filterData,
- })
- expect(dispatchMock).toHaveBeenCalledWith(
- `${SEARCH}/${UPDATE_QUERY}`,
- null,
- { root: true }
- )
- })
-
- it('CLEAR_FILTERS sets providers filters checked to false', async () => {
- state.filters.imageProviders = [
- { code: 'met', name: 'Metropolitan', checked: true },
- { code: 'flickr', name: 'Flickr', checked: false },
- ]
-
- actions[CLEAR_FILTERS]({
- commit: commitMock,
- dispatch: dispatchMock,
- state,
- })
- const expectedFilters = {
- ...state.filters,
- imageProviders: [
- { code: 'met', name: 'Metropolitan', checked: false },
- { code: 'flickr', name: 'Flickr', checked: false },
- ],
- }
- expect(commitMock).toHaveBeenCalledWith(REPLACE_FILTERS, {
- newFilterData: expectedFilters,
- })
- expect(dispatchMock).toHaveBeenCalledWith(
- `${SEARCH}/${UPDATE_QUERY}`,
- null,
- { root: true }
- )
- })
-
- it('TOGGLE_FILTER commits SET_FILTER with filter index', () => {
- state.filters.providers = [
- { code: 'met', name: 'Metropolitan', checked: true },
- { code: 'flickr', name: 'Flickr', checked: false },
- ]
-
- const params = { filterType: 'providers', code: 'flickr' }
-
- actions[TOGGLE_FILTER](
- { commit: commitMock, dispatch: dispatchMock, state },
- params
- )
-
- expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {
- codeIdx: 1,
- ...params,
- })
- })
-
- it('TOGGLE_FILTER updates license state', () => {
- actions[TOGGLE_FILTER](
- { commit: commitMock, dispatch: dispatchMock, state },
- { filterType: 'licenses', code: 'cc0' }
- )
- expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {
- filterType: 'licenses',
- code: 'cc0',
- codeIdx: 0,
- })
- expect(dispatchMock).toHaveBeenCalledWith(
- `${SEARCH}/${UPDATE_QUERY}`,
- null,
- { root: true }
- )
- })
-
- it('TOGGLE_FILTER updates license type state', () => {
- actions[TOGGLE_FILTER](
- { commit: commitMock, dispatch: dispatchMock, state },
- { filterType: 'licenseTypes', code: 'modification' }
- )
-
- expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {
- filterType: 'licenseTypes',
- code: 'modification',
- codeIdx: 1,
- })
- expect(dispatchMock).toHaveBeenCalledWith(
- `${SEARCH}/${UPDATE_QUERY}`,
- null,
- { root: true }
- )
- })
-
- it('TOGGLE_FILTER updates imageExtensions state', () => {
- actions[TOGGLE_FILTER](
- { commit: commitMock, dispatch: dispatchMock, state },
- {
- filterType: 'imageExtensions',
- code: 'svg',
- }
- )
-
- expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {
- filterType: 'imageExtensions',
- code: 'svg',
- codeIdx: 3,
- })
-
- expect(dispatchMock).toHaveBeenCalledWith(
- `${SEARCH}/${UPDATE_QUERY}`,
- null,
- { root: true }
- )
- })
-
- it('TOGGLE_FILTER updates image types state', () => {
- actions[TOGGLE_FILTER](
- { commit: commitMock, dispatch: dispatchMock, state },
- {
- filterType: 'imageCategories',
- code: 'photograph',
- }
- )
- expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {
- filterType: 'imageCategories',
- code: 'photograph',
- codeIdx: 0,
- })
-
- expect(dispatchMock).toHaveBeenCalledWith(
- `${SEARCH}/${UPDATE_QUERY}`,
- null,
- { root: true }
- )
- })
-
- it('TOGGLE_FILTER updates search by creator', () => {
- actions[TOGGLE_FILTER](
- { commit: commitMock, dispatch: dispatchMock, state },
- { filterType: 'searchBy', code: 'creator' }
- )
-
- expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {
- filterType: 'searchBy',
- code: 'creator',
- codeIdx: 0,
- })
-
- expect(dispatchMock).toHaveBeenCalledWith(
- `${SEARCH}/${UPDATE_QUERY}`,
- null,
- { root: true }
- )
- })
-
- it('TOGGLE_FILTER updates mature', () => {
- actions[TOGGLE_FILTER](
- { commit: commitMock, dispatch: dispatchMock, state },
- { filterType: 'mature' }
- )
-
- expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {
- filterType: 'mature',
- codeIdx: -1,
- })
-
- expect(dispatchMock).toHaveBeenCalledWith(
- `${SEARCH}/${UPDATE_QUERY}`,
- null,
- { root: true }
- )
- })
-
- it('TOGGLE_FILTER updates aspect ratio', () => {
- actions[TOGGLE_FILTER](
- { commit: commitMock, dispatch: dispatchMock, state },
- { filterType: 'aspectRatios', code: 'tall' }
- )
-
- expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {
- filterType: 'aspectRatios',
- code: 'tall',
- codeIdx: 0,
- })
-
- expect(dispatchMock).toHaveBeenCalledWith(
- `${SEARCH}/${UPDATE_QUERY}`,
- null,
- { root: true }
- )
- })
-
- it('TOGGLE_FILTER updates size', () => {
- actions[TOGGLE_FILTER](
- { commit: commitMock, dispatch: dispatchMock, state },
- { filterType: 'sizes', code: 'medium' }
- )
-
- expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {
- filterType: 'sizes',
- code: 'medium',
- codeIdx: 1,
- })
-
- expect(dispatchMock).toHaveBeenCalledWith(
- `${SEARCH}/${UPDATE_QUERY}`,
- null,
- { root: true }
- )
- })
-
- it('TOGGLE_FILTER toggles mature', () => {
- state.filters.mature = true
- actions[TOGGLE_FILTER](
- { commit: commitMock, dispatch: dispatchMock, state },
- { filterType: 'mature' }
- )
-
- expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {
- filterType: 'mature',
- codeIdx: -1,
- })
-
- expect(dispatchMock).toHaveBeenCalledWith(
- `${SEARCH}/${UPDATE_QUERY}`,
- null,
- { root: true }
- )
- })
- })
-})
diff --git a/test/unit/specs/store/media-store.spec.js b/test/unit/specs/store/media-store.spec.js
new file mode 100644
index 000000000..3a2abe59f
--- /dev/null
+++ b/test/unit/specs/store/media-store.spec.js
@@ -0,0 +1,514 @@
+import store, { createActions } from '~/store/media'
+import {
+ FETCH_END_MEDIA,
+ FETCH_MEDIA_ERROR,
+ FETCH_START_MEDIA,
+ MEDIA_NOT_FOUND,
+ RESET_MEDIA,
+ SET_AUDIO,
+ SET_IMAGE,
+ SET_MEDIA,
+} from '~/constants/mutation-types'
+import {
+ FETCH_AUDIO,
+ FETCH_IMAGE,
+ FETCH_MEDIA,
+ HANDLE_MEDIA_ERROR,
+ HANDLE_NO_MEDIA,
+} from '~/constants/action-types'
+import { AUDIO, IMAGE } from '~/constants/media'
+import {
+ SEND_RESULT_CLICKED_EVENT,
+ SEND_SEARCH_QUERY_EVENT,
+} from '~/constants/usage-data-analytics-types'
+import { USAGE_DATA } from '~/constants/store-modules'
+
+describe('Search Store', () => {
+ describe('state', () => {
+ it('exports default state', () => {
+ const state = store.state()
+ expect(state.results.audio).toEqual({
+ count: 0,
+ items: [],
+ page: undefined,
+ pageCount: 0,
+ })
+ expect(state.results.image).toEqual({
+ count: 0,
+ items: [],
+ page: undefined,
+ pageCount: 0,
+ })
+ expect(state.fetchingState.audio).toEqual({
+ fetchingError: null,
+ isFetching: false,
+ })
+ expect(state.fetchingState.image).toEqual({
+ fetchingError: null,
+ isFetching: false,
+ })
+ expect(state.audio).toEqual({})
+ expect(state.image).toEqual({})
+ })
+ })
+
+ describe('mutations', () => {
+ let state = null
+ const mutations = store.mutations
+
+ beforeEach(() => {
+ state = store.state()
+ })
+
+ 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()
+ })
+
+ it('FETCH_END_MEDIA updates state', () => {
+ mutations[FETCH_END_MEDIA](state, { mediaType: IMAGE })
+
+ expect(state.fetchingState.image.isFetching).toBeFalsy()
+ })
+
+ it('FETCH_MEDIA_ERROR updates state', () => {
+ mutations[FETCH_MEDIA_ERROR](state, {
+ mediaType: IMAGE,
+ errorMessage: 'error',
+ })
+
+ expect(state.fetchingState.image.isFetching).toBeFalsy()
+ expect(state.fetchingState.image.fetchingError).toBeTruthy()
+ expect(state.fetchingState.image.fetchingError).toBe('error')
+ })
+
+ it('SET_AUDIO updates state', () => {
+ const params = { audio: { title: 'Foo', creator: 'bar', tags: [] } }
+ mutations[SET_AUDIO](state, params)
+
+ expect(state.audio).toEqual(params.audio)
+ })
+
+ it('SET_IMAGE updates state', () => {
+ const params = { image: { title: 'Foo', creator: 'bar', tags: [] } }
+ mutations[SET_IMAGE](state, params)
+
+ expect(state.image).toEqual(params.image)
+ })
+
+ it('SET_MEDIA updates state persisting images', () => {
+ const img1 = { title: 'Foo', creator: 'foo', tags: [] }
+ const img2 = { title: 'Bar', creator: 'bar', tags: [] }
+ state.results.image.items = [img1]
+ const params = {
+ media: [img2],
+ mediaCount: 2,
+ page: 2,
+ shouldPersistMedia: true,
+ mediaType: IMAGE,
+ }
+ mutations[SET_MEDIA](state, params)
+
+ expect(state.results.image.items).toEqual([img1, img2])
+ expect(state.results.image.count).toBe(params.mediaCount)
+ expect(state.results.image.page).toBe(params.page)
+ })
+
+ it('SET_MEDIA updates state not persisting images', () => {
+ const img = { title: 'Foo', creator: 'bar', tags: [] }
+ state.results.image.items = ['img1']
+ const params = {
+ media: [img],
+ mediaCount: 2,
+ page: 2,
+ shouldPersistMedia: false,
+ mediaType: IMAGE,
+ }
+ mutations[SET_MEDIA](state, params)
+
+ expect(state.results.image.items).toEqual([img])
+ expect(state.results.image.count).toBe(params.mediaCount)
+ expect(state.results.image.page).toBe(params.page)
+ })
+
+ it('SET_MEDIA updates state with default count and page', () => {
+ const img = { title: 'Foo', creator: 'bar', tags: [] }
+ state.results.image.items = ['img1']
+ const params = { media: [img], mediaType: IMAGE }
+ mutations[SET_MEDIA](state, params)
+
+ expect(state.results.image.count).toBe(0)
+ expect(state.results.image.page).toBe(1)
+ })
+
+ it('MEDIA_NOT_FOUND throws an error', () => {
+ expect(() =>
+ mutations[MEDIA_NOT_FOUND](state, { mediaType: AUDIO })
+ ).toThrow('Media of type audio not found')
+ })
+
+ it('RESET_MEDIA resets the media type state', () => {
+ state = {
+ results: {
+ image: {
+ items: [{ id: 'image1' }, { id: 'image2' }],
+ page: 2,
+ count: 200,
+ pageCount: 2,
+ },
+ },
+ }
+
+ mutations[RESET_MEDIA](state, { mediaType: IMAGE })
+ expect(state.results.image.items).toStrictEqual([])
+ expect(state.results.image.count).toEqual(0)
+ expect(state.results.image.page).toBe(undefined)
+ expect(state.results.image.pageCount).toEqual(0)
+ })
+ })
+
+ describe('actions', () => {
+ const searchData = { results: ['foo'], result_count: 1 }
+ const audioDetailData = 'audioDetails'
+ const imageDetailData = 'imageDetails'
+ let services = null
+ let audioServiceMock = null
+ let imageServiceMock = null
+ let state
+ let context
+ beforeEach(() => {
+ imageServiceMock = {
+ search: jest.fn(() => Promise.resolve({ data: searchData })),
+ getProviderCollection: jest.fn(() =>
+ Promise.resolve({ data: searchData })
+ ),
+ getMediaDetail: jest.fn(() =>
+ Promise.resolve({ data: imageDetailData })
+ ),
+ }
+ audioServiceMock = {
+ search: jest.fn(() => Promise.resolve({ data: searchData })),
+ getProviderCollection: jest.fn(() =>
+ Promise.resolve({ data: searchData })
+ ),
+ getMediaDetail: jest.fn(() =>
+ Promise.resolve({ data: audioDetailData })
+ ),
+ }
+ services = { [AUDIO]: audioServiceMock, [IMAGE]: imageServiceMock }
+ state = {
+ results: {
+ image: {
+ items: [{ id: 'foo' }, { id: 'bar' }, { id: 'zeta' }],
+ },
+ audio: {
+ items: [{ id: 'foo' }, { id: 'bar' }, { id: 'zeta' }],
+ },
+ },
+ }
+
+ context = {
+ commit: jest.fn(),
+ dispatch: jest.fn(),
+ rootState: {
+ user: { usageSessionId: 'foo' },
+ search: { query: { q: 'cat' } },
+ },
+ 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,
+ }
+ const action = createActions(services)[FETCH_MEDIA]
+ await action(context, params)
+ expect(context.commit).toHaveBeenCalledWith(FETCH_START_MEDIA, {
+ mediaType: IMAGE,
+ })
+ expect(context.commit).toHaveBeenCalledWith(FETCH_END_MEDIA, {
+ mediaType: IMAGE,
+ })
+
+ expect(context.commit).toHaveBeenCalledWith(SET_MEDIA, {
+ media: searchData.results,
+ mediaCount: searchData.result_count,
+ shouldPersistMedia: params.shouldPersistMedia,
+ page: params.page,
+ mediaType: IMAGE,
+ })
+ delete params.mediaType
+ expect(services[IMAGE].search).toHaveBeenCalledWith(params)
+ })
+
+ it('FETCH_MEDIA dispatches SEND_SEARCH_QUERY_EVENT', async () => {
+ const params = { q: 'foo', shouldPersistMedia: false, mediaType: IMAGE }
+ const action = createActions(services)[FETCH_MEDIA]
+ await action(context, params)
+
+ expect(context.dispatch).toHaveBeenCalledWith(
+ `${USAGE_DATA}/${SEND_SEARCH_QUERY_EVENT}`,
+ {
+ query: params.q,
+ sessionId: context.rootState.user.usageSessionId,
+ },
+ { root: true }
+ )
+ })
+
+ it('does not dispatch SEND_SEARCH_QUERY_EVENT if page param is available', async () => {
+ const params = {
+ q: 'foo',
+ page: 1,
+ shouldPersistMedia: false,
+ mediaType: IMAGE,
+ }
+ const action = createActions(services)[FETCH_MEDIA]
+ await action(context, params)
+
+ expect(context.dispatch).not.toHaveBeenCalledWith(
+ `${USAGE_DATA}/${SEND_SEARCH_QUERY_EVENT}`,
+ {
+ query: params.q,
+ sessionId: context.rootState.user.usageSessionId,
+ }
+ )
+ })
+
+ it('FETCH_MEDIA on error', async () => {
+ const mediaType = IMAGE
+ services[IMAGE] = {
+ search: jest.fn(() => Promise.reject('error')),
+ }
+ const params = {
+ q: 'foo',
+ page: 1,
+ shouldPersistMedia: false,
+ mediaType,
+ }
+ const action = createActions(services)[FETCH_MEDIA]
+ await action(context, params)
+ await expect(services[IMAGE].search).rejects.toEqual('error')
+
+ expect(context.commit).toHaveBeenCalledWith(FETCH_START_MEDIA, {
+ mediaType,
+ })
+ expect(context.dispatch).toHaveBeenCalledWith(HANDLE_MEDIA_ERROR, {
+ error: 'error',
+ mediaType,
+ })
+ })
+
+ it('FETCH_MEDIA resets images if page is not defined', async () => {
+ const mediaType = IMAGE
+ const params = {
+ q: 'foo',
+ page: undefined,
+ shouldPersistMedia: false,
+ mediaType,
+ }
+ const action = createActions(services)[FETCH_MEDIA]
+ await action(context, params)
+
+ expect(context.commit).toHaveBeenCalledWith(FETCH_START_MEDIA, {
+ mediaType,
+ })
+ expect(context.commit).toHaveBeenCalledWith(RESET_MEDIA, { mediaType })
+ expect(context.commit).toHaveBeenCalledWith(FETCH_END_MEDIA, {
+ mediaType,
+ })
+ })
+
+ it('FETCH_MEDIA does not reset images if page is defined', async () => {
+ const mediaType = IMAGE
+ const params = {
+ q: 'foo',
+ page: 1,
+ shouldPersistMedia: false,
+ mediaType,
+ }
+ const action = createActions(services)[FETCH_MEDIA]
+ await action(context, params)
+
+ expect(context.commit).not.toHaveBeenCalledWith(RESET_MEDIA, {
+ mediaType,
+ })
+ })
+
+ it('FETCH_AUDIO on success', async () => {
+ const params = { id: 'foo' }
+ const action = createActions(services)[FETCH_AUDIO]
+ await action(context, params)
+ expect(context.commit).toHaveBeenCalledWith(SET_AUDIO, { audio: {} })
+ expect(context.commit).toHaveBeenCalledWith(SET_AUDIO, {
+ audio: audioDetailData,
+ })
+ expect(audioServiceMock.getMediaDetail).toHaveBeenCalledWith(params)
+ })
+
+ it('FETCH_AUDIO dispatches SEND_RESULT_CLICKED_EVENT', () => {
+ const params = { id: 'foo' }
+ const action = createActions(services)[FETCH_AUDIO]
+ action(context, params)
+
+ expect(context.dispatch).toHaveBeenLastCalledWith(
+ `${USAGE_DATA}/${SEND_RESULT_CLICKED_EVENT}`,
+ {
+ query: context.rootState.search.query.q,
+ resultUuid: 'foo',
+ resultRank: 0,
+ sessionId: context.rootState.user.usageSessionId,
+ },
+ { root: true }
+ )
+ })
+
+ it('FETCH_AUDIO on error', async () => {
+ services[AUDIO] = {
+ getMediaDetail: jest.fn(() => Promise.reject('error')),
+ }
+ const params = { id: 'foo' }
+ const action = createActions(services)[FETCH_AUDIO]
+ await action(context, params)
+ await expect(services[AUDIO].getMediaDetail).rejects.toEqual('error')
+
+ expect(context.dispatch).toHaveBeenLastCalledWith(HANDLE_MEDIA_ERROR, {
+ error: 'error',
+ mediaType: 'audio',
+ })
+ })
+
+ it('FETCH_AUDIO on 404 doesnt break and commits MEDIA_NOT_FOUND', async () => {
+ const mediaType = AUDIO
+ services[AUDIO] = {
+ getMediaDetail: jest.fn(() =>
+ Promise.reject({ response: { status: 404 } })
+ ),
+ }
+ const params = { id: 'foo' }
+ const action = createActions(services)[FETCH_AUDIO]
+ await action(context, params)
+ expect(context.commit).toHaveBeenCalledWith(MEDIA_NOT_FOUND, {
+ mediaType,
+ })
+ })
+
+ it('FETCH_IMAGE on success', async () => {
+ const params = { id: 'foo' }
+ const action = createActions(services)[FETCH_IMAGE]
+ await action(context, params)
+ expect(context.commit).toHaveBeenCalledWith(SET_IMAGE, { image: {} })
+ expect(context.commit).toHaveBeenCalledWith(SET_IMAGE, {
+ image: imageDetailData,
+ })
+
+ expect(imageServiceMock.getMediaDetail).toHaveBeenCalledWith(params)
+ })
+
+ it('FETCH_IMAGE dispatches SEND_RESULT_CLICKED_EVENT', () => {
+ const params = { id: 'foo' }
+ const action = createActions(services)[FETCH_IMAGE]
+ action(context, params)
+
+ expect(context.dispatch).toHaveBeenLastCalledWith(
+ `${USAGE_DATA}/${SEND_RESULT_CLICKED_EVENT}`,
+ {
+ query: context.rootState.search.query.q,
+ resultUuid: 'foo',
+ resultRank: 0,
+ sessionId: context.rootState.user.usageSessionId,
+ },
+ { root: true }
+ )
+ })
+
+ it('FETCH_IMAGE on error', async () => {
+ services[IMAGE] = {
+ getMediaDetail: jest.fn(() =>
+ Promise.reject(new Error('Server error'))
+ ),
+ }
+ const params = { id: 'foo' }
+ const action = createActions(services)[FETCH_IMAGE]
+ await expect(action(context, params)).rejects.toThrow(
+ 'Error fetching the image: Server error'
+ )
+ })
+
+ it('FETCH_IMAGE on 404 doesnt break and commits MEDIA_NOT_FOUND', async () => {
+ const mediaType = IMAGE
+ services[IMAGE] = {
+ getMediaDetail: jest.fn(() =>
+ Promise.reject({ response: { status: 404 } })
+ ),
+ }
+ const params = { id: 'foo' }
+ const action = createActions(services)[FETCH_IMAGE]
+ await action(context, params)
+ expect(context.commit).toHaveBeenCalledWith(MEDIA_NOT_FOUND, {
+ mediaType,
+ })
+ })
+
+ it('HANDLE_MEDIA_ERROR handles 500 error', () => {
+ const action = createActions(services)[HANDLE_MEDIA_ERROR]
+ const error = { response: { status: 500, message: 'Server error' } }
+
+ action(context, { mediaType: AUDIO, error })
+ expect(context.commit).toHaveBeenCalledWith(FETCH_MEDIA_ERROR, {
+ errorMessage: 'There was a problem with our servers',
+ mediaType: AUDIO,
+ })
+ })
+
+ it('HANDLE_MEDIA_ERROR handles a 403 error', () => {
+ const action = createActions(services)[HANDLE_MEDIA_ERROR]
+ const error = { response: { status: 403, message: 'Server error' } }
+
+ action(context, { mediaType: AUDIO, error })
+ expect(context.commit).toHaveBeenCalledWith(FETCH_MEDIA_ERROR, {
+ errorMessage: error.response.message,
+ mediaType: AUDIO,
+ })
+ })
+
+ it('HANDLE_MEDIA_ERROR throws a new error on error when server did not respond', async () => {
+ const action = createActions(services)[HANDLE_MEDIA_ERROR]
+ const error = new Error('Server did not respond')
+ await expect(
+ action(context, { mediaType: AUDIO, error })
+ ).rejects.toThrow(error.message)
+ })
+
+ it('HANDLE_NO_MEDIA throws an error when media count is 0', async () => {
+ const action = createActions(services)[HANDLE_NO_MEDIA]
+ await action(context, { mediaCount: 0, mediaType: IMAGE })
+ expect(context.commit).toHaveBeenLastCalledWith(FETCH_MEDIA_ERROR, {
+ errorMessage: 'No image found for this query',
+ })
+ })
+
+ it('HANDLE_NO_MEDIA does not throw an error when media count is not 0', () => {
+ const action = createActions(services)[HANDLE_NO_MEDIA]
+ action(context, { mediaCount: 1, mediaType: IMAGE })
+ expect(context.commit.mock.calls.length).toEqual(0)
+ })
+ })
+})
diff --git a/test/unit/specs/store/provider.spec.js b/test/unit/specs/store/provider.spec.js
index d4efef578..ef5b3faea 100644
--- a/test/unit/specs/store/provider.spec.js
+++ b/test/unit/specs/store/provider.spec.js
@@ -55,16 +55,6 @@ describe('Image Provider Store', () => {
expect(store.state.isFetchingImageProvidersError).toBe(params.error)
})
-
- it('SET_IMAGE_PROVIDERS sets imageProviders', () => {
- const params = {
- mediaType: 'image',
- providers: [{ name: 'testProvider' }],
- }
- store.mutations[SET_MEDIA_PROVIDERS](store.state, params)
-
- expect(store.state.imageProviders).toBe(params.providers)
- })
})
describe('actions', () => {
diff --git a/test/unit/specs/store/search-store.spec.js b/test/unit/specs/store/search-store.spec.js
index 6db5a7ee9..638ff0699 100644
--- a/test/unit/specs/store/search-store.spec.js
+++ b/test/unit/specs/store/search-store.spec.js
@@ -1,573 +1,349 @@
-import store, { createActions } from '~/store/search'
+import store, { filterData } from '~/store/search'
import {
- FETCH_END_MEDIA,
- FETCH_MEDIA_ERROR,
- FETCH_START_MEDIA,
- MEDIA_NOT_FOUND,
- RESET_MEDIA,
- SET_AUDIO,
- SET_IMAGE,
- SET_IMAGE_PAGE,
- SET_MEDIA,
- SET_QUERY,
- SET_SEARCH_TYPE,
- UPDATE_FILTERS,
-} from '~/constants/mutation-types'
-import {
- FETCH_AUDIO,
- FETCH_IMAGE,
- FETCH_MEDIA,
- HANDLE_MEDIA_ERROR,
- HANDLE_NO_MEDIA,
- SET_SEARCH_TYPE_FROM_URL,
+ SET_SEARCH_STATE_FROM_URL,
+ TOGGLE_FILTER,
+ UPDATE_QUERY_FROM_FILTERS,
UPDATE_SEARCH_TYPE,
} from '~/constants/action-types'
-import { ALL_MEDIA, AUDIO, IMAGE } from '~/constants/media'
import {
- SEND_RESULT_CLICKED_EVENT,
- SEND_SEARCH_QUERY_EVENT,
-} from '~/constants/usage-data-analytics-types'
-import { FILTER, USAGE_DATA } from '~/constants/store-modules'
+ SET_FILTER,
+ SET_PROVIDERS_FILTERS,
+ CLEAR_FILTERS,
+ SET_FILTER_IS_VISIBLE,
+ REPLACE_FILTERS,
+ SET_SEARCH_TYPE,
+ CLEAR_OTHER_MEDIA_TYPE_FILTERS,
+ SET_QUERY,
+} from '~/constants/mutation-types'
+import { ALL_MEDIA, AUDIO, IMAGE } from '~/constants/media'
-describe('Search Store', () => {
+describe('Filter Store', () => {
describe('state', () => {
- it('exports default state', () => {
- const state = store.state()
- expect(state.audios).toHaveLength(0)
- expect(state.audiosCount).toBe(0)
- expect(state.audioPage).toBe(1)
- expect(state.images).toHaveLength(0)
- expect(state.imagesCount).toBe(0)
- expect(state.imagePage).toBe(1)
- expect(state.pageCount.audios).toBe(0)
- expect(state.pageCount.images).toBe(0)
- expect(state.isFetching.audios).toBeFalsy()
- expect(state.isFetching.images).toBeFalsy()
- expect(state.isFetchingError.audios).toBeTruthy()
- expect(state.isFetchingError.images).toBeTruthy()
- expect(state.query.q).toBe(undefined)
- expect(state.errorMessage).toBe(null)
- })
- })
-
- describe('mutations', () => {
- let state = null
- const mutations = store.mutations
+ it('state contains all filters', () => {
+ const defaultState = store.state()
- beforeEach(() => {
- state = store.state()
+ expect(defaultState.filters).toEqual(filterData)
})
- it('FETCH_START_MEDIA updates state', () => {
- mutations[FETCH_START_MEDIA](state, { mediaType: IMAGE })
+ it('state has filter hidden', () => {
+ const defaultState = store.state()
- expect(state.isFetching.images).toBeTruthy()
- expect(state.isFetchingError.images).toBeFalsy()
+ expect(defaultState.isFilterVisible).toBeFalsy()
})
- it('FETCH_END_MEDIA updates state', () => {
- mutations[FETCH_END_MEDIA](state, { mediaType: IMAGE })
-
- expect(state.isFetching.images).toBeFalsy()
+ it('isFilterVisible should be false when innerWidth property is undefined', () => {
+ window.innerWidth = undefined
+ const state = store.state()
+ expect(state.isFilterVisible).toBeFalsy()
})
-
- it('FETCH_MEDIA_ERROR updates state', () => {
- mutations[FETCH_MEDIA_ERROR](state, {
- mediaType: IMAGE,
- errorMessage: 'error',
- })
-
- expect(state.isFetching.images).toBeFalsy()
- expect(state.isFetchingError.images).toBeTruthy()
- expect(state.errorMessage).toBe('error')
+ it('isFilterVisible should be false when window width is less then 800', () => {
+ window.innerWidth = 500
+ const state = store.state()
+ expect(state.isFilterVisible).toBeFalsy()
})
+ })
- it('SET_AUDIO updates state', () => {
- const params = { audio: { title: 'Foo', creator: 'bar', tags: [] } }
- mutations[SET_AUDIO](state, params)
+ describe('mutations', () => {
+ let state = null
+ let mutations = null
+ let getters = null
- expect(state.audio).toEqual(params.audio)
+ beforeEach(() => {
+ state = {
+ search: {
+ searchType: 'image',
+ query: { q: 'foo' },
+ },
+ ...store.state(),
+ }
+ mutations = store.mutations
+ getters = store.getters
})
- it('SET_IMAGE updates state', () => {
- const params = { image: { title: 'Foo', creator: 'bar', tags: [] } }
- mutations[SET_IMAGE](state, params)
+ it('SET_QUERY updates state', () => {
+ const params = { query: { q: 'foo' } }
+ mutations[SET_QUERY](state, params)
- expect(state.image).toEqual(params.image)
+ expect(state.query.q).toBe(params.query.q)
})
- it('SET_IMAGE_PAGE updates state', () => {
- const params = { imagePage: 1 }
- mutations[SET_IMAGE_PAGE](state, params)
-
- expect(state.imagePage).toBe(params.imagePage)
+ it('SET_SEARCH_TYPE updates the state', () => {
+ state.searchType = IMAGE
+ mutations[SET_SEARCH_TYPE](state, { searchType: AUDIO })
+ expect(state.searchType).toEqual(AUDIO)
})
- it('SET_MEDIA updates state persisting images', () => {
- const img1 = { title: 'Foo', creator: 'foo', tags: [] }
- const img2 = { title: 'Bar', creator: 'bar', tags: [] }
- state.images = [img1]
- const params = {
- media: [img2],
- mediaCount: 2,
- page: 2,
- shouldPersistMedia: true,
- mediaType: IMAGE,
+ it.each`
+ filterType | codeIdx
+ ${'licenses'} | ${0}
+ ${'licenseTypes'} | ${0}
+ ${'imageExtensions'} | ${0}
+ ${'imageCategories'} | ${0}
+ ${'searchBy'} | ${0}
+ ${'aspectRatios'} | ${0}
+ ${'sizes'} | ${0}
+ `(
+ 'SET_FILTER updates $filterType filter state',
+ ({ filterType, codeIdx }) => {
+ mutations[SET_FILTER](state, { filterType, codeIdx })
+
+ expect(state.filters[filterType][codeIdx].checked).toBeTruthy()
}
- mutations[SET_MEDIA](state, params)
+ )
+
+ it('SET_FILTER updates mature', () => {
+ mutations[SET_FILTER](state, { filterType: 'mature' })
- expect(state.images).toEqual([img1, img2])
- expect(state.imagesCount).toBe(params.mediaCount)
- expect(state.imagePage).toBe(params.page)
+ expect(state.filters.mature).toBeTruthy()
})
- it('SET_MEDIA updates state not persisting images', () => {
- const img = { title: 'Foo', creator: 'bar', tags: [] }
- state.images = ['img1']
- const params = {
- media: [img],
- mediaCount: 2,
- page: 2,
- shouldPersistMedia: false,
- mediaType: IMAGE,
- }
- mutations[SET_MEDIA](state, params)
+ it('SET_FILTER toggles mature', () => {
+ state.filters.mature = true
+ mutations[SET_FILTER](state, { filterType: 'mature' })
- expect(state.images).toEqual([img])
- expect(state.imagesCount).toBe(params.mediaCount)
- expect(state.imagePage).toBe(params.page)
+ expect(state.filters.mature).toBeFalsy()
})
- it('SET_MEDIA updates state with default count and page', () => {
- const img = { title: 'Foo', creator: 'bar', tags: [] }
- state.images = ['img1']
- const params = { media: [img], mediaType: IMAGE }
- mutations[SET_MEDIA](state, params)
+ it('SET_FILTER updates isFilterApplied with provider', () => {
+ state.filters.imageProviders = [{ code: 'met', checked: false }]
+ mutations[SET_FILTER](state, { filterType: 'imageProviders', codeIdx: 0 })
- expect(state.imagesCount).toBe(0)
- expect(state.imagePage).toBe(1)
+ expect(getters.isAnyFilterApplied).toBeTruthy()
})
- it('SET_QUERY updates state', () => {
- const params = { query: { q: 'foo' } }
- mutations[SET_QUERY](state, params)
+ it('SET_FILTER updates isFilterApplied with license type', () => {
+ mutations[SET_FILTER](state, { filterType: 'licenseTypes', codeIdx: 0 })
- expect(state.query.q).toBe(params.query.q)
+ expect(getters.isAnyFilterApplied).toBeTruthy()
})
- it('SET_QUERY resets images to empty array', () => {
- const params = { query: { q: 'bar' } }
- state.query = {
- q: 'foo',
- images: [{ id: 'foo' }],
- }
- mutations[SET_QUERY](state, params)
+ it('SET_PROVIDERS_FILTERS merges with existing provider filters', () => {
+ const existingProviderFilters = [{ code: 'met', checked: true }]
- expect(state.query.q).toBe('bar')
- expect(state.images).toEqual([])
- })
+ const providers = [
+ { source_name: 'met', display_name: 'Metropolitan' },
+ { source_name: 'flickr', display_name: 'Flickr' },
+ ]
- it('MEDIA_NOT_FOUND throws an error', () => {
- expect(() =>
- mutations[MEDIA_NOT_FOUND](state, { mediaType: AUDIO })
- ).toThrow('Media of type audio not found')
- })
+ state.filters.imageProviders = existingProviderFilters
- it('SET_SEARCH_TYPE updates the state', () => {
- state.searchType = IMAGE
- mutations[SET_SEARCH_TYPE](state, { searchType: AUDIO })
- expect(state.searchType).toEqual(AUDIO)
+ mutations[SET_PROVIDERS_FILTERS](state, {
+ mediaType: 'image',
+ providers: providers,
+ })
+
+ expect(state.filters.imageProviders).toEqual([
+ { code: 'met', name: 'Metropolitan', checked: true },
+ { code: 'flickr', name: 'Flickr', checked: false },
+ ])
})
- it('RESET_MEDIA resets the media type state', () => {
- state = {
- images: [{ id: 'image1' }, { id: 'image2' }],
- imagePage: 2,
- imagesCount: 200,
- pageCount: {
- images: 2,
- },
- }
+ it('SET_FILTER_IS_VISIBLE updates state', () => {
+ const params = { isFilterVisible: 'bar' }
+ mutations[SET_FILTER_IS_VISIBLE](state, params)
- mutations[RESET_MEDIA](state, { mediaType: IMAGE })
- expect(state.images).toStrictEqual([])
- expect(state.imagesCount).toEqual(0)
- expect(state.imagePage).toBe(undefined)
- expect(state.pageCount.images).toEqual(0)
+ expect(state.isFilterVisible).toBe(params.isFilterVisible)
})
})
describe('actions', () => {
- const searchData = { results: ['foo'], result_count: 1 }
- const audioDetailData = 'audioDetails'
- const imageDetailData = 'imageDetails'
- let services = null
- let audioServiceMock = null
- let imageServiceMock = null
- let state
- let context
- beforeEach(() => {
- imageServiceMock = {
- search: jest.fn(() => Promise.resolve({ data: searchData })),
- getProviderCollection: jest.fn(() =>
- Promise.resolve({ data: searchData })
- ),
- getMediaDetail: jest.fn(() =>
- Promise.resolve({ data: imageDetailData })
- ),
- }
- audioServiceMock = {
- search: jest.fn(() => Promise.resolve({ data: searchData })),
- getProviderCollection: jest.fn(() =>
- Promise.resolve({ data: searchData })
- ),
- getMediaDetail: jest.fn(() =>
- Promise.resolve({ data: audioDetailData })
- ),
- }
- services = { [AUDIO]: audioServiceMock, [IMAGE]: imageServiceMock }
- state = {
- audios: [{ id: 'foo' }, { id: 'bar' }, { id: 'zeta' }],
- images: [{ id: 'foo' }, { id: 'bar' }, { id: 'zeta' }],
- query: { q: 'foo query' },
- }
+ let state = null
+ let commitMock = null
+ let dispatchMock = null
+ let actions = null
+ let context = null
+ beforeEach(() => {
+ commitMock = jest.fn()
+ dispatchMock = jest.fn()
+ state = store.state()
+ actions = store.actions
context = {
- commit: jest.fn(),
- dispatch: jest.fn(),
- rootState: { user: { usageSessionId: 'foo' } },
+ commit: commitMock,
+ dispatch: dispatchMock,
+ rootState: {},
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,
+ it.each`
+ searchType | path | mediaType
+ ${'all'} | ${'/search/'} | ${'image'}
+ ${'image'} | ${'/search/image/'} | ${'image'}
+ ${'audio'} | ${'/search/audio/'} | ${'audio'}
+ ${'video'} | ${'/search/video'} | ${null}
+ `(
+ "SET_SEARCH_STATE_FROM_URL should set searchType '$searchType' and mediaType '$mediaType' from path '$path'",
+ ({ searchType, path, mediaType }) => {
+ actions[SET_SEARCH_STATE_FROM_URL](
+ { commit: commitMock, dispatch: dispatchMock, state },
+ { path: path, query: {} }
+ )
+ expect(commitMock).toHaveBeenLastCalledWith(SET_SEARCH_TYPE, {
+ searchType,
+ })
+ expect(dispatchMock).toHaveBeenCalledWith(UPDATE_QUERY_FROM_FILTERS, {
+ mediaType: mediaType,
+ })
}
- 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,
- shouldPersistMedia: false,
- mediaType: IMAGE,
+ )
+
+ it.each`
+ query | path | mediaType
+ ${{ license: 'cc0,by' }} | ${'/search/'} | ${'image'}
+ ${{ searchBy: 'creator' }} | ${'/search/image/'} | ${'image'}
+ ${{ mature: 'true' }} | ${'/search/audio/'} | ${'audio'}
+ ${{ durations: 'medium' }} | ${'/search/image'} | ${'image'}
+ `(
+ "SET_SEARCH_STATE_FROM_URL should set query '$searchType' from query '$path'",
+ ({ path, query, mediaType }) => {
+ actions[SET_SEARCH_STATE_FROM_URL](
+ { commit: commitMock, dispatch: dispatchMock, state },
+ { path: path, query: query }
+ )
+ expect(dispatchMock).toHaveBeenCalledWith(UPDATE_QUERY_FROM_FILTERS, {
+ mediaType,
+ })
}
- const action = createActions(services)[FETCH_MEDIA]
- await action(context, params)
- expect(context.commit).toHaveBeenCalledWith(FETCH_START_MEDIA, {
- mediaType: IMAGE,
- })
- expect(context.commit).toHaveBeenCalledWith(FETCH_END_MEDIA, {
- mediaType: IMAGE,
- })
+ )
- expect(context.commit).toHaveBeenCalledWith(SET_MEDIA, {
- media: searchData.results,
- mediaCount: searchData.result_count,
- shouldPersistMedia: params.shouldPersistMedia,
- page: params.page,
- mediaType: IMAGE,
- })
- expect(services[IMAGE].search).toHaveBeenCalledWith(params)
- })
-
- it('FETCH_MEDIA dispatches SEND_SEARCH_QUERY_EVENT', async () => {
- const params = { q: 'foo', shouldPersistMedia: false, mediaType: IMAGE }
- const action = createActions(services)[FETCH_MEDIA]
- await action(context, params)
+ it('SET_SEARCH_STATE_FROM_URL sets search type to image', () => {
+ const path = '/search/image'
+ const query = { q: 'cat', source: 'met' }
+ actions[SET_SEARCH_STATE_FROM_URL](context, { path, query })
- expect(context.dispatch).toHaveBeenCalledWith(
- `${USAGE_DATA}/${SEND_SEARCH_QUERY_EVENT}`,
- {
- query: params.q,
- sessionId: context.rootState.user.usageSessionId,
- },
- { root: true }
- )
- })
-
- it('does not dispatch SEND_SEARCH_QUERY_EVENT if page param is available', async () => {
- const params = {
- q: 'foo',
- page: 1,
- shouldPersistMedia: false,
- mediaType: IMAGE,
- }
- const action = createActions(services)[FETCH_MEDIA]
- await action(context, params)
-
- expect(context.dispatch).not.toHaveBeenCalledWith(
- `${USAGE_DATA}/${SEND_SEARCH_QUERY_EVENT}`,
- {
- query: params.q,
- sessionId: context.rootState.user.usageSessionId,
- }
- )
- })
-
- it('FETCH_MEDIA on error', async () => {
- const mediaType = IMAGE
- services[IMAGE] = {
- search: jest.fn(() => Promise.reject('error')),
- }
- const params = {
- q: 'foo',
- page: 1,
- shouldPersistMedia: false,
- mediaType,
- }
- const action = createActions(services)[FETCH_MEDIA]
- await action(context, params)
- await expect(services[IMAGE].search).rejects.toEqual('error')
-
- expect(context.commit).toHaveBeenCalledWith(FETCH_START_MEDIA, {
- mediaType,
- })
- expect(context.dispatch).toHaveBeenCalledWith(HANDLE_MEDIA_ERROR, {
- error: 'error',
- mediaType,
+ expect(context.commit).toHaveBeenLastCalledWith(SET_SEARCH_TYPE, {
+ searchType: IMAGE,
})
})
- it('FETCH_MEDIA resets images if page is not defined', async () => {
- const mediaType = IMAGE
- const params = {
- q: 'foo',
- page: undefined,
- shouldPersistMedia: false,
- mediaType,
- }
- const action = createActions(services)[FETCH_MEDIA]
- await action(context, params)
+ it('SET_SEARCH_STATE_FROM_URL sets search type to ALL_MEDIA if URL param is not set', () => {
+ const action = actions[SET_SEARCH_STATE_FROM_URL]
- expect(context.commit).toHaveBeenCalledWith(FETCH_START_MEDIA, {
- mediaType,
+ action(context, {
+ path: '/search/',
+ query: { q: 'cat', source: 'met' },
})
- expect(context.commit).toHaveBeenCalledWith(RESET_MEDIA, { mediaType })
- expect(context.commit).toHaveBeenCalledWith(FETCH_END_MEDIA, {
- mediaType,
+ const searchType = ALL_MEDIA
+ expect(context.commit).toHaveBeenLastCalledWith(SET_SEARCH_TYPE, {
+ searchType,
})
})
- it('FETCH_MEDIA does not reset images if page is defined', async () => {
- const mediaType = IMAGE
- const params = {
- q: 'foo',
- page: 1,
- shouldPersistMedia: false,
- mediaType,
- }
- const action = createActions(services)[FETCH_MEDIA]
- await action(context, params)
-
- expect(context.commit).not.toHaveBeenCalledWith(RESET_MEDIA, {
- mediaType,
- })
- })
+ it('UPDATE_SEARCH_TYPE sets search type to ALL_MEDIA if URL param is not set', () => {
+ const action = actions[UPDATE_SEARCH_TYPE]
- it('FETCH_AUDIO on success', async () => {
- const params = { id: 'foo' }
- const action = createActions(services)[FETCH_AUDIO]
- await action(context, params)
- expect(context.commit).toHaveBeenCalledWith(SET_AUDIO, { audio: {} })
- expect(context.commit).toHaveBeenCalledWith(SET_AUDIO, {
- audio: audioDetailData,
+ action(context, { searchType: ALL_MEDIA })
+ expect(context.commit).toHaveBeenCalledWith(SET_SEARCH_TYPE, {
+ searchType: ALL_MEDIA,
})
- expect(audioServiceMock.getMediaDetail).toHaveBeenCalledWith(params)
- })
-
- it('FETCH_AUDIO dispatches SEND_RESULT_CLICKED_EVENT', () => {
- const params = { id: 'foo' }
- const action = createActions(services)[FETCH_AUDIO]
- action(context, params)
-
- expect(context.dispatch).toHaveBeenLastCalledWith(
- `${USAGE_DATA}/${SEND_RESULT_CLICKED_EVENT}`,
+ expect(context.commit).toHaveBeenCalledWith(
+ CLEAR_OTHER_MEDIA_TYPE_FILTERS,
{
- query: state.query.q,
- resultUuid: 'foo',
- resultRank: 0,
- sessionId: context.rootState.user.usageSessionId,
- },
- { root: true }
+ searchType: 'all',
+ }
)
})
- it('FETCH_AUDIO on error', async () => {
- services[AUDIO] = {
- getMediaDetail: jest.fn(() => Promise.reject('error')),
- }
- const params = { id: 'foo' }
- const action = createActions(services)[FETCH_AUDIO]
- await action(context, params)
- await expect(services[AUDIO].getMediaDetail).rejects.toEqual('error')
-
- expect(context.dispatch).toHaveBeenLastCalledWith(HANDLE_MEDIA_ERROR, {
- error: 'error',
- mediaType: 'audio',
+ it('CLEAR_FILTERS resets filters to initial state', async () => {
+ state.filters.licenses = [
+ { code: 'by', checked: true },
+ { code: 'by-nc', checked: true },
+ { code: 'by-nd', checked: true },
+ ]
+ actions[CLEAR_FILTERS]({
+ commit: commitMock,
+ dispatch: dispatchMock,
+ state,
})
- })
-
- it('FETCH_AUDIO on 404 doesnt break and commits MEDIA_NOT_FOUND', async () => {
- const mediaType = AUDIO
- services[AUDIO] = {
- getMediaDetail: jest.fn(() =>
- Promise.reject({ response: { status: 404 } })
- ),
- }
- const params = { id: 'foo' }
- const action = createActions(services)[FETCH_AUDIO]
- await action(context, params)
- expect(context.commit).toHaveBeenCalledWith(MEDIA_NOT_FOUND, {
- mediaType,
+ expect(commitMock).toHaveBeenCalledWith(REPLACE_FILTERS, {
+ newFilterData: filterData,
})
- })
-
- it('FETCH_IMAGE on success', async () => {
- const params = { id: 'foo' }
- const action = createActions(services)[FETCH_IMAGE]
- await action(context, params)
- expect(context.commit).toHaveBeenCalledWith(SET_IMAGE, { image: {} })
- expect(context.commit).toHaveBeenCalledWith(SET_IMAGE, {
- image: imageDetailData,
+ expect(dispatchMock).toHaveBeenCalledWith(UPDATE_QUERY_FROM_FILTERS, {
+ q: '',
})
-
- expect(imageServiceMock.getMediaDetail).toHaveBeenCalledWith(params)
})
- it('FETCH_IMAGE dispatches SEND_RESULT_CLICKED_EVENT', () => {
- const params = { id: 'foo' }
- const action = createActions(services)[FETCH_IMAGE]
- action(context, params)
+ it('CLEAR_FILTERS sets providers filters checked to false', async () => {
+ state.filters.imageProviders = [
+ { code: 'met', name: 'Metropolitan', checked: true },
+ { code: 'flickr', name: 'Flickr', checked: false },
+ ]
- expect(context.dispatch).toHaveBeenLastCalledWith(
- `${USAGE_DATA}/${SEND_RESULT_CLICKED_EVENT}`,
- {
- query: state.query.q,
- resultUuid: 'foo',
- resultRank: 0,
- sessionId: context.rootState.user.usageSessionId,
- },
- { root: true }
- )
- })
-
- it('FETCH_IMAGE on error', async () => {
- services[IMAGE] = {
- getMediaDetail: jest.fn(() =>
- Promise.reject(new Error('Server error'))
- ),
- }
- const params = { id: 'foo' }
- const action = createActions(services)[FETCH_IMAGE]
- await expect(action(context, params)).rejects.toThrow(
- 'Error fetching the image: Server error'
- )
- })
-
- it('FETCH_IMAGE on 404 doesnt break and commits MEDIA_NOT_FOUND', async () => {
- const mediaType = IMAGE
- services[IMAGE] = {
- getMediaDetail: jest.fn(() =>
- Promise.reject({ response: { status: 404 } })
- ),
+ actions[CLEAR_FILTERS]({
+ commit: commitMock,
+ dispatch: dispatchMock,
+ state,
+ })
+ const expectedFilters = {
+ ...state.filters,
+ imageProviders: [
+ { code: 'met', name: 'Metropolitan', checked: false },
+ { code: 'flickr', name: 'Flickr', checked: false },
+ ],
}
- const params = { id: 'foo' }
- const action = createActions(services)[FETCH_IMAGE]
- await action(context, params)
- expect(context.commit).toHaveBeenCalledWith(MEDIA_NOT_FOUND, {
- mediaType,
+ expect(commitMock).toHaveBeenCalledWith(REPLACE_FILTERS, {
+ newFilterData: expectedFilters,
})
- })
-
- it('HANDLE_MEDIA_ERROR handles 500 error', () => {
- const action = createActions(services)[HANDLE_MEDIA_ERROR]
- const error = { response: { status: 500, message: 'Server error' } }
-
- action(context, { mediaType: AUDIO, error })
- expect(context.commit).toHaveBeenCalledWith(FETCH_MEDIA_ERROR, {
- errorMessage: 'There was a problem with our servers',
- mediaType: AUDIO,
+ expect(dispatchMock).toHaveBeenCalledWith(UPDATE_QUERY_FROM_FILTERS, {
+ q: '',
})
})
- it('HANDLE_MEDIA_ERROR handles a 403 error', () => {
- const action = createActions(services)[HANDLE_MEDIA_ERROR]
- const error = { response: { status: 403, message: 'Server error' } }
-
- action(context, { mediaType: AUDIO, error })
- expect(context.commit).toHaveBeenCalledWith(FETCH_MEDIA_ERROR, {
- errorMessage: error.response.message,
- mediaType: AUDIO,
- })
- })
+ it.each`
+ filterType | code | idx
+ ${'licenses'} | ${'cc0'} | ${0}
+ ${'licenseTypes'} | ${'modification'} | ${1}
+ ${'imageExtensions'} | ${'svg'} | ${3}
+ ${'imageCategories'} | ${'photograph'} | ${0}
+ ${'searchBy'} | ${'creator'} | ${0}
+ ${'mature'} | ${undefined} | ${-1}
+ ${'aspectRatios'} | ${'tall'} | ${0}
+ ${'sizes'} | ${'medium'} | ${1}
+ `(
+ "TOGGLE_FILTER should set filter '$code' of type '$filterType",
+ ({ filterType, code, idx }) => {
+ actions[TOGGLE_FILTER](
+ { commit: commitMock, dispatch: dispatchMock, state },
+ { filterType: filterType, code: code }
+ )
+ expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {
+ filterType: filterType,
+ code: code,
+ codeIdx: idx,
+ })
+
+ expect(dispatchMock).toHaveBeenCalledWith(UPDATE_QUERY_FROM_FILTERS)
+ }
+ )
- it('HANDLE_MEDIA_ERROR throws a new error on error when server did not respond', async () => {
- const action = createActions(services)[HANDLE_MEDIA_ERROR]
- const error = new Error('Server did not respond')
- await expect(
- action(context, { mediaType: AUDIO, error })
- ).rejects.toThrow(error.message)
- })
+ it('TOGGLE_FILTER updates mature', () => {
+ actions[TOGGLE_FILTER](
+ { commit: commitMock, dispatch: dispatchMock, state },
+ { filterType: 'mature' }
+ )
- it('HANDLE_NO_MEDIA throws an error when media count is 0', async () => {
- const action = createActions(services)[HANDLE_NO_MEDIA]
- await action(context, { mediaCount: 0, mediaType: IMAGE })
- expect(context.commit).toHaveBeenLastCalledWith(FETCH_MEDIA_ERROR, {
- errorMessage: 'No image found for this query',
+ expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {
+ filterType: 'mature',
+ codeIdx: -1,
})
- })
- it('HANDLE_NO_MEDIA does not throw an error when media count is not 0', () => {
- const action = createActions(services)[HANDLE_NO_MEDIA]
- action(context, { mediaCount: 1, mediaType: IMAGE })
- expect(context.commit.mock.calls.length).toEqual(0)
+ expect(dispatchMock).toHaveBeenCalledWith(UPDATE_QUERY_FROM_FILTERS)
})
- it('SET_SEARCH_TYPE_FROM_URL sets search type to image', () => {
- const action = createActions(services)[SET_SEARCH_TYPE_FROM_URL]
- action(context, { url: '/search/image?q=cat&source=met' })
- expect(context.commit).toHaveBeenCalledWith(SET_SEARCH_TYPE, {
- searchType: IMAGE,
- })
- expect(context.commit).toHaveBeenCalledWith(
- `${FILTER}/${UPDATE_FILTERS}`,
- { searchType: IMAGE },
- { root: true }
+ it('TOGGLE_FILTER toggles mature', () => {
+ state.filters.mature = true
+ actions[TOGGLE_FILTER](
+ { commit: commitMock, dispatch: dispatchMock, state },
+ { filterType: 'mature' }
)
- })
- it('SET_SEARCH_TYPE_FROM_URL sets search type to ALL_MEDIA if URL param is not set', () => {
- const action = createActions(services)[SET_SEARCH_TYPE_FROM_URL]
- action(context, { url: '/search/?q=cat&source=met' })
- expect(context.commit).toHaveBeenCalledWith(SET_SEARCH_TYPE, {
- searchType: ALL_MEDIA,
+ expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {
+ filterType: 'mature',
+ codeIdx: -1,
})
- expect(context.commit).toHaveBeenCalledWith(
- `${FILTER}/${UPDATE_FILTERS}`,
- { searchType: 'all' },
- { root: true }
- )
- })
-
- it('UPDATE_SEARCH_TYPE sets search type to ALL_MEDIA if URL param is not set', () => {
- const action = createActions(services)[UPDATE_SEARCH_TYPE]
- action(context, { searchType: ALL_MEDIA })
- expect(context.commit).toHaveBeenCalledWith(SET_SEARCH_TYPE, {
- searchType: ALL_MEDIA,
- })
- expect(context.commit).toHaveBeenCalledWith(
- `${FILTER}/${UPDATE_FILTERS}`,
- { searchType: 'all' },
- { root: true }
- )
+ expect(dispatchMock).toHaveBeenCalledWith(UPDATE_QUERY_FROM_FILTERS)
})
})
})
diff --git a/test/unit/specs/utils/search-query-transform.spec.js b/test/unit/specs/utils/search-query-transform.spec.js
index ab4a8a668..d8f216147 100644
--- a/test/unit/specs/utils/search-query-transform.spec.js
+++ b/test/unit/specs/utils/search-query-transform.spec.js
@@ -4,7 +4,7 @@ import {
queryToFilterData,
queryStringToQueryData,
} from '~/utils/search-query-transform'
-import { filterData } from '~/store/filter'
+import { filterData } from '~/store/search'
import { IMAGE } from '~/constants/media'
describe('searchQueryTransform', () => {
@@ -110,9 +110,9 @@ describe('searchQueryTransform', () => {
const filters = {
...filterData,
}
- const query = ''
+ const query = {}
- const result = queryToFilterData(query)
+ const result = queryToFilterData({ query, defaultFilters: filters })
expect(result).toEqual(filters) // toEqual checks for value equality
})
it('queryToFilterData all image filters', () => {
@@ -246,14 +246,27 @@ describe('searchQueryTransform', () => {
],
mature: true,
}
- const queryString =
- 'http://localhost:8443/search/audio?q=cat&license=cc0&license_type=commercial&categories=music&extension=mp3&duration=medium&source=jamendo,wikimedia&searchBy=creator&mature=true'
+ const query = {
+ q: 'cat',
+ license: 'cc0',
+ license_type: 'commercial',
+ categories: 'music',
+ extension: 'mp3',
+ duration: 'medium',
+ source: 'jamendo',
+ searchBy: 'creator',
+ mature: 'true',
+ }
const testFilters = clonedeep(filters)
testFilters.audioProviders = [
{ code: 'jamendo', checked: true },
{ code: 'wikimedia', checked: true },
]
- const result = queryToFilterData(queryString, testFilters)
+ const result = queryToFilterData({
+ query,
+ searchType: 'audio',
+ defaultFilters: testFilters,
+ })
expect(result).toEqual(filters) // toEqual checks for value equality
})
it('queryStringToQueryData', () => {
diff --git a/test/unit/test-utils/sample-store.js b/test/unit/test-utils/sample-store.js
index 004432600..636f61265 100644
--- a/test/unit/test-utils/sample-store.js
+++ b/test/unit/test-utils/sample-store.js
@@ -1,4 +1,4 @@
-import SearchStore from '~/store/search'
+import SearchStore from '~/store/media'
import MediaProviderStore from '~/store/provider'
const store = {