Skip to content

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

Convert the search store to Pinia (#1040)

Olga Bulatd1f02ff71fd3
diff --git a/src/components/VAudioDetails/VAudioDetails.vue b/src/components/VAudioDetails/VAudioDetails.vue
index e846b79bf..e326f7685 100644
--- a/src/components/VAudioDetails/VAudioDetails.vue
+++ b/src/components/VAudioDetails/VAudioDetails.vue
@@ -82,12 +82,10 @@
</template>
<script>
-import { mapState } from 'vuex'
+import { mapGetters, mapState } from 'vuex'
import { PROVIDER } from '~/constants/store-modules'
-import getProviderName from '~/utils/get-provider-name'
-
import VLink from '~/components/VLink.vue'
import VAudioThumbnail from '~/components/VAudioThumbnail/VAudioThumbnail.vue'
import VMediaTag from '~/components/VMediaTag/VMediaTag.vue'
@@ -98,11 +96,12 @@ export default {
props: ['audio'],
computed: {
...mapState(PROVIDER, ['audioProviders']),
+ ...mapGetters(PROVIDER, ['getProviderName']),
providerName() {
- return getProviderName(this.audioProviders, this.$props.audio.provider)
+ return this.getProviderName(this.$props.audio.provider)
},
sourceName() {
- return getProviderName(this.audioProviders, this.$props.audio.source)
+ return this.getProviderName(this.$props.audio.source)
},
},
}
diff --git a/src/components/VContentSwitcher/VSearchTypeButton.vue b/src/components/VContentSwitcher/VSearchTypeButton.vue
index d20e8351c..dae58e957 100644
--- a/src/components/VContentSwitcher/VSearchTypeButton.vue
+++ b/src/components/VContentSwitcher/VSearchTypeButton.vue
@@ -32,9 +32,10 @@ import {
useContext,
} from '@nuxtjs/composition-api'
-import { ALL_MEDIA, supportedSearchTypes } from '~/constants/media'
+import { ALL_MEDIA } from '~/constants/media'
import useSearchType from '~/composables/use-search-type'
import { isMinScreen } from '~/composables/use-media-query'
+import { isValidSearchType } from '~/utils/prop-validators'
import VIcon from '~/components/VIcon/VIcon.vue'
import VButton from '~/components/VButton.vue'
@@ -52,7 +53,7 @@ export default defineComponent({
activeItem: {
type: String,
default: ALL_MEDIA,
- validator: (v) => supportedSearchTypes.includes(v),
+ validator: isValidSearchType,
},
type: {
type: String,
diff --git a/src/components/VContentSwitcher/VSearchTypeItem.vue b/src/components/VContentSwitcher/VSearchTypeItem.vue
index 9679e0bfb..6a1bcbe2a 100644
--- a/src/components/VContentSwitcher/VSearchTypeItem.vue
+++ b/src/components/VContentSwitcher/VSearchTypeItem.vue
@@ -16,10 +16,11 @@
</template>
<script>
-import { computed, useContext, useRoute } from '@nuxtjs/composition-api'
+import { computed, useContext } from '@nuxtjs/composition-api'
import { defineComponent } from '@vue/composition-api'
import { ALL_MEDIA, contentStatus } from '~/constants/media'
+import { useSearchStore } from '~/stores/search'
import VIcon from '~/components/VIcon/VIcon.vue'
import VItem from '~/components/VItemGroup/VItem.vue'
@@ -39,16 +40,14 @@ export default defineComponent({
props: propTypes,
setup(props) {
const { app } = useContext()
- const route = useRoute()
+ const searchStore = useSearchStore()
const status = computed(() => {
return contentStatus[props.item]
})
/**
- * The query is temporarily set to the incorrect value here: it uses the existing query
- * that is set for selected search type. When the search store conversion PR is merged,
- * we will set the query specific for the search type using `computeQueryParams(props.item)` method.
+ * The query sets the filters that are applicable for the specific search type.
*/
const component = computed(() => {
if (!props.useLinks) {
@@ -58,8 +57,7 @@ export default defineComponent({
as: 'VLink',
href: app.localePath({
path: `/search/${props.item === ALL_MEDIA ? '' : props.item}`,
- // query: searchStore.computeQueryParams(props.item),
- query: route.value.query,
+ query: searchStore.computeQueryParams(props.item),
}),
}
})
diff --git a/src/components/VContentSwitcher/VSearchTypeRadio.vue b/src/components/VContentSwitcher/VSearchTypeRadio.vue
index 95aafa307..65016264a 100644
--- a/src/components/VContentSwitcher/VSearchTypeRadio.vue
+++ b/src/components/VContentSwitcher/VSearchTypeRadio.vue
@@ -13,12 +13,8 @@
<script>
import { computed, defineComponent } from '@nuxtjs/composition-api'
-import {
- ALL_MEDIA,
- AUDIO,
- IMAGE,
- supportedSearchTypes,
-} from '~/constants/media'
+import { ALL_MEDIA, AUDIO, IMAGE } from '~/constants/media'
+import { isValidSearchType } from '~/utils/prop-validators'
import VIcon from '~/components/VIcon/VIcon.vue'
@@ -42,7 +38,7 @@ export default defineComponent({
searchType: {
type: String,
required: true,
- validator: (v) => supportedSearchTypes.includes(v),
+ validator: isValidSearchType,
},
selected: {
type: Boolean,
diff --git a/src/components/VErrorSection/VNoResults.vue b/src/components/VErrorSection/VNoResults.vue
index 0125b24fc..b87ac844c 100644
--- a/src/components/VErrorSection/VNoResults.vue
+++ b/src/components/VErrorSection/VNoResults.vue
@@ -1,6 +1,8 @@
<template>
<div class="no-results text-center md:text-left">
- <h5 class="text-5xl">{{ $t('no-results.heading', { query: query.q }) }}</h5>
+ <h5 class="text-5xl">
+ {{ $t('no-results.heading', { query: query.q }) }}
+ </h5>
<h6 class="text-3xl font-normal md:font-bold mt-10 md:mt-16">
{{ $t('no-results.alternatives') }}
</h6>
@@ -9,7 +11,7 @@
</template>
<script>
-import { supportedSearchTypes } from '~/constants/media'
+import { isValidSearchType } from '~/utils/prop-validators'
import VMetaSourceList from '~/components/VMetaSearch/VMetaSourceList.vue'
@@ -19,7 +21,7 @@ export default {
props: {
type: {
type: String,
- validator: (val) => supportedSearchTypes.includes(val),
+ validator: isValidSearchType,
},
query: {
type: Object,
diff --git a/src/components/VFilters/VFilterChecklist.vue b/src/components/VFilters/VFilterChecklist.vue
index 09cf4f62f..2863da465 100644
--- a/src/components/VFilters/VFilterChecklist.vue
+++ b/src/components/VFilters/VFilterChecklist.vue
@@ -56,7 +56,7 @@
</template>
<script>
-import { useFilterStore } from '~/stores/filter'
+import { useSearchStore } from '~/stores/search'
import VLicenseExplanation from '~/components/VFilters/VLicenseExplanation.vue'
import VCheckbox from '~/components/VCheckbox/VCheckbox.vue'
@@ -105,14 +105,14 @@ export default {
: this.$t(item.name)
},
onValueChange({ value }) {
- this.$emit('filterChanged', {
+ this.$emit('toggle-filter', {
code: value,
filterType: this.filterType,
})
},
isDisabled(item) {
return (
- useFilterStore().isFilterDisabled(item, this.filterType) ??
+ useSearchStore().isFilterDisabled(item, this.filterType) ??
this.disabled
)
},
diff --git a/src/components/VFilters/VSearchGridFilter.vue b/src/components/VFilters/VSearchGridFilter.vue
index bb47b8a0a..8ac4d2998 100644
--- a/src/components/VFilters/VSearchGridFilter.vue
+++ b/src/components/VFilters/VSearchGridFilter.vue
@@ -2,9 +2,6 @@
<div
class="filters py-8 px-10 min-h-full md:bg-dark-charcoal-06"
data-testid="filters-list"
- @onUpdateFilter="onUpdateFilter"
- @onToggleSearchGridFilter="$emit('close')"
- @onClearFilters="clearFilters"
>
<div class="flex items-center justify-between mt-2 mb-6">
<h4 class="text-sr font-semibold py-2 uppercase">
@@ -27,7 +24,7 @@
:options="filters[filterType]"
:title="filterTypeTitle(filterType)"
:filter-type="filterType"
- @filterChanged="onUpdateFilter"
+ @toggle-filter="toggleFilter"
/>
</form>
<footer v-if="isAnyFilterApplied" class="flex justify-between">
@@ -43,16 +40,17 @@
</template>
<script>
-import { computed, useContext, useRouter } from '@nuxtjs/composition-api'
+import {
+ computed,
+ useContext,
+ useRoute,
+ useRouter,
+ watch,
+} from '@nuxtjs/composition-api'
import { kebab } from 'case'
-import { useFilterStore } from '~/stores/filter'
-import {
- CLEAR_FILTERS,
- FETCH_MEDIA,
- TOGGLE_FILTER,
-} from '~/constants/action-types'
-import { MEDIA, SEARCH } from '~/constants/store-modules'
+import { useSearchStore } from '~/stores/search'
+import { areQueriesEqual } from '~/utils/search-query-transform'
import VFilterChecklist from '~/components/VFilters/VFilterChecklist.vue'
@@ -62,15 +60,14 @@ export default {
VFilterChecklist,
},
setup() {
- const filterStore = useFilterStore()
- const { i18n, store } = useContext()
- const router = useRouter()
+ const searchStore = useSearchStore()
- const isAnyFilterApplied = computed(() => filterStore.isAnyFilterApplied)
+ const { app, i18n } = useContext()
+ const route = useRoute()
+ const router = useRouter()
- const filters = computed(() => {
- return store.getters[`${SEARCH}/searchFilters`]
- })
+ const isAnyFilterApplied = computed(() => searchStore.isAnyFilterApplied)
+ const filters = computed(() => searchStore.searchFilters)
const filterTypes = computed(() => Object.keys(filters.value))
const filterTypeTitle = (filterType) => {
if (filterType === 'searchBy') {
@@ -79,30 +76,34 @@ export default {
return i18n.t(`filters.${kebab(filterType)}.title`)
}
- const updateSearch = async () => {
- await router.push({ query: store.getters['search/searchQueryParams'] })
- await store.dispatch(`${MEDIA}/${FETCH_MEDIA}`, {
- ...store.getters['search/searchQueryParams'],
- })
- }
-
- const onUpdateFilter = async ({ code, filterType }) => {
- await store.dispatch(`${SEARCH}/${TOGGLE_FILTER}`, { code, filterType })
- await updateSearch()
- }
- const clearFilters = async () => {
- await store.dispatch(`${SEARCH}/${CLEAR_FILTERS}`)
-
- await updateSearch()
- }
+ /**
+ * This watcher fires even when the queries are equal. We update the path only
+ * when the queries change.
+ */
+ watch(
+ () => searchStore.searchQueryParams,
+ /**
+ * @param {import('../../store/types').ApiQueryParams} newQuery
+ * @param {import('../../store/types').ApiQueryParams} oldQuery
+ */
+ (newQuery, oldQuery) => {
+ if (!areQueriesEqual(newQuery, oldQuery)) {
+ const newPath = app.localePath({
+ path: route.value.path,
+ query: searchStore.searchQueryParams,
+ })
+ router.push(newPath)
+ }
+ }
+ )
return {
isAnyFilterApplied,
filters,
filterTypes,
filterTypeTitle,
- clearFilters,
- onUpdateFilter,
+ clearFilters: searchStore.clearFilters,
+ toggleFilter: searchStore.toggleFilter,
}
},
}
diff --git a/src/components/VFourOhFour.vue b/src/components/VFourOhFour.vue
index 34be920d4..355a97ecd 100644
--- a/src/components/VFourOhFour.vue
+++ b/src/components/VFourOhFour.vue
@@ -55,8 +55,10 @@ import {
useRouter,
} from '@nuxtjs/composition-api'
-import { MEDIA, SEARCH } from '~/constants/store-modules'
-import { FETCH_MEDIA, UPDATE_QUERY } from '~/constants/action-types'
+import { MEDIA } from '~/constants/store-modules'
+import { FETCH_MEDIA } from '~/constants/action-types'
+
+import { useSearchStore } from '~/stores/search'
import VSearchBar from '~/components/VHeader/VSearchBar/VSearchBar.vue'
import VLink from '~/components/VLink.vue'
@@ -76,6 +78,7 @@ const VFourOhFour = defineComponent({
},
props: ['error'],
setup() {
+ const searchStore = useSearchStore()
const { app, store } = useContext()
const router = useRouter()
@@ -87,9 +90,7 @@ const VFourOhFour = defineComponent({
const handleSearch = async () => {
if (searchTerm.value === '') return
- await store.dispatch(`${SEARCH}/${UPDATE_QUERY}`, {
- q: searchTerm.value,
- })
+ searchStore.setSearchTerm(searchTerm.value)
await store.dispatch(`${MEDIA}/${FETCH_MEDIA}`, {
query: { q: searchTerm.value },
})
diff --git a/src/components/VHeader/VFilterButton.vue b/src/components/VHeader/VFilterButton.vue
index 452aefd06..266ad9d69 100644
--- a/src/components/VHeader/VFilterButton.vue
+++ b/src/components/VHeader/VFilterButton.vue
@@ -26,7 +26,7 @@ import {
useContext,
} from '@nuxtjs/composition-api'
-import { useFilterStore } from '~/stores/filter'
+import { useSearchStore } from '~/stores/search'
import VButton from '~/components/VButton.vue'
import VIcon from '~/components/VIcon/VIcon.vue'
@@ -47,11 +47,11 @@ const VFilterButton = defineComponent({
},
setup(props, { emit }) {
const { i18n } = useContext()
- const filterStore = useFilterStore()
+ const searchStore = useSearchStore()
const { pressed } = toRefs(props)
const isMinScreenMd = inject('isMinScreenMd', false)
const isHeaderScrolled = inject('isHeaderScrolled', false)
- const filterCount = computed(() => filterStore.appliedFilterCount)
+ const filterCount = computed(() => searchStore.appliedFilterCount)
const filtersAreApplied = computed(() => filterCount.value > 0)
/**
diff --git a/src/components/VHeader/VHeader.vue b/src/components/VHeader/VHeader.vue
index 2dd64e666..e54ce06cc 100644
--- a/src/components/VHeader/VHeader.vue
+++ b/src/components/VHeader/VHeader.vue
@@ -61,20 +61,16 @@ import {
watch,
} from '@nuxtjs/composition-api'
-import { MEDIA, SEARCH } from '~/constants/store-modules'
-import {
- CLEAR_MEDIA,
- FETCH_MEDIA,
- UPDATE_QUERY,
-} from '~/constants/action-types'
-import { supportedMediaTypes } from '~/constants/media'
+import { MEDIA } from '~/constants/store-modules'
+import { CLEAR_MEDIA, FETCH_MEDIA } from '~/constants/action-types'
+import { ALL_MEDIA, supportedMediaTypes } from '~/constants/media'
import { isMinScreen } from '~/composables/use-media-query'
import { useMatchSearchRoutes } from '~/composables/use-match-routes'
import { useFilterSidebarVisibility } from '~/composables/use-filter-sidebar-visibility'
import { useI18nResultsCount } from '~/composables/use-i18n-utilities'
+import { useSearchStore } from '~/stores/search'
import VLogoButton from '~/components/VHeader/VLogoButton.vue'
-
import VHeaderFilter from '~/components/VHeader/VHeaderFilter.vue'
import VSearchBar from '~/components/VHeader/VSearchBar/VSearchBar.vue'
import VHeaderMenu from '~/components/VHeader/VHeaderMenu.vue'
@@ -95,6 +91,7 @@ const VHeader = defineComponent({
VSearchBar,
},
setup() {
+ const searchStore = useSearchStore()
const { app, i18n, store } = useContext()
const router = useRouter()
@@ -149,60 +146,67 @@ const VHeader = defineComponent({
* Shows the loading state or result count.
*/
const searchStatus = computed(() => {
- if (!isSearchRoute.value || store.state.search.query.q === '') return ''
+ if (!isSearchRoute.value || searchStore.searchTerm === '') return ''
if (isFetching.value) return i18n.t('header.loading')
return getI18nCount(resultsCount.value)
})
- const localSearchTerm = ref(store.state.search.query.q)
+ const localSearchTerm = ref(searchStore.searchTerm)
+ let searchTermChanged = computed(() => {
+ return searchStore.searchTerm !== localSearchTerm.value
+ })
+ /**
+ * Search term has a getter and setter to be used as a v-model.
+ * To prevent sending unnecessary requests, we also keep track of whether
+ * the search term was changed.
+ * @type {import('@nuxtjs/composition-api').WritableComputedRef<string>}
+ */
const searchTerm = computed({
get: () => localSearchTerm.value,
- set: async (value) => {
+ set: (value) => {
localSearchTerm.value = value
},
})
- watch(
- () => store.state.search.query.q,
- (newSearchTerm) => {
- if (newSearchTerm !== localSearchTerm.value) {
- localSearchTerm.value = newSearchTerm
- }
- }
- )
-
+ /**
+ * Called when the 'search' button in the header is clicked.
+ * There are several scenarios:
+ * - search term hasn't changed:
+ * - on a search route, do nothing.
+ * - on other routes: set searchType to 'All content', reset the media,
+ * change the path to `/search/` (All content) and fetch media.
+ * - search term changed:
+ * - on a search route: Update the store searchTerm value, update query `q` param, reset media,
+ * fetch new media.
+ * - on other routes: Update the store searchTerm value, set searchType to 'All content', reset media,
+ * update query `q` param, fetch new media.
+ */
const handleSearch = async () => {
- /**
- * If search term hasn't changed, don't do anything on a search route,
- * and change path to search path (all content types) from other pages.
- * If is search route and search term hasn't changed: return
- * If is not search route and search term hasn't changed: set the search type to all, set path.
- * If is search route and search term changed: set the query, set path
- * If is not search route, and search term changed: set search type to all, set query, set path
- */
- const searchTermChanged =
- localSearchTerm.value !== store.state.search.query.q
- if (isSearchRoute.value && !searchTermChanged) return
- const searchType = store.state.search.searchType
- if (searchTermChanged) {
+ const searchStore = useSearchStore()
+ const searchType = isSearchRoute.value
+ ? searchStore.searchType
+ : ALL_MEDIA
+ if (
+ isSearchRoute.value &&
+ (!searchTermChanged.value || searchTerm.value === '')
+ )
+ return
+ if (searchTermChanged.value) {
await Promise.all(
supportedMediaTypes.map((mediaType) =>
store.dispatch(`${MEDIA}/${CLEAR_MEDIA}`, { mediaType })
)
)
- await store.dispatch(`${SEARCH}/${UPDATE_QUERY}`, {
- q: localSearchTerm.value,
- searchType,
- })
+ searchStore.setSearchTerm(searchTerm.value)
+ searchStore.setSearchType(searchType)
}
const newPath = app.localePath({
path: `/search/${searchType === 'all' ? '' : searchType}`,
- query: store.getters['search/searchQueryParams'],
+ query: searchStore.searchQueryParams,
})
router.push(newPath)
-
await store.dispatch(`${MEDIA}/${FETCH_MEDIA}`, {
- ...store.getters['search/searchQueryParams'],
+ ...searchStore.searchQueryParams,
})
}
diff --git a/src/components/VHeader/VHeaderMenu.vue b/src/components/VHeader/VHeaderMenu.vue
index e6235f2e2..2fa2f327e 100644
--- a/src/components/VHeader/VHeaderMenu.vue
+++ b/src/components/VHeader/VHeaderMenu.vue
@@ -14,6 +14,8 @@ import { ALL_MEDIA, supportedMediaTypes } from '~/constants/media'
import { FETCH_MEDIA } from '~/constants/action-types'
import { MEDIA } from '~/constants/store-modules'
+import { useSearchStore } from '~/stores/search'
+
import VMobileMenuModal from '~/components/VContentSwitcher/VMobileMenuModal.vue'
import VSearchTypePopover from '~/components/VContentSwitcher/VSearchTypePopover.vue'
import VDesktopPageMenu from '~/components/VHeader/VPageMenu/VDesktopPageMenu.vue'
@@ -40,6 +42,7 @@ export default {
const menuModalRef = ref(null)
const content = useSearchType()
const { app } = useContext()
+ const searchStore = useSearchStore()
const store = useStore()
const router = useRouter()
@@ -49,11 +52,11 @@ export default {
})
const selectSearchType = async (type) => {
menuModalRef.value?.closeMenu()
- await content.setActiveType(type)
+ content.setActiveType(type)
const newPath = app.localePath({
path: `/search/${type === ALL_MEDIA ? '' : type}`,
- query: store.getters['search/searchQueryParams'],
+ query: searchStore.searchQueryParams,
})
router.push(newPath)
@@ -68,7 +71,7 @@ export default {
if (shouldFetchMedia) {
await store.dispatch(`${MEDIA}/${FETCH_MEDIA}`, {
- ...store.getters['search/searchQueryParams'],
+ ...searchStore.searchQueryParams,
})
}
}
diff --git a/src/components/VSearchGrid.vue b/src/components/VSearchGrid.vue
index 30bc51c0d..172335f0e 100644
--- a/src/components/VSearchGrid.vue
+++ b/src/components/VSearchGrid.vue
@@ -1,7 +1,9 @@
<template>
- <section v-if="resultsCount">
+ <section
+ v-if="fetchState.isFetching || (!fetchState.isFetching && resultsCount)"
+ >
<header
- v-if="query.q && isSupported"
+ v-if="query.q && supported"
class="mt-4"
:class="isAllView ? 'mb-10' : 'mb-8'"
>
@@ -20,7 +22,7 @@
:type="metaSearchFormType"
:has-no-results="hasNoResults"
:query="query"
- :is-supported="isSupported"
+ :is-supported="supported"
/>
</section>
<VErrorSection v-else-if="!fetchState.isFetching" class="w-full py-10">
@@ -34,7 +36,7 @@
<script>
import { computed } from '@nuxtjs/composition-api'
-import { ALL_MEDIA, IMAGE, supportedSearchTypes } from '~/constants/media'
+import { ALL_MEDIA, IMAGE } from '~/constants/media'
import { NO_RESULT } from '~/constants/errors'
import VMetaSearchForm from '~/components/VMetaSearch/VMetaSearchForm.vue'
@@ -83,9 +85,6 @@ export default {
? props.query.q !== '' && props.resultsCount === 0
: false
})
- const isSupported = computed(() => {
- return supportedSearchTypes.includes(props.searchType)
- })
const metaSearchFormType = computed(() => {
return props.searchType === ALL_MEDIA ? IMAGE : props.searchType
})
@@ -95,7 +94,6 @@ export default {
return {
hasNoResults,
- isSupported,
metaSearchFormType,
isAllView,
NO_RESULT,
diff --git a/src/composables/use-search-type.js b/src/composables/use-search-type.js
index 0c760df80..323689227 100644
--- a/src/composables/use-search-type.js
+++ b/src/composables/use-search-type.js
@@ -1,8 +1,8 @@
-import { computed, ref, useContext } from '@nuxtjs/composition-api'
+import { computed, ref } from '@nuxtjs/composition-api'
import { supportedSearchTypes } from '~/constants/media'
-import { SEARCH } from '~/constants/store-modules'
-import { UPDATE_QUERY } from '~/constants/action-types'
+
+import { useSearchStore } from '~/stores/search'
import allIcon from '~/assets/icons/all-content.svg'
import audioIcon from '~/assets/icons/audio-content.svg'
@@ -16,15 +16,11 @@ const icons = {
const searchTypes = [...supportedSearchTypes]
export default function useSearchType() {
- const { store } = useContext()
-
- const activeType = computed(() => store.state.search.searchType)
+ const activeType = computed(() => useSearchStore().searchType)
const previousSearchType = ref(activeType.value)
- const setActiveType = async (searchType) => {
+ const setActiveType = (searchType) => {
if (previousSearchType.value === searchType) return
- await store.dispatch(`${SEARCH}/${UPDATE_QUERY}`, {
- searchType,
- })
+ useSearchStore().setSearchType(searchType)
previousSearchType.value = searchType
}
return {
diff --git a/src/constants/action-types.js b/src/constants/action-types.js
index 0b3ed31b1..d68f0ed07 100644
--- a/src/constants/action-types.js
+++ b/src/constants/action-types.js
@@ -4,10 +4,5 @@ export const FETCH_MEDIA_ITEM = 'FETCH_MEDIA_ITEM'
export const FETCH_MEDIA = 'FETCH_MEDIA'
export const FETCH_SINGLE_MEDIA_TYPE = 'FETCH_SINGLE_MEDIA_TYPE'
export const HANDLE_MEDIA_ERROR = 'HANDLE_MEDIA_ERROR'
-export const TOGGLE_FILTER = 'TOGGLE_FILTER'
export const HANDLE_NO_MEDIA = 'HANDLE_NO_MEDIA'
-export const UPDATE_QUERY = 'UPDATE_QUERY'
-export const UPDATE_QUERY_FROM_FILTERS = 'UPDATE_QUERY_FROM_FILTERS'
-export const SET_SEARCH_STATE_FROM_URL = 'SET_SEARCH_STATE_FROM_URL'
export const CLEAR_MEDIA = 'CLEAR_MEDIA'
-export const CLEAR_FILTERS = 'CLEAR_FILTERS'
diff --git a/src/constants/filters.ts b/src/constants/filters.ts
index 33914337c..09703567b 100644
--- a/src/constants/filters.ts
+++ b/src/constants/filters.ts
@@ -88,7 +88,7 @@ const filterCodesPerCategory = deepFreeze<Record<FilterCategory, string[]>>({
* }
*```
*/
-const initFilters = () =>
+export const initFilters = () =>
Object.entries(filterCodesPerCategory).reduce(
(acc, [filterType, filters]) => ({
...acc,
diff --git a/src/constants/mutation-types.js b/src/constants/mutation-types.js
index 139f0fba3..d04a3eb7e 100644
--- a/src/constants/mutation-types.js
+++ b/src/constants/mutation-types.js
@@ -8,7 +8,5 @@ export const FETCH_START_MEDIA = 'FETCH_START_MEDIA'
export const SET_MEDIA_ITEM = 'SET_MEDIA_ITEM'
export const SET_MEDIA_PROVIDERS = 'SET_MEDIA_PROVIDERS'
export const SET_MEDIA = 'SET_MEDIA'
-export const SET_SEARCH_TYPE = 'SET_SEARCH_TYPE'
export const RESET_MEDIA = 'RESET_MEDIA'
-export const SET_QUERY = 'SET_QUERY'
export const RESET_FETCH_STATE = 'RESET_FETCH_STATE'
diff --git a/src/constants/store-modules.js b/src/constants/store-modules.js
index 1386e2cc0..b50fccec5 100644
--- a/src/constants/store-modules.js
+++ b/src/constants/store-modules.js
@@ -1,4 +1,2 @@
-export const RELATED = 'related'
export const PROVIDER = 'provider'
-export const SEARCH = 'search'
export const MEDIA = 'media'
diff --git a/src/locales/po-files/openverse.pot b/src/locales/po-files/openverse.pot
index ce0368e21..0eab71969 100644
--- a/src/locales/po-files/openverse.pot
+++ b/src/locales/po-files/openverse.pot
@@ -4,7 +4,7 @@ msgid ""
msgstr ""
"Project-Id-Version: Openverse \n"
"Report-Msgid-Bugs-To: https://github.com/wordpress/openverse/issues \n"
-"POT-Creation-Date: 2022-03-21T12:21:26+00:00\n"
+"POT-Creation-Date: 2022-03-22T03:16:50+00:00\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
@@ -68,12 +68,12 @@ msgid "Whoops, it looks like that request took too long to complete. Please try
msgstr ""
#. Do not translate words between ### ###.
-#: src/components/VErrorSection/VNoResults.vue:3
+#: src/components/VErrorSection/VNoResults.vue:4
msgctxt "no-results.heading"
msgid "We couldn't find anything for \"###query###\"."
msgstr ""
-#: src/components/VErrorSection/VNoResults.vue:5
+#: src/components/VErrorSection/VNoResults.vue:7
msgctxt "no-results.alternatives"
msgid "Try a different query or use one of the additional sources to expand your search."
msgstr ""
@@ -817,7 +817,7 @@ msgctxt "browse-page.search-rating.feedback-thanks"
msgid "Thank you for the feedback!"
msgstr ""
-#: src/components/VFilters/VSearchGridFilter.vue:11
+#: src/components/VFilters/VSearchGridFilter.vue:8
msgctxt "filter-list.filter-by"
msgid "Filter by"
msgstr ""
@@ -826,12 +826,12 @@ msgctxt "filter-list.hide"
msgid "Hide filters"
msgstr ""
-#: src/components/VFilters/VSearchGridFilter.vue:20
+#: src/components/VFilters/VSearchGridFilter.vue:17
msgctxt "filter-list.clear"
msgid "Clear filters"
msgstr ""
-#: src/components/VFilters/VSearchGridFilter.vue:39
+#: src/components/VFilters/VSearchGridFilter.vue:36
msgctxt "filter-list.show"
msgid "Show results"
msgstr ""
@@ -1801,7 +1801,7 @@ msgctxt "header.api-nav-item"
msgid "API"
msgstr ""
-#: src/components/VHeader/VHeader.vue:153
+#: src/components/VHeader/VHeader.vue:150
msgctxt "header.loading"
msgid "Loading..."
msgstr ""
diff --git a/src/pages/index.vue b/src/pages/index.vue
index 0b88e80dd..71f1b2a60 100644
--- a/src/pages/index.vue
+++ b/src/pages/index.vue
@@ -134,11 +134,13 @@
<script>
import { ref, useContext, useRouter, useStore } from '@nuxtjs/composition-api'
-import { FETCH_MEDIA, UPDATE_QUERY } from '~/constants/action-types'
-import { MEDIA, SEARCH } from '~/constants/store-modules'
+import { FETCH_MEDIA } from '~/constants/action-types'
+import { MEDIA } from '~/constants/store-modules'
import { ALL_MEDIA, supportedSearchTypes } from '~/constants/media'
import { isMinScreen } from '~/composables/use-media-query'
+import { useSearchStore } from '~/stores/search'
+
import VLink from '~/components/VLink.vue'
import VLogoButton from '~/components/VHeader/VLogoButton.vue'
import VSearchBar from '~/components/VHeader/VSearchBar/VSearchBar.vue'
@@ -173,6 +175,7 @@ const HomePage = {
setup() {
const { app } = useContext()
const router = useRouter()
+ const searchStore = useSearchStore()
const store = useStore()
const featuredSearches = imageInfo.sets.map((setItem) => ({
@@ -197,32 +200,27 @@ const HomePage = {
const contentSwitcher = ref(null)
const searchType = ref(ALL_MEDIA)
- const setSearchType = async (type) => {
+ const setSearchType = (type) => {
searchType.value = type
contentSwitcher.value?.closeMenu()
- await store.dispatch(`${SEARCH}/${UPDATE_QUERY}`, {
- searchType: type,
- })
+ useSearchStore().setSearchType(type)
}
const searchTerm = ref('')
const handleSearch = async () => {
if (!searchTerm.value) return
- await store.dispatch(`${SEARCH}/${UPDATE_QUERY}`, {
- q: searchTerm.value,
- searchType: searchType.value,
- })
+ searchStore.setSearchTerm(searchTerm.value)
+ searchStore.setSearchType(searchType.value)
+ const query = searchStore.searchQueryParams
const newPath = app.localePath({
path: `/search/${
searchType.value === ALL_MEDIA ? '' : searchType.value
}`,
- query: store.getters['search/searchQueryParams'],
+ query,
})
router.push(newPath)
- await store.dispatch(`${MEDIA}/${FETCH_MEDIA}`, {
- ...store.getters['search/searchQueryParams'],
- })
+ await store.dispatch(`${MEDIA}/${FETCH_MEDIA}`, { ...query })
}
return {
diff --git a/src/pages/search.vue b/src/pages/search.vue
index 3e26a44ee..335115b02 100644
--- a/src/pages/search.vue
+++ b/src/pages/search.vue
@@ -27,20 +27,18 @@
</template>
<script>
-import { mapActions, mapGetters, mapState } from 'vuex'
+import { mapActions, mapGetters } from 'vuex'
import { isShallowEqualObjects } from '@wordpress/is-shallow-equal'
-import { inject } from '@nuxtjs/composition-api'
+import { computed, inject } from '@nuxtjs/composition-api'
-import {
- FETCH_MEDIA,
- UPDATE_QUERY,
- SET_SEARCH_STATE_FROM_URL,
-} from '~/constants/action-types'
+import { FETCH_MEDIA } from '~/constants/action-types'
import { supportedSearchTypes } from '~/constants/media'
-import { MEDIA, SEARCH } from '~/constants/store-modules'
+import { MEDIA } from '~/constants/store-modules'
import { isMinScreen } from '~/composables/use-media-query'
import { useFilterSidebarVisibility } from '~/composables/use-filter-sidebar-visibility'
+import { useSearchStore } from '~/stores/search'
+
import VSearchGrid from '~/components/VSearchGrid.vue'
import VSkipToContentContainer from '~/components/VSkipToContentContainer.vue'
import VScrollButton from '~/components/VScrollButton.vue'
@@ -56,30 +54,42 @@ const BrowsePage = {
const isMinScreenMd = isMinScreen('md')
const { isVisible } = useFilterSidebarVisibility()
const showScrollButton = inject('showScrollButton')
+ const searchStore = useSearchStore()
+
+ const searchTerm = computed(() => searchStore.searchTerm)
+ const searchType = computed(() => searchStore.searchType)
+ const query = computed(() => searchStore.searchQueryParams)
+ const supported = computed(() =>
+ supportedSearchTypes.includes(searchType.value)
+ )
return {
isMinScreenMd,
isVisible,
showScrollButton,
+ searchTerm,
+ searchType,
+ supported,
+ query,
+ setSearchStateFromUrl: searchStore.setSearchStateFromUrl,
}
},
scrollToTop: false,
async fetch() {
- if (this.supported && !this.resultCount && this.query.q.trim() !== '') {
+ if (this.supported && !this.resultCount && this.searchTerm.trim() !== '') {
await this.fetchMedia({})
}
},
- async asyncData({ route, store }) {
+ asyncData({ route, $pinia }) {
if (process.server) {
- await store.dispatch(`${SEARCH}/${SET_SEARCH_STATE_FROM_URL}`, {
+ const searchStore = useSearchStore($pinia)
+ searchStore.setSearchStateFromUrl({
path: route.path,
- query: route.query,
+ urlQuery: route.query,
})
}
},
computed: {
- ...mapState(SEARCH, ['query', 'searchType']),
- ...mapGetters(SEARCH, ['searchQueryParams']),
...mapGetters(MEDIA, ['resultCount', 'fetchState', 'resultItems']),
/**
* Number of search results. Returns 0 for unsupported types.
@@ -88,19 +98,9 @@ const BrowsePage = {
resultsCount() {
return this.supported ? this.resultCount : 0 ?? 0
},
- supported() {
- return supportedSearchTypes.includes(this.searchType)
- },
},
methods: {
...mapActions(MEDIA, { fetchMedia: FETCH_MEDIA }),
- ...mapActions(SEARCH, {
- setSearchStateFromUrl: SET_SEARCH_STATE_FROM_URL,
- updateQuery: UPDATE_QUERY,
- }),
- onSearchFormSubmit({ q }) {
- this.updateQuery({ q })
- },
},
watch: {
/**
@@ -113,7 +113,8 @@ const BrowsePage = {
newRoute.path !== oldRoute.path ||
!isShallowEqualObjects(newRoute.query, oldRoute.query)
) {
- await this.setSearchStateFromUrl(newRoute)
+ const { query, path } = newRoute
+ await this.setSearchStateFromUrl({ urlQuery: query, path })
this.fetchMedia(this.searchQueryParams)
}
},
diff --git a/src/store/media.js b/src/store/media.js
index 3a9db2a7b..776e76ba5 100644
--- a/src/store/media.js
+++ b/src/store/media.js
@@ -22,6 +22,8 @@ import MediaService from '~/data/media-service'
import { hash, rand as prng } from '~/utils/prng'
+import { useSearchStore } from '~/stores/search'
+
/**
* @return {import('./types').MediaState}
*/
@@ -108,14 +110,11 @@ export const createActions = (services = mediaServices) => ({
* @param {boolean} [payload.shouldPersistMedia] - whether the existing media should be added to or replaced.
* @return {Promise<void>}
*/
- async [FETCH_SINGLE_MEDIA_TYPE](
- { commit, dispatch, rootGetters, state },
- payload
- ) {
+ async [FETCH_SINGLE_MEDIA_TYPE]({ commit, dispatch, state }, payload) {
const { mediaType, shouldPersistMedia = false, ...params } = payload
const queryParams = prepareSearchQueryParams({
- ...rootGetters['search/searchQueryParams'],
+ ...useSearchStore().searchQueryParams,
...params,
})
@@ -288,6 +287,9 @@ export const getters = {
)
}
},
+ searchType() {
+ return useSearchStore().searchType
+ },
allMedia(state, getters) {
const media = getters.resultItems
@@ -327,9 +329,6 @@ export const getters = {
return newResults
},
- searchType(state, getters, rootState) {
- return rootState.search.searchType
- },
}
export const mutations = {
diff --git a/src/store/provider.js b/src/store/provider.js
index 9e172a0ec..77f08534d 100644
--- a/src/store/provider.js
+++ b/src/store/provider.js
@@ -1,9 +1,7 @@
import { capital } from 'case'
-import { useFilterStore } from '~/stores/filter'
-
import MediaProviderService from '~/data/media-provider-service'
-import { AUDIO, IMAGE } from '~/constants/media'
+import { ALL_MEDIA, AUDIO, IMAGE } from '~/constants/media'
import {
FETCH_MEDIA_TYPE_PROVIDERS,
FETCH_MEDIA_PROVIDERS,
@@ -16,6 +14,8 @@ import {
} from '~/constants/mutation-types'
import { warn } from '~/utils/console'
+import { useSearchStore } from '~/stores/search'
+
const AudioProviderService = MediaProviderService(AUDIO)
const ImageProviderService = MediaProviderService(IMAGE)
@@ -37,8 +37,10 @@ export const state = () => ({
})
export const getters = {
- getProviderName: (state, getters, rootState) => (providerCode) => {
- const mediaType = rootState.search.mediaType
+ getProviderName: (state) => (providerCode) => {
+ const searchStore = useSearchStore()
+ const mediaType =
+ searchStore.searchType === ALL_MEDIA ? IMAGE : searchStore.searchType
const providersList = state[`${mediaType}Providers`]
if (!providersList) {
return capital(providerCode) || ''
@@ -61,19 +63,20 @@ export const createActions = (services) => ({
},
[FETCH_MEDIA_TYPE_PROVIDERS]({ commit }, params) {
const { mediaType } = params
- const filterStore = useFilterStore()
+ const searchStore = useSearchStore()
commit(SET_PROVIDER_FETCH_ERROR, { mediaType, error: false })
commit(FETCH_MEDIA_PROVIDERS_START, { mediaType })
const providerService = services[mediaType]
let sortedProviders
return providerService
.getProviderStats()
- .then(({ data }) => {
+ .then((res) => {
+ const { data } = res
sortedProviders = sortProviders(data)
})
.catch((error) => {
warn(
- `Error getting ${mediaType} providers: ${error}. Will use saved provider data instead.`
+ `Error getting ${mediaType} providers: ${error} Will use saved provider data instead.`
)
commit(SET_PROVIDER_FETCH_ERROR, { mediaType, error: true })
})
@@ -83,7 +86,7 @@ export const createActions = (services) => ({
mediaType,
providers: sortedProviders,
})
- filterStore.initProviderFilters({
+ searchStore.initProviderFilters({
mediaType,
providers: sortedProviders,
})
diff --git a/src/store/search.js b/src/store/search.js
deleted file mode 100644
index 4aceff062..000000000
--- a/src/store/search.js
+++ /dev/null
@@ -1,188 +0,0 @@
-import {
- filtersToQueryData,
- queryStringToSearchType,
-} from '~/utils/search-query-transform'
-import { ALL_MEDIA } from '~/constants/media'
-import {
- UPDATE_QUERY,
- SET_SEARCH_STATE_FROM_URL,
- TOGGLE_FILTER,
- UPDATE_QUERY_FROM_FILTERS,
- CLEAR_FILTERS,
-} from '~/constants/action-types'
-import { SET_QUERY, SET_SEARCH_TYPE } from '~/constants/mutation-types'
-
-import { useFilterStore } from '~/stores/filter'
-
-/**
- * `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 = () => ({
- searchType: ALL_MEDIA,
- query: {
- q: '',
- license_type: '',
- license: '',
- categories: '',
- extension: '',
- duration: '',
- aspect_ratio: '',
- size: '',
- source: '',
- searchBy: '',
- mature: '',
- },
-})
-
-export const getters = {
- /**
- * Returns the search query parameters for API request:
- * drops 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.trim() }
- // Handle mature filter separately
- const filterKeys = Object.keys(state.query).filter(
- (key) => !['q', 'mature'].includes(key)
- )
- filterKeys.forEach((key) => {
- if (state.query[key].length) {
- params[key] = state.query[key]
- }
- })
- if (state.query.mature === true) {
- params.mature = true
- }
- return params
- },
- searchFilters: (state) => {
- return useFilterStore().getMediaTypeFilters({ mediaType: state.searchType })
- },
-}
-
-const actions = {
- /**
- * Called when `q` search term or `searchType` are changed.
- * @param {import('vuex').ActionContext} context
- * @param {import('vuex').ActionPayload} params
- * @param {string} [params.q]
- * @param {import('./types').SupportedSearchType} [params.searchType]
- * @return {Promise<void>}
- */
- async [UPDATE_QUERY]({ commit, dispatch, state }, params = {}) {
- const { q, searchType } = params
- /** @type {{ q: string? }} */
- const queryParams = {}
- if (q) {
- queryParams.q = q.trim()
- }
- if (searchType && searchType !== state.searchType) {
- commit(SET_SEARCH_TYPE, { searchType })
- useFilterStore().clearOtherMediaTypeFilters({ searchType })
- }
- await dispatch(UPDATE_QUERY_FROM_FILTERS, queryParams)
- },
- /**
- * Toggles a filter's checked parameter
- * @param {import('vuex').ActionContext} context
- * @param params
- */
- async [TOGGLE_FILTER]({ dispatch }, params) {
- useFilterStore().toggleFilter(params)
- await dispatch(UPDATE_QUERY_FROM_FILTERS)
- },
-
- /**
- * 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]({ dispatch }) {
- useFilterStore().clearFilters()
- await dispatch(UPDATE_QUERY_FROM_FILTERS, { q: '' })
- },
-
- /**
- * 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 }, { path, query }) {
- const searchType = queryStringToSearchType(path)
- const queryParams = {}
- if (query.q) {
- queryParams.q = query.q
- }
-
- commit(SET_SEARCH_TYPE, { searchType })
- useFilterStore().updateFiltersFromUrl(query, searchType)
-
- await dispatch(UPDATE_QUERY_FROM_FILTERS, queryParams)
- },
- /**
- * 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(
- useFilterStore().filters,
- params.mediaType || state.searchType,
- true
- )
-
- // If the filter was unchecked, its value in `queryFromFilters` would be falsy, ''.
- // So we check if the key exists, not if the value is not falsy.
- const changedKeys = Object.keys(queryFromFilters)
- const updatedQuery = /** @type {import('../store/types').Query} */ (
- Object.keys(state.query).reduce((obj, key) => {
- if (key === 'q') {
- obj[key] = params?.q || state.query.q
- } else {
- obj[key] = changedKeys.includes(key) ? queryFromFilters[key] : ''
- }
- return obj
- }, {})
- )
- commit(SET_QUERY, { query: updatedQuery })
- },
-}
-
-const mutations = {
- /**
- * Sets the content type to search.
- * @param {import('./types').SearchState} state
- * @param {import('../constants/media').SearchType} searchType
- */
- [SET_SEARCH_TYPE](state, { searchType }) {
- state.searchType = searchType
- useFilterStore().setSearchType(searchType)
- },
- /**
- * Replaces the query object that is used for API calls.
- * @param {import('./types').SearchState} state
- * @param {Object} query
- */
- [SET_QUERY](state, { query }) {
- state.query = query
- },
-}
-
-export default {
- state,
- getters,
- actions,
- mutations,
-}
diff --git a/src/store/types.ts b/src/store/types.ts
index 742eb2b79..beab30130 100644
--- a/src/store/types.ts
+++ b/src/store/types.ts
@@ -33,7 +33,7 @@ export interface MediaResult<
: never
}
-export type Query = {
+export interface Query {
q: string
license_type: string
license: string
@@ -46,8 +46,9 @@ export type Query = {
duration: string
mature: string
}
+export type QueryKey = keyof Query
-export type ApiQueryParams = {
+export interface ApiQueryParams {
q: string
license?: string
license_type?: string
@@ -60,6 +61,8 @@ export type ApiQueryParams = {
duration?: string
mature?: string
}
+export type ApiQueryFilters = Omit<ApiQueryParams, 'q'>
+export type ApiQueryKeys = keyof ApiQueryFilters
export interface Tag {
name: string
diff --git a/src/stores/filter.js b/src/stores/filter.js
deleted file mode 100644
index 81dcd7d70..000000000
--- a/src/stores/filter.js
+++ /dev/null
@@ -1,280 +0,0 @@
-import { defineStore } from 'pinia'
-import { computed, reactive, readonly, ref } from '@nuxtjs/composition-api'
-import clonedeep from 'lodash.clonedeep'
-
-import {
- ALL_MEDIA,
- AUDIO,
- IMAGE,
- supportedSearchTypes,
-} from '~/constants/media'
-import { queryToFilterData } from '~/utils/search-query-transform'
-import {
- filterData,
- mediaFilterKeys,
- mediaUniqueFilterKeys,
-} from '~/constants/filters'
-import { warn } from '~/utils/console'
-
-export const useFilterStore = defineStore('filter', () => {
- /** @type {{ filters: import('../store/types').Filters}} */
- const filters = reactive(clonedeep(filterData))
- const searchType = /** @type {import('../constants/media').SearchType} */ (
- ref(ALL_MEDIA)
- )
-
- /**
- * @param {import('../constants/media').SearchType} type
- */
- const setSearchType = (type) => (searchType.value = type)
- /**
- *
- * @param {{ mediaType: import('../constants/media').SearchType, includeMature?: boolean }} params
- * @returns {Partial<import('~/constants/media').Filters>}
- */
- function getMediaTypeFilters({ mediaType, includeMature = false }) {
- let filterKeys = mediaFilterKeys[mediaType]
- if (!includeMature) {
- filterKeys = filterKeys.filter((filterKey) => filterKey !== 'mature')
- }
- const mediaTypeFilters = {}
- filterKeys.forEach((filterKey) => {
- mediaTypeFilters[filterKey] = filters[filterKey]
- })
- return mediaTypeFilters
- }
- /**
- * Initial filters do not include the provider filters. We create the provider filters object
- * when we fetch the provider data on the Nuxt server initialization.
- * We call this function to reset the filters to the initial base filters AND the provider filters.
- * @returns {import('../store/types').Filters}
- */
- const getBaseFiltersWithProviders = () => {
- /**
- * @param {import('../store/types').SupportedMediaType} mediaType
- * @returns {import('../store/types').FilterItem[]}
- */
- const resetProviders = (mediaType) => {
- return filters[`${mediaType}Providers`].map((provider) => ({
- ...provider,
- checked: false,
- }))
- }
- return {
- ...clonedeep(filterData),
- audioProviders: resetProviders(AUDIO),
- imageProviders: resetProviders(IMAGE),
- }
- }
-
- /**
- * Returns the number of checked filters, excluding the `mature` filter.
- *
- * @type {import('@nuxtjs/composition-api').ComputedRef<number>}
- */
- const appliedFilterCount = computed(() => {
- const filterKeys = mediaFilterKeys[searchType.value].filter(
- (f) => f !== 'mature'
- )
- return filterKeys.reduce((count, filterType) => {
- return count + filters[filterType].filter((f) => f.checked).length
- }, 0)
- })
-
- /**
- * True if any filter for selected search type except `mature` is checked.
- *
- * @type {import('@nuxtjs/composition-api').ComputedRef<boolean>}
- */
- const isAnyFilterApplied = computed(() => {
- const searchTypeFilters = getMediaTypeFilters({
- mediaType: searchType.value,
- })
- return Object.entries(searchTypeFilters).some(
- ([filterKey, filterItems]) =>
- filterKey !== 'mature' && filterItems.some((filter) => filter.checked)
- )
- })
-
- /**
- * After a search type is changed, unchecks all the filters that are not
- * applicable for this Media type.
- * @param {{ searchType: import('../constants/media').SearchType }} props
- */
- function clearOtherMediaTypeFilters({ searchType }) {
- const mediaTypesToClear = supportedSearchTypes.filter(
- (type) => type !== searchType
- )
- let filterKeysToClear = mediaTypesToClear.reduce((acc, type) => {
- acc = [...acc, ...mediaUniqueFilterKeys[type]]
- return acc
- }, [])
-
- Object.keys(filters).forEach((filterType) => {
- if (filterKeysToClear.includes(filterType)) {
- filters[filterType] = filters[filterType].map((f) => ({
- ...f,
- checked: false,
- }))
- }
- })
- }
-
- /**
- * Replaces filters with the newFilterData parameter, making sure that
- * audio/image provider filters are handled correctly.
- *
- * @param {object} params
- * @param {import('../store/types').Filters} params.newFilterData
- */
- function replaceFilters({ newFilterData }) {
- Object.keys(filters).forEach((filterType) => {
- if (['audioProviders', 'imageProviders'].includes(filterType)) {
- newFilterData[filterType].forEach((provider) => {
- const idx = filters[filterType].findIndex(
- (p) => p.code === provider.code
- )
- if (idx > -1) {
- filters[filterType][idx].checked = provider.checked
- }
- })
- } else {
- filters[filterType] = newFilterData[filterType]
- }
- })
- }
-
- /**
- * 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.
- * @param {{ mediaType: import('../store/types').SupportedMediaType, providers: {source_name: string, display_name: string}[]}} params
- */
- function initProviderFilters({ mediaType, providers }) {
- const providersKey = `${mediaType}Providers`
- const currentProviders = filters[providersKey]
- ? [...filters[providersKey]]
- : []
- filters[providersKey] = providers.map((provider) => {
- const existingProviderFilterIdx = currentProviders.findIndex(
- (p) => p.code === provider.source_name
- )
- const checked =
- existingProviderFilterIdx >= 0
- ? currentProviders[existingProviderFilterIdx].checked
- : false
-
- return {
- code: provider.source_name,
- name: provider.display_name,
- checked,
- }
- })
- }
- /**
- * Toggles a filter's checked parameter. Requires either codeIdx or code.
- * @param {{ filterType: string, codeIdx?: number, code?: string}} params
- */
- function toggleFilter(params) {
- if (
- typeof params.codeIdx === 'undefined' &&
- typeof params.code === 'undefined'
- ) {
- warn(
- `Cannot toggle filter of type ${params.filterType}. Use code or codeIdx parameter`
- )
- return
- }
- const { filterType } = params
- let codeIdx =
- params.codeIdx ??
- filters[filterType].findIndex((f) => f.code === params.code)
- filters[filterType][codeIdx].checked = !filters[filterType][codeIdx].checked
- }
-
- /**
- *
- * @param {Record<string, string>} searchQuery
- * @param {import('../store/types').SupportedSearchType} searchType
- */
- function updateFiltersFromUrl(searchQuery, searchType) {
- // When setting filters from URL query, 'mature' has a value of 'true',
- // but we need the 'mature' code. Creating a local shallow copy to prevent mutation.
- const query = { ...searchQuery }
- if (query.mature === 'true') {
- query.mature = 'mature'
- } else {
- delete query.mature
- }
-
- const newFilterData = queryToFilterData({
- query,
- searchType,
- defaultFilters: getBaseFiltersWithProviders(),
- })
- replaceFilters({ newFilterData })
- }
- /**
- * Resets all filters to initial values.
- * Provider filters are not in the initial filters, so they need to be
- * handled separately.
- *
- */
- function clearFilters() {
- replaceFilters({
- newFilterData: getBaseFiltersWithProviders(),
- })
- }
-
- /**
- * Selecting some filter items disables related items. For example, selecting an `nc`
- * license filter (CC BY-NC, CC BY-NC-SA, CC BY-NC-ND) disables the `Commercial` license
- * type filter. This function determines if the filter item should be disabled based on
- * the currently checked filter items.
- *
- * @param {import('../store/types').FilterItem} item
- * @param {import('../store/types').FilterCategory} filterCategory
- * @returns {boolean|undefined}
- */
- function isFilterDisabled(item, filterCategory) {
- if (!['licenseTypes', 'licenses'].includes(filterCategory)) {
- return
- }
- if (['commercial', 'modification'].includes(item.code)) {
- let targetCode = /** @type {string} */ (
- { commercial: 'nc', modification: 'nd' }[item.code]
- )
- return filters.licenses.some(
- (item) => item.code.includes(targetCode) && item.checked
- )
- } else {
- /** @type {string[]} */
- const dependentFilters = []
- if (item.code.includes('nc')) {
- dependentFilters.push('commercial')
- }
- if (item.code.includes('nd')) {
- dependentFilters.push('modification')
- }
- return filters.licenseTypes
- .filter((item) => dependentFilters.includes(item.code))
- .some((item) => item.checked)
- }
- }
-
- return {
- appliedFilterCount,
- isAnyFilterApplied,
-
- getMediaTypeFilters,
- initProviderFilters,
- isFilterDisabled,
- // These are used by the searchStore internally
- clearOtherMediaTypeFilters,
- clearFilters,
- setSearchType,
- toggleFilter,
- updateFiltersFromUrl,
- // Filters are exported for testing
- filters: readonly(filters),
- }
-})
diff --git a/src/stores/search.ts b/src/stores/search.ts
new file mode 100644
index 000000000..90f5006c5
--- /dev/null
+++ b/src/stores/search.ts
@@ -0,0 +1,342 @@
+import { defineStore } from 'pinia'
+import {
+ computed,
+ ComputedRef,
+ reactive,
+ toRefs,
+ watch,
+} from '@nuxtjs/composition-api'
+// We plan to remove this dependency, so don't need to add types for it:
+// https://github.com/WordPress/openverse-frontend/issues/1103
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-ignore
+import clonedeep from 'lodash.clonedeep'
+
+import {
+ ALL_MEDIA,
+ AUDIO,
+ IMAGE,
+ SupportedMediaType,
+ supportedSearchTypes,
+} from '~/constants/media'
+import {
+ filtersToQueryData,
+ queryStringToSearchType,
+ queryToFilterData,
+} from '~/utils/search-query-transform'
+import {
+ filterData,
+ mediaFilterKeys,
+ mediaUniqueFilterKeys,
+} from '~/constants/filters'
+import type { SupportedSearchType } from '~/constants/media'
+import type {
+ ApiQueryParams,
+ FilterCategory,
+ FilterItem,
+ Filters,
+ QueryKey,
+} from '~/store/types'
+
+export const useSearchStore = defineStore('search', () => {
+ const state: {
+ searchType: SupportedSearchType
+ searchTerm: string
+ filters: Filters
+ } = reactive({
+ searchType: ALL_MEDIA,
+ searchTerm: '',
+ filters: clonedeep(filterData),
+ })
+ const { filters, searchType, searchTerm } = toRefs(state)
+
+ // Setters
+ const setSearchType = (type: SupportedSearchType) => {
+ state.searchType = type
+ }
+ function setSearchTerm(term: string) {
+ state.searchTerm = term.trim()
+ }
+ watch(searchType, (searchType) => clearOtherMediaTypeFilters(searchType))
+
+ // Getters
+ /**
+ * Returns the search query parameters for API request:
+ * drops all parameters with blank values.
+ */
+ const searchQueryParams: ComputedRef<ApiQueryParams> = computed(() => {
+ return computeQueryParams(searchType.value, filters.value)
+ })
+
+ const computeQueryParams = (
+ searchType: SupportedSearchType,
+ filters: Filters = state.filters
+ ) => {
+ const query = { ...filtersToQueryData(filters, searchType) }
+
+ const queryKeys = Object.keys(query) as QueryKey[]
+ return queryKeys.reduce(
+ (obj, key: QueryKey) => {
+ if (key !== 'q' && query[key]?.length) {
+ obj[key] = query[key]
+ }
+ return obj
+ },
+ // Ensure that q filter always comes first
+ { q: state.searchTerm.trim() } as ApiQueryParams
+ )
+ }
+
+ const allFilterCategories = Object.keys(state.filters) as FilterCategory[]
+ /**
+ * Initial filters do not include the provider filters. We create the provider filters object
+ * when we fetch the provider data on the Nuxt server initialization.
+ * We call this function to reset the filters to the initial base filters AND the provider filters.
+ */
+ const getBaseFiltersWithProviders = (): Filters => {
+ const resetProviders = (mediaType: SupportedMediaType): FilterItem[] => {
+ return state.filters[`${mediaType}Providers`].map((provider) => ({
+ ...provider,
+ checked: false,
+ }))
+ }
+ return {
+ ...clonedeep(filterData),
+ audioProviders: resetProviders(AUDIO),
+ imageProviders: resetProviders(IMAGE),
+ }
+ }
+
+ /**
+ * Returns the number of checked filters, excluding the `mature` filter.
+ */
+ const appliedFilterCount: ComputedRef<number> = computed(() => {
+ const filterKeys = mediaFilterKeys[state.searchType].filter(
+ (f) => f !== 'mature'
+ )
+ return filterKeys.reduce((count, filterCategory) => {
+ return (
+ count + state.filters[filterCategory].filter((f) => f.checked).length
+ )
+ }, 0)
+ })
+
+ /**
+ * True if any filter for selected search type except `mature` is checked.
+ */
+ const isAnyFilterApplied: ComputedRef<boolean> = computed(() => {
+ const filterEntries = Object.entries(searchFilters.value) as [
+ string,
+ FilterItem[]
+ ][]
+ return filterEntries.some(
+ ([filterKey, filterItems]) =>
+ filterKey !== 'mature' && filterItems.some((filter) => filter.checked)
+ )
+ })
+
+ // Actions
+ /**
+ * After a search type is changed, unchecks all the filters that are not
+ * applicable for this Media type.
+ */
+ function clearOtherMediaTypeFilters(searchType: SupportedSearchType) {
+ const mediaTypesToClear = supportedSearchTypes.filter(
+ (type) => type !== searchType
+ )
+ const filterKeysToClear = mediaTypesToClear.reduce((acc, type) => {
+ return [...acc, ...mediaUniqueFilterKeys[type]]
+ }, [] as FilterCategory[])
+
+ allFilterCategories.forEach((filterCategory) => {
+ if (filterKeysToClear.includes(filterCategory)) {
+ state.filters[filterCategory] = state.filters[filterCategory].map(
+ (f) => ({
+ ...f,
+ checked: false,
+ })
+ )
+ }
+ })
+ }
+
+ /**
+ * Replaces filters with the newFilterData object that was created using initial filters,
+ * and setting parameters from the search query to checked.
+ *
+ *
+ *
+ */
+ function replaceFilters(newFilterData: Filters) {
+ allFilterCategories.forEach((filterCategory) => {
+ state.filters[filterCategory] = newFilterData[filterCategory]
+ })
+ }
+
+ /**
+ * 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.
+ */
+ function initProviderFilters({
+ mediaType,
+ providers,
+ }: {
+ mediaType: SupportedMediaType
+ providers: { source_name: string; display_name: string }[]
+ }) {
+ const providersKey: FilterCategory = `${mediaType}Providers`
+ const currentProviders = state.filters[providersKey]
+ ? [...state.filters[providersKey]]
+ : []
+ state.filters[providersKey] = providers.map((provider) => {
+ const existingProviderFilterIdx = currentProviders.findIndex(
+ (p) => p.code === provider.source_name
+ )
+ const checked =
+ existingProviderFilterIdx >= 0
+ ? currentProviders[existingProviderFilterIdx].checked
+ : false
+
+ return {
+ code: provider.source_name,
+ name: provider.display_name,
+ checked,
+ }
+ })
+ }
+ /**
+ * Toggles a filter's checked parameter. Requires either codeIdx or code.
+ */
+ function toggleFilter({
+ filterType,
+ codeIdx,
+ code,
+ }: {
+ filterType: FilterCategory
+ codeIdx?: number
+ code?: string
+ }) {
+ if (typeof codeIdx === 'undefined' && typeof code === 'undefined') {
+ throw new Error(
+ `Cannot toggle filter of type ${filterType}. Use code or codeIdx parameter`
+ )
+ }
+ const filterItems = state.filters[filterType]
+ const idx = codeIdx ?? filterItems.findIndex((f) => f.code === code)
+ state.filters[filterType][idx].checked = !filterItems[idx].checked
+ }
+
+ /**
+ * Resets all filters to initial values.
+ * Provider filters are not in the initial filters, so they need to be
+ * handled separately.
+ *
+ */
+ const clearFilters = () => {
+ for (const filterCategory of Object.keys(
+ state.filters
+ ) as FilterCategory[]) {
+ for (const filterItem of state.filters[filterCategory]) {
+ filterItem.checked = false
+ }
+ }
+ }
+
+ /**
+ * Selecting some filter items disables related items. For example, selecting an `nc`
+ * license filter (CC BY-NC, CC BY-NC-SA, CC BY-NC-ND) disables the `Commercial` license
+ * type filter. This function determines if the filter item should be disabled based on
+ * the currently checked filter items.
+ */
+ function isFilterDisabled(
+ item: FilterItem,
+ filterCategory: FilterCategory
+ ): boolean | undefined {
+ if (!['licenseTypes', 'licenses'].includes(filterCategory)) {
+ return
+ }
+ if (item.code === 'commercial' || item.code === 'modification') {
+ const targetCode = {
+ commercial: 'nc',
+ modification: 'nd',
+ }[item.code]
+ return state.filters.licenses.some(
+ (item) => item.code.includes(targetCode) && item.checked
+ )
+ } else {
+ const dependentFilters: string[] = []
+ if (item.code.includes('nc')) {
+ dependentFilters.push('commercial')
+ }
+ if (item.code.includes('nd')) {
+ dependentFilters.push('modification')
+ }
+ return state.filters.licenseTypes.some(
+ (item) => dependentFilters.includes(item.code) && item.checked
+ )
+ }
+ }
+
+ /**
+ * Returns the object with filters for selected search type, with codes, names for i18n labels, and checked status.
+ */
+ const searchFilters: ComputedRef<Filters> = computed(() => {
+ return mediaFilterKeys[state.searchType]
+ .filter((filterKey) => filterKey !== 'mature')
+ .reduce((obj, filterKey) => {
+ obj[filterKey] = state.filters[filterKey]
+ return obj
+ }, {} as Filters)
+ })
+
+ /**
+ * Called when a /search path is server-rendered.
+ */
+ function setSearchStateFromUrl({
+ path,
+ urlQuery,
+ }: {
+ path: string
+ urlQuery: Record<string, string>
+ }) {
+ if (urlQuery.q) {
+ setSearchTerm(urlQuery.q.trim())
+ }
+ state.searchType = queryStringToSearchType(path)
+ // When setting filters from URL query, 'mature' has a value of 'true',
+ // but we need the 'mature' code. Creating a local shallow copy to prevent mutation.
+ const query = { ...urlQuery }
+ if (query.mature === 'true') {
+ query.mature = 'mature'
+ } else {
+ delete query.mature
+ }
+
+ const newFilterData = queryToFilterData({
+ query,
+ searchType: state.searchType,
+ defaultFilters: getBaseFiltersWithProviders(),
+ })
+ replaceFilters(newFilterData)
+ }
+
+ return {
+ searchTerm,
+ searchType,
+ filters,
+
+ appliedFilterCount,
+ isAnyFilterApplied,
+ searchFilters,
+ searchQueryParams,
+
+ setSearchTerm,
+ setSearchType,
+ setSearchStateFromUrl,
+ initProviderFilters,
+ isFilterDisabled,
+ clearFilters,
+ toggleFilter,
+ computeQueryParams,
+ }
+})
diff --git a/src/utils/get-provider-name.js b/src/utils/get-provider-name.js
deleted file mode 100644
index 786bcd30f..000000000
--- a/src/utils/get-provider-name.js
+++ /dev/null
@@ -1,13 +0,0 @@
-import { capital } from 'case'
-
-export default function getProviderName(providersList, providerCode) {
- if (!providersList) {
- return capital(providerCode) || ''
- }
-
- const provider = providersList.filter(
- (p) => p.source_name === providerCode
- )[0]
-
- return provider ? provider.display_name : capital(providerCode) || ''
-}
diff --git a/src/utils/prop-validators.js b/src/utils/prop-validators.js
new file mode 100644
index 000000000..6f1f8efda
--- /dev/null
+++ b/src/utils/prop-validators.js
@@ -0,0 +1,10 @@
+import { supportedSearchTypes } from '~/constants/media'
+
+/**
+ * Validates the search types that have supported API endpoints.
+ * This means that ALL_MEDIA is invalid because it is basically
+ * a combination of all other supported API media types.
+ * Any future search type that is not fully supported (video, 3d)
+ * will also be invalid.
+ */
+export const isValidSearchType = (v) => supportedSearchTypes.includes(v)
diff --git a/src/utils/search-query-transform.js b/src/utils/search-query-transform.ts
similarity index 50%
rename from src/utils/search-query-transform.js
rename to src/utils/search-query-transform.ts
index 8faa9a216..bed100c39 100644
--- a/src/utils/search-query-transform.js
+++ b/src/utils/search-query-transform.ts
@@ -1,11 +1,24 @@
+// We plan to remove this dependency, so don't need to add types for it:
+// https://github.com/WordPress/openverse-frontend/issues/1103
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-ignore
import clonedeep from 'lodash.clonedeep'
import { mediaFilterKeys } from '~/constants/filters'
-import { ALL_MEDIA } from '~/constants/media'
+import { ALL_MEDIA, SupportedSearchType } from '~/constants/media'
import { getParameterByName } from '~/utils/url-params'
-
-const filterPropertyMappings = {
+import type {
+ ApiQueryFilters,
+ ApiQueryKeys,
+ ApiQueryParams,
+ FilterCategory,
+ FilterItem,
+ Filters,
+ QueryKey,
+} from '~/store/types'
+
+const filterPropertyMappings: Record<FilterCategory, ApiQueryKeys> = {
licenses: 'license',
licenseTypes: 'license_type',
audioCategories: 'categories',
@@ -21,7 +34,9 @@ const filterPropertyMappings = {
mature: 'mature',
}
-const getMediaFilterTypes = (searchType) => [...mediaFilterKeys[searchType]]
+const getMediaFilterTypes = (searchType: SupportedSearchType) => [
+ ...mediaFilterKeys[searchType],
+]
// {
// license: 'cc0,pdm,by,by-sa,by-nc,by-nd,by-nc-sa,by-nc-nd',
// imageCategories: 'photograph,illustration,digitized_artwork',
@@ -35,9 +50,8 @@ const getMediaFilterTypes = (searchType) => [...mediaFilterKeys[searchType]]
* Joins all the filters which have the checked property `true`
* to a string separated by commas for the API request URL, e.g.: "by,nd-nc,nc-sa".
* Mature is a special case, and is converted to `true`.
- * @param {import('../store/types').FilterItem[]} filterItem
*/
-const filterToString = (filterItem) => {
+const filterToString = (filterItem: FilterItem[]) => {
const filterString = filterItem
.filter((f) => f.checked)
.map((filterItem) => filterItem.code)
@@ -46,40 +60,28 @@ const filterToString = (filterItem) => {
}
/**
- * converts the filter store object to the data format accepted by the API,
- * which has slightly different property names
- * @param {object} filters object containing the filter data that comes from the filter store
- * @param {import('../constants/media').SearchType} searchType
- * @param hideEmpty
- * @todo Refactor all of these 'reduce' calls to just use lodash methods :)
+ * Converts the filter store object to the data format accepted by the API,
+ * which has slightly different property names.
+ * @param filters - object containing the filter data that comes from the filter store
+ * @param searchType - search type for which API query should be created
+ * @param hideEmpty - whether the query params with empty values should be removed
+ * TODO: Refactor all of these 'reduce' calls to just use lodash methods :)
*/
export const filtersToQueryData = (
- filters,
- searchType = ALL_MEDIA,
+ filters: Filters,
+ searchType: SupportedSearchType = ALL_MEDIA,
hideEmpty = true
-) => {
- let queryDataObject = {}
-
- let mediaFilterTypes = getMediaFilterTypes(searchType)
- mediaFilterTypes.reduce((queryData, filterDataKey) => {
- const queryDataKey = filterPropertyMappings[filterDataKey]
- queryData[queryDataKey] = filterToString(filters[filterDataKey])
- return queryData
- }, queryDataObject)
-
- if (hideEmpty) {
- queryDataObject = Object.entries(queryDataObject).reduce(
- (obj, [key, value]) => {
- if (value) {
- obj[key] = value
- }
- return obj
- },
- {}
- )
- }
-
- return queryDataObject
+): ApiQueryFilters => {
+ const mediaFilterTypes = getMediaFilterTypes(searchType)
+
+ return mediaFilterTypes.reduce((query, filterCategory) => {
+ const queryKey = filterPropertyMappings[filterCategory]
+ const queryValue = filterToString(filters[filterCategory])
+ if (queryValue || !hideEmpty) {
+ query[queryKey] = queryValue
+ }
+ return query
+ }, {} as ApiQueryFilters)
}
/**
@@ -87,13 +89,16 @@ export const filtersToQueryData = (
* of the path between `/search/` and query, or `all` by default.
* `/search/?q=test`: all
* `/search/image?q=test`: image
- * @param {string} queryString
- * @return {import('../constants/media').SearchType}
+ * @param queryString - the query string from the url
*/
-export const queryStringToSearchType = (queryString) => {
+export const queryStringToSearchType = (
+ queryString: string
+): SupportedSearchType => {
const searchTypePattern = /\/search\/(image|audio|video)\?*/
- let matchedType = queryString.match(searchTypePattern)
- return matchedType === null ? ALL_MEDIA : matchedType[1]
+ const matchedType = queryString.match(searchTypePattern)
+ return matchedType === null
+ ? ALL_MEDIA
+ : (matchedType[1] as SupportedSearchType)
}
/**
@@ -102,20 +107,21 @@ export const queryStringToSearchType = (queryString) => {
* `source` - audioProviders/imageProviders
* `extensions` - audioExtensions/imageExtensions
* `categories` - audioCategories/imageCategories
+ *
* This function sets only filters that are possible for current
* media type. E.g., for queryString `search/audio?extensions=ogg`
* the `audioExtensions.ogg.checked` is set to true,
* but for `search/images?extensions=ogg`, the extensions query parameter
* is discarded, because `ogg` is not a valid extension for images.
- * @param {string} filterParameter
- * @param {import('../store/types').FilterItem[]} parameterFilters
- * @return {import('../store/types').FilterItem[]}
*/
-const getMediaTypeApiFilters = (filterParameter, parameterFilters) => {
+const getMediaTypeApiFilters = (
+ filterParameter: string,
+ parameterFilters: FilterItem[]
+): FilterItem[] => {
if (filterParameter !== '') {
const parameterValues = filterParameter.split(',')
parameterValues.forEach((parameter) => {
- let existingParameterIdx = parameterFilters.findIndex(
+ const existingParameterIdx = parameterFilters.findIndex(
(p) => p.code === parameter
)
if (existingParameterIdx > -1) {
@@ -130,20 +136,29 @@ const getMediaTypeApiFilters = (filterParameter, parameterFilters) => {
}
/**
- * converts the browser filter query string into the internal filter store data format
- * @param {object} params
- * @param {Record<string, string>} params.query - browser filter query
- * @param {import('../constants/media').SearchType} [params.searchType]
- * @param {object} params.defaultFilters default filters for testing purposes
+ * Converts the browser filter query string into the internal filter store data format.
+ * For the API parameters that have the same name, but correspond to different filter categories
+ * (`differentFiltersWithSameApiParams`), only the filters that exist for the selected search type
+ * are used:
+ * E.g. when the search type is `audio`, `extension=jpg,mp3` sets the audioExtensions mp3.checked to true,
+ * and discards `jpg`.
+ *
+ * @param query - browser filter query
+ * @param searchType - search type determines which filters are applied
+ * @param defaultFilters - default filters for testing purposes
*/
export const queryToFilterData = ({
query,
searchType = 'image',
defaultFilters,
+}: {
+ query: Record<string, string>
+ searchType: SupportedSearchType
+ defaultFilters: Partial<Filters>
}) => {
// The default filterData object from search store doesn't contain provider filters,
// so we can't use it.
- const filters = clonedeep(defaultFilters)
+ const filters = clonedeep(defaultFilters) as Filters
const filterTypes = getMediaFilterTypes(searchType)
const differentFiltersWithSameApiParams = [
'audioProviders',
@@ -155,23 +170,29 @@ export const queryToFilterData = ({
]
filterTypes.forEach((filterDataKey) => {
if (differentFiltersWithSameApiParams.includes(filterDataKey)) {
- const parameter = query[filterPropertyMappings[filterDataKey]]
- if (parameter) {
- filters[filterDataKey] = getMediaTypeApiFilters(
- parameter,
- filters[filterDataKey]
- )
+ if (filterDataKey.startsWith(searchType)) {
+ const parameter = query[filterPropertyMappings[filterDataKey]]
+ if (parameter) {
+ filters[filterDataKey] = getMediaTypeApiFilters(
+ parameter,
+ filters[filterDataKey]
+ )
+ }
}
} else {
const queryDataKey = filterPropertyMappings[filterDataKey]
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
- }
- })
+ if (queryDataKey === 'mature' && query[queryDataKey].length > 0) {
+ filters[filterDataKey][0].checked = true
+ } else {
+ const filterValues = query[queryDataKey].split(',')
+ filterValues.forEach((val: string) => {
+ const idx = filters[filterDataKey].findIndex((f) => f.code === val)
+ if (idx >= 0) {
+ filters[filterDataKey][idx].checked = true
+ }
+ })
+ }
}
}
})
@@ -187,10 +208,9 @@ export const queryToFilterData = ({
*
* TODO: we might be able to refactor to eliminate the need for these two
* separate functions.
- * @param {string} queryString
*/
-export const queryStringToQueryData = (queryString) => {
- const queryDataObject = {}
+export const queryStringToQueryData = (queryString: string) => {
+ const queryDataObject = {} as ApiQueryParams
const searchType = queryStringToSearchType(queryString)
const filterTypes = getMediaFilterTypes(searchType)
filterTypes.forEach((filterDataKey) => {
@@ -205,8 +225,20 @@ export const queryStringToQueryData = (queryString) => {
return queryDataObject
}
-export const areQueriesEqual = (oldQuery, newQuery) => {
- for (let key of Object.keys(oldQuery)) {
+/**
+ * Compares two API queries, excluding the search term (`q`) parameter.
+ */
+export const areQueriesEqual = (
+ newQuery: ApiQueryParams,
+ oldQuery: ApiQueryParams
+): boolean => {
+ const queryKeys = (query: ApiQueryParams) =>
+ Object.keys(query).filter((k) => k !== 'q') as QueryKey[]
+ const oldQueryKeys = queryKeys(oldQuery)
+ const newQueryKeys = queryKeys(newQuery)
+ if (oldQueryKeys.length !== newQueryKeys.length) return false
+
+ for (const key of oldQueryKeys) {
if (oldQuery[key] !== newQuery[key]) {
return false
}
diff --git a/test/e2e/filters.spec.js b/test/e2e/filters.spec.js
index 652ae74e7..fe6ce0d51 100644
--- a/test/e2e/filters.spec.js
+++ b/test/e2e/filters.spec.js
@@ -73,6 +73,9 @@ test('common filters are retained when media type changes from all media to sing
await openFilters(page)
const expectedFilters = ['cc0', 'commercial', 'creator']
+ for (let checkbox of expectedFilters) {
+ await assertCheckboxStatus(page, checkbox)
+ }
await changeContentType(page, 'Images')
await expect(page).toHaveURL(
diff --git a/test/unit/specs/components/VHeader/v-filter-button.spec.js b/test/unit/specs/components/VHeader/v-filter-button.spec.js
index 981e03a78..be3a77c3e 100644
--- a/test/unit/specs/components/VHeader/v-filter-button.spec.js
+++ b/test/unit/specs/components/VHeader/v-filter-button.spec.js
@@ -6,21 +6,22 @@ import { ref } from '@nuxtjs/composition-api'
import { createPinia, PiniaVuePlugin } from 'pinia'
import messages from '~/locales/en.json'
-import { useFilterStore } from '~/stores/filter'
-import { filterData, mediaFilterKeys } from '~/constants/filters'
+import { filterData, mediaFilterKeys } from '~/constants/filters'
import { IMAGE } from '~/constants/media'
+import { useSearchStore } from '~/stores/search'
+
import VFilterButton from '~/components/VHeader/VFilterButton.vue'
-function applyNFilters(filterCount, filterStore) {
+function applyNFilters(filterCount, searchStore) {
const filterTypes = [...mediaFilterKeys[IMAGE]]
let filterIdx = 0
// Skip license type filters as they can disable license filters
let filterTypeIdx = 1
for (let i = 0; i < filterCount; i++) {
let filterType = filterTypes[filterTypeIdx]
- filterStore.toggleFilter({
+ searchStore.toggleFilter({
filterType,
codeIdx: filterIdx,
})
@@ -41,7 +42,7 @@ describe('VFilterButton', () => {
isHeaderScrolled: ref(false),
}
let pinia
- let filterStore
+ let searchStore
const i18n = new VueI18n({
locale: 'en',
@@ -54,10 +55,10 @@ describe('VFilterButton', () => {
localVue.use(VueI18n)
localVue.use(PiniaVuePlugin)
pinia = createPinia()
- filterStore = useFilterStore(pinia)
+ searchStore = useSearchStore(pinia)
// the default ALL_MEDIA has fewer filters that can be applied,
// ensure that we can test for more than 10 filters
- filterStore.setSearchType(IMAGE)
+ searchStore.setSearchType(IMAGE)
options = {
localVue,
@@ -83,7 +84,7 @@ describe('VFilterButton', () => {
provided.isMinScreenMd.value = true
// +2 to guarantee it's plural
const filterCount = Math.floor(Math.random() * 9) + 2
- applyNFilters(filterCount, filterStore)
+ applyNFilters(filterCount, searchStore)
const wrapper = render(VFilterButton, options)
const button = wrapper.getByText(`${filterCount} Filters`)
@@ -91,7 +92,7 @@ describe('VFilterButton', () => {
})
it('does not show the icon when filters are applied', () => {
provided.isMinScreenMd.value = true
- filterStore.toggleFilter({ filterType: 'licenses', codeIdx: 0 })
+ searchStore.toggleFilter({ filterType: 'licenses', codeIdx: 0 })
const { container } = render(VFilterButton, options)
const icon = container.querySelector('svg')
@@ -115,7 +116,7 @@ describe('VFilterButton', () => {
provided.isMinScreenMd.value = false
// +2 to guarantee it's plural
const filterCount = Math.floor(Math.random() * 10) + 2
- applyNFilters(filterCount, filterStore)
+ applyNFilters(filterCount, searchStore)
const { container } = render(VFilterButton, options)
const icon = container.querySelector('svg')
@@ -129,7 +130,7 @@ describe('VFilterButton', () => {
provided.isHeaderScrolled.value = true
// +2 to guarantee it's plural
const filterCount = Math.floor(Math.random() * 10) + 2
- applyNFilters(filterCount, filterStore)
+ applyNFilters(filterCount, searchStore)
const { container } = render(VFilterButton, options)
const icon = container.querySelector('svg')
diff --git a/test/unit/specs/components/v-search-grid-filter.spec.js b/test/unit/specs/components/v-search-grid-filter.spec.js
index 48bd16540..bd2f7d91d 100644
--- a/test/unit/specs/components/v-search-grid-filter.spec.js
+++ b/test/unit/specs/components/v-search-grid-filter.spec.js
@@ -1,17 +1,14 @@
import Vuex from 'vuex'
import { fireEvent, render, screen } from '@testing-library/vue'
import { createLocalVue } from '@vue/test-utils'
-
import VueI18n from 'vue-i18n'
import { createPinia, PiniaVuePlugin } from 'pinia'
-import { IMAGE } from '~/constants/media'
-import store from '~/store/search'
-import { FETCH_MEDIA } from '~/constants/action-types'
-
import messages from '~/locales/en.json'
-import { useFilterStore } from '~/stores/filter'
+import { FETCH_MEDIA } from '~/constants/action-types'
+
+import { useSearchStore } from '~/stores/search'
import VSearchGridFilter from '~/components/VFilters/VSearchGridFilter.vue'
@@ -20,8 +17,9 @@ describe('VSearchGridFilter', () => {
let storeMock
let localVue
let pinia
- let filterStore
+ let searchStore
const routerMock = { push: jest.fn() }
+ const routeMock = { path: jest.fn() }
beforeEach(() => {
localVue = createLocalVue()
@@ -36,16 +34,6 @@ describe('VSearchGridFilter', () => {
})
storeMock = new Vuex.Store({
modules: {
- search: {
- namespaced: true,
- state: {
- searchType: IMAGE,
- query: { q: '' },
- },
- mutations: store.mutations,
- actions: store.actions,
- getters: store.getters,
- },
media: {
namespaced: true,
state: {
@@ -63,17 +51,19 @@ describe('VSearchGridFilter', () => {
pinia,
i18n,
mocks: {
+ $route: routeMock,
$router: routerMock,
$store: storeMock,
$nuxt: {
context: {
+ app: { localePath: jest.fn() },
i18n: { t: (s) => s },
store: storeMock,
},
},
},
}
- filterStore = useFilterStore(pinia)
+ searchStore = useSearchStore(pinia)
})
it('toggles filter', async () => {
@@ -87,7 +77,7 @@ describe('VSearchGridFilter', () => {
})
it('clears filters', async () => {
- filterStore.toggleFilter({ filterType: 'licenses', code: 'by' })
+ searchStore.toggleFilter({ filterType: 'licenses', code: 'by' })
await render(VSearchGridFilter, options)
// if no checked checkboxes were found, this would raise an error
screen.getByRole('checkbox', { checked: true })
@@ -99,7 +89,7 @@ describe('VSearchGridFilter', () => {
})
expect(checkedFilters.length).toEqual(0)
- // Filters are reset with the initial `filterData`
- expect(uncheckedFilters.length).toEqual(24)
+ // Filters are reset with the initial `filterData` for ALL_MEDIA
+ expect(uncheckedFilters.length).toEqual(11)
})
})
diff --git a/test/unit/specs/pages/browse-page.spec.js b/test/unit/specs/pages/browse-page.spec.js
index e87753820..04353bb67 100644
--- a/test/unit/specs/pages/browse-page.spec.js
+++ b/test/unit/specs/pages/browse-page.spec.js
@@ -2,25 +2,29 @@ import { render, screen } from '@testing-library/vue'
import { createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
import { ref } from '@nuxtjs/composition-api'
+import { createPinia, PiniaVuePlugin } from 'pinia'
import SearchIndex from '~/pages/search.vue'
+import { IMAGE } from '~/constants/media'
+
+import { useSearchStore } from '~/stores/search'
describe('SearchIndex', () => {
let options
let localVue
let storeMock
+ let pinia
+ let searchStore
beforeEach(() => {
localVue = createLocalVue()
localVue.use(Vuex)
+ localVue.use(PiniaVuePlugin)
+ pinia = createPinia()
+ searchStore = useSearchStore(pinia)
+ searchStore.setSearchTerm('cat')
+ searchStore.setSearchType(IMAGE)
storeMock = new Vuex.Store({
modules: {
- search: {
- namespaced: true,
- state: {
- query: { q: 'foo' },
- searchType: 'image',
- },
- },
media: {
namespaced: true,
getters: {
@@ -33,6 +37,7 @@ describe('SearchIndex', () => {
})
options = {
localVue,
+ pinia,
store: storeMock,
mocks: {
$router: { path: { name: 'search-image' } },
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 581445f96..000000000
--- a/test/unit/specs/store/filter-store.spec.js
+++ /dev/null
@@ -1,269 +0,0 @@
-import { setActivePinia, createPinia } from 'pinia'
-
-import { useFilterStore } from '~/stores/filter'
-
-import { filterData } from '~/constants/filters'
-import { ALL_MEDIA, AUDIO, IMAGE, VIDEO } from '~/constants/media'
-import { warn } from '~/utils/console'
-
-jest.mock('~/utils/console', () => ({
- warn: jest.fn(),
-}))
-
-describe('Filter Store', () => {
- beforeEach(() => {
- setActivePinia(createPinia())
- })
- describe('state', () => {
- it('sets initial filters to filterData', () => {
- const filterStore = useFilterStore()
- expect(filterStore.filters).toEqual(filterData)
- })
- })
- describe('getters', () => {
- /**
- * Check for some special cases:
- * - `mature` and `searchBy`.
- * - several options for single filter.
- * - media specific filters that are unique (durations).
- * - media specific filters that have the same API param (extensions)
- */
- it.each`
- query | searchType | filterCount
- ${{ licenses: ['by'], mature: ['mature'] }} | ${IMAGE} | ${1}
- ${{ licenses: ['by'], searchBy: ['creator'] }} | ${ALL_MEDIA} | ${2}
- ${{ licenses: ['cc0', 'pdm', 'by', 'by-nc'] }} | ${ALL_MEDIA} | ${4}
- ${{ durations: ['medium'] }} | ${AUDIO} | ${1}
- ${{ imageExtensions: ['svg'] }} | ${IMAGE} | ${1}
- ${{ audioExtensions: ['mp3'] }} | ${AUDIO} | ${1}
- `(
- 'returns correct filter status for $query and searchType $searchType',
- ({ query, searchType, filterCount }) => {
- const filterStore = useFilterStore()
- filterStore.setSearchType(searchType)
- for (let [filterType, values] of Object.entries(query)) {
- values.forEach((val) =>
- filterStore.toggleFilter({ filterType, code: val })
- )
- }
-
- expect(filterStore.appliedFilterCount).toEqual(filterCount)
- expect(filterStore.isAnyFilterApplied).toBe(filterCount > 0)
- }
- )
- })
- describe('actions', () => {
- it.each`
- filterType | codeIdx
- ${'licenses'} | ${0}
- ${'licenseTypes'} | ${0}
- ${'imageExtensions'} | ${0}
- ${'imageCategories'} | ${0}
- ${'searchBy'} | ${0}
- ${'aspectRatios'} | ${0}
- ${'sizes'} | ${0}
- ${'mature'} | ${0}
- `(
- 'toggleFilter updates $filterType filter state',
- ({ filterType, codeIdx }) => {
- const filterStore = useFilterStore()
-
- filterStore.toggleFilter({ filterType, codeIdx })
- const filterItem = filterStore.filters[filterType][codeIdx]
- expect(filterItem.checked).toEqual(true)
- }
- )
-
- it('toggleFilter updates isFilterApplied with provider', () => {
- const filterStore = useFilterStore()
- filterStore.setSearchType(IMAGE)
- filterStore.initProviderFilters({
- mediaType: IMAGE,
- providers: [{ source_name: 'met', display_name: 'Met' }],
- })
-
- filterStore.toggleFilter({ filterType: 'imageProviders', code: 'met' })
- expect(filterStore.appliedFilterCount).toEqual(1)
- expect(filterStore.isAnyFilterApplied).toEqual(true)
- })
-
- it('toggleFilter updates isFilterApplied with license type', () => {
- const filterStore = useFilterStore()
- filterStore.toggleFilter({ filterType: 'licenseTypes', codeIdx: 0 })
-
- expect(filterStore.isAnyFilterApplied).toEqual(true)
- })
-
- it('initProviderFilters merges with existing provider filters', () => {
- const filterStore = useFilterStore()
- const existingProviderFilters = [{ code: 'met', checked: true }]
-
- filterStore.$patch({
- filters: { imageProviders: existingProviderFilters },
- })
- const providers = [
- { source_name: 'met', display_name: 'Metropolitan' },
- { source_name: 'flickr', display_name: 'Flickr' },
- ]
-
- filterStore.initProviderFilters({
- mediaType: 'image',
- providers: providers,
- })
-
- expect(filterStore.filters.imageProviders).toEqual([
- { code: 'met', name: 'Metropolitan', checked: true },
- { code: 'flickr', name: 'Flickr', checked: false },
- ])
- })
-
- it('clearFilters resets filters to initial state', async () => {
- const filterStore = useFilterStore()
- filterStore.filters.licenses = [
- { code: 'by', checked: true },
- { code: 'by-nc', checked: true },
- { code: 'by-nd', checked: true },
- ]
- filterStore.clearFilters()
- expect(filterStore.filters).toEqual(filterData)
- })
-
- it('clearFilters sets providers filters checked to false', async () => {
- const filterStore = useFilterStore()
- filterStore.filters.imageProviders = [
- { code: 'met', name: 'Metropolitan', checked: true },
- { code: 'flickr', name: 'Flickr', checked: false },
- ]
-
- filterStore.clearFilters()
- const expectedFilters = {
- ...filterStore.filters,
- imageProviders: [
- { code: 'met', name: 'Metropolitan', checked: false },
- { code: 'flickr', name: 'Flickr', checked: false },
- ],
- }
- expect(filterStore.filters).toEqual(expectedFilters)
- })
-
- it.each`
- filterType | code | idx
- ${'licenses'} | ${'cc0'} | ${1}
- ${'licenseTypes'} | ${'modification'} | ${1}
- ${'imageExtensions'} | ${'svg'} | ${3}
- ${'imageCategories'} | ${'photograph'} | ${0}
- ${'searchBy'} | ${'creator'} | ${0}
- ${'mature'} | ${'mature'} | ${-0}
- ${'aspectRatios'} | ${'tall'} | ${0}
- ${'sizes'} | ${'medium'} | ${1}
- `(
- "toggleFilter should set filter '$code' of type '$filterType",
- ({ filterType, code, idx }) => {
- const filterStore = useFilterStore()
- filterStore.toggleFilter({ filterType: filterType, code: code })
-
- const filterItem = filterStore.filters[filterType][idx]
-
- expect(filterItem.checked).toEqual(true)
- }
- )
- it.each`
- item | dependency | disabled
- ${{ code: 'by-nc', filterType: 'licenses' }} | ${{ filterType: 'licenseTypes', code: 'commercial' }} | ${true}
- ${{ code: 'by-nc-nd', filterType: 'licenses' }} | ${{ filterType: 'licenseTypes', code: 'commercial' }} | ${true}
- ${{ code: 'by-nc-sa', filterType: 'licenses' }} | ${{ filterType: 'licenseTypes', code: 'commercial' }} | ${true}
- ${{ code: 'by-nd', filterType: 'licenses' }} | ${{ filterType: 'licenseTypes', code: 'modification' }} | ${true}
- ${{ code: 'by-nc-nd', filterType: 'licenses' }} | ${{ filterType: 'licenseTypes', code: 'modification' }} | ${true}
- ${{ code: 'by-nc', filterType: 'licenses' }} | ${{ filterType: 'licenseTypes', code: 'modification' }} | ${false}
- ${{ code: 'by-nd', filterType: 'licenses' }} | ${{ filterType: 'licenseTypes', code: 'commercial' }} | ${false}
- ${{ code: 'commercial', filterType: 'licenseTypes' }} | ${{ filterType: 'licenses', code: 'by-nc' }} | ${true}
- ${{ code: 'commercial', filterType: 'licenseTypes' }} | ${{ filterType: 'licenses', code: 'by-nc-nd' }} | ${true}
- ${{ code: 'commercial', filterType: 'licenseTypes' }} | ${{ filterType: 'licenses', code: 'by-nc-sa' }} | ${true}
- ${{ code: 'modification', filterType: 'licenseTypes' }} | ${{ filterType: 'licenses', code: 'by-nd' }} | ${true}
- ${{ code: 'modification', filterType: 'licenseTypes' }} | ${{ filterType: 'licenses', code: 'by-nc-nd' }} | ${true}
- `(
- 'isFilterDisabled for $item.code should return $disabled when $dependency.code is checked',
- ({ item, dependency, disabled }) => {
- const filterStore = useFilterStore()
- filterStore.toggleFilter({
- filterType: dependency.filterType,
- code: dependency.code,
- })
- const isDisabled = filterStore.isFilterDisabled(item, item.filterType)
- expect(isDisabled).toBe(disabled)
- }
- )
-
- it('toggleFilter without code or codeIdx parameters warns about it', () => {
- const filterStore = useFilterStore()
- const expectedFilters = filterStore.filters
-
- filterStore.toggleFilter({ filterType: 'licenses' })
- expect(warn).toHaveBeenCalledWith(
- 'Cannot toggle filter of type licenses. Use code or codeIdx parameter'
- )
- expect(filterStore.filters).toEqual(expectedFilters)
- })
-
- it.each`
- searchType | expectedFilterCount
- ${IMAGE} | ${25}
- ${AUDIO} | ${21}
- ${VIDEO} | ${12}
- ${ALL_MEDIA} | ${12}
- `(
- 'clearOtherMediaTypeFilters clears all but $expectedFilterCount $searchType filters ',
- ({ searchType, expectedFilterCount }) => {
- const filterStore = useFilterStore()
-
- // Set all filters to checked
- for (let ft in filterStore.filters) {
- for (let f of filterStore.filters[ft]) {
- filterStore.toggleFilter({ filterType: ft, code: f.code })
- }
- }
-
- filterStore.clearOtherMediaTypeFilters({ searchType })
- const checkedFilterCount = Object.keys(filterStore.filters)
- .map(
- (key) => filterStore.filters[key].filter((f) => f.checked).length
- )
- .reduce((partialSum, count) => partialSum + count, 0)
- expect(checkedFilterCount).toEqual(expectedFilterCount)
- }
- )
-
- it.each`
- query | checkedFilters
- ${{ q: 'cat', license: 'by-sa', mature: 'true' }} | ${[['licenses', 'by-sa'], ['mature', 'mature']]}
- ${{ license: 'cc0', extension: 'svg' }} | ${[['licenses', 'cc0'], ['imageExtensions', 'svg']]}
- `(
- 'updateFiltersFromUrl sets correct filters from $query',
- ({ query, checkedFilters }) => {
- const filterStore = useFilterStore()
- filterStore.updateFiltersFromUrl(query, IMAGE)
- for (let [filterType, filterCode] of checkedFilters) {
- const filterItem = filterStore.filters[filterType].find(
- (f) => f.code === filterCode
- )
- expect(filterItem.checked).toEqual(true)
- }
- }
- )
- it('Does not set filter or count filter as applied, and does not raise error for unsupported search types', () => {
- const filterStore = useFilterStore()
- filterStore.toggleFilter({
- filterType: 'licenseTypes',
- code: 'commercial',
- })
- expect(filterStore.isAnyFilterApplied).toEqual(true)
-
- filterStore.setSearchType(VIDEO)
- filterStore.toggleFilter({
- filterType: 'licenseTypes',
- code: 'commercial',
- })
- expect(filterStore.isAnyFilterApplied).toEqual(false)
- })
- })
-})
diff --git a/test/unit/specs/store/media-store.spec.js b/test/unit/specs/store/media-store.spec.js
index f00173c6d..f64f9fd49 100644
--- a/test/unit/specs/store/media-store.spec.js
+++ b/test/unit/specs/store/media-store.spec.js
@@ -1,3 +1,5 @@
+import { createPinia, setActivePinia } from 'pinia'
+
import store, { createActions } from '~/store/media'
import {
FETCH_END_MEDIA,
@@ -16,7 +18,9 @@ import {
} from '~/constants/action-types'
import { AUDIO, IMAGE, supportedMediaTypes } from '~/constants/media'
-describe('Search Store', () => {
+import { useSearchStore } from '~/stores/search'
+
+describe('Media Store', () => {
describe('state', () => {
it('exports default state', () => {
const state = store.state()
@@ -186,7 +190,10 @@ describe('Search Store', () => {
let services = null
let state
let context
+ let searchStore
+
beforeEach(() => {
+ setActivePinia(createPinia())
services = {
[AUDIO]: {
search: jest.fn(() => Promise.resolve(searchResults)),
@@ -221,12 +228,6 @@ describe('Search Store', () => {
context = {
commit: jest.fn(),
dispatch: jest.fn(),
- rootState: {
- search: { query: { q: 'cat' } },
- },
- rootGetters: {
- search: { searchQueryParams: () => ({ q: 'cat' }) },
- },
state: state,
}
})
@@ -234,6 +235,8 @@ describe('Search Store', () => {
it.each(supportedMediaTypes)(
'FETCH_SINGLE_MEDIA_TYPE (%s) on success',
async (mediaType) => {
+ searchStore = useSearchStore()
+ searchStore.setSearchTerm('cat')
const params = {
q: 'foo',
shouldPersistMedia: true,
@@ -356,6 +359,8 @@ describe('Search Store', () => {
'FETCH_MEDIA_ITEM dispatches SEND_RESULT_CLICKED_EVENT',
(mediaType) => {
const params = { id: 'foo', mediaType }
+ searchStore = useSearchStore()
+ searchStore.setSearchTerm('cat')
const action = createActions(services)[FETCH_MEDIA_ITEM]
action(context, params)
}
diff --git a/test/unit/specs/store/search-store.spec.js b/test/unit/specs/store/search-store.spec.js
deleted file mode 100644
index 738324463..000000000
--- a/test/unit/specs/store/search-store.spec.js
+++ /dev/null
@@ -1,148 +0,0 @@
-import { createPinia, setActivePinia } from 'pinia'
-
-import store from '~/store/search'
-
-import {
- CLEAR_FILTERS,
- SET_SEARCH_STATE_FROM_URL,
- UPDATE_QUERY_FROM_FILTERS,
-} from '~/constants/action-types'
-import { SET_SEARCH_TYPE, SET_QUERY } from '~/constants/mutation-types'
-import { ALL_MEDIA, AUDIO, IMAGE } from '~/constants/media'
-
-import { useFilterStore } from '~/stores/filter'
-
-const initialState = {
- query: {
- aspect_ratio: '',
- categories: '',
- duration: '',
- extension: '',
- license: '',
- license_type: '',
- mature: '',
- q: '',
- searchBy: '',
- size: '',
- source: '',
- },
- searchType: ALL_MEDIA,
-}
-
-describe('Search Store', () => {
- describe('state', () => {
- it('initial state is set correctly', () => {
- const defaultState = store.state()
- expect(defaultState).toEqual(initialState)
- })
- })
-
- describe('mutations', () => {
- let state = null
- let mutations = null
-
- beforeEach(() => {
- setActivePinia(createPinia())
-
- state = {
- search: {
- searchType: 'image',
- query: { q: 'foo' },
- },
- ...store.state(),
- }
- mutations = store.mutations
- })
-
- it('SET_QUERY updates state', () => {
- const params = { query: { q: 'foo' } }
- mutations[SET_QUERY](state, params)
-
- expect(state.query.q).toBe(params.query.q)
- })
-
- it('SET_SEARCH_TYPE updates the state', () => {
- state.searchType = IMAGE
- mutations[SET_SEARCH_TYPE](state, { searchType: AUDIO })
- expect(state.searchType).toEqual(AUDIO)
- })
- })
-
- describe('actions', () => {
- 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: commitMock,
- dispatch: dispatchMock,
- rootState: {},
- state: state,
- }
- })
-
- it.each`
- searchType | path
- ${'all'} | ${'/search/'}
- ${'image'} | ${'/search/image/'}
- ${'audio'} | ${'/search/audio/'}
- ${'video'} | ${'/search/video'}
- `(
- "SET_SEARCH_STATE_FROM_URL should set searchType '$searchType' 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,
- })
- }
- )
-
- it.each`
- query | path | searchType
- ${{ license: 'cc0,by' }} | ${'/search/'} | ${ALL_MEDIA}
- ${{ searchBy: 'creator' }} | ${'/search/image/'} | ${IMAGE}
- ${{ mature: 'true' }} | ${'/search/audio/'} | ${AUDIO}
- ${{ durations: 'medium' }} | ${'/search/image'} | ${IMAGE}
- `(
- "SET_SEARCH_STATE_FROM_URL should set '$searchType' from query '$path'",
- ({ query, path, searchType }) => {
- actions[SET_SEARCH_STATE_FROM_URL](
- { commit: commitMock, dispatch: dispatchMock, state },
- { path: path, query: query }
- )
- expect(dispatchMock).toHaveBeenCalledWith(UPDATE_QUERY_FROM_FILTERS, {})
- expect(context.commit).toHaveBeenLastCalledWith(SET_SEARCH_TYPE, {
- searchType,
- })
- }
- )
-
- it('CLEAR_FILTERS resets filters to initial state', async () => {
- const filterStore = useFilterStore()
- filterStore.toggleFilter({ filterType: 'licenses', code: 'by' })
- filterStore.toggleFilter({ filterType: 'licenses', code: 'by-nc' })
- filterStore.toggleFilter({ filterType: 'licenses', code: 'by-nd' })
- actions[CLEAR_FILTERS]({
- commit: commitMock,
- dispatch: dispatchMock,
- state,
- })
- expect(dispatchMock).toHaveBeenCalledWith(UPDATE_QUERY_FROM_FILTERS, {
- q: '',
- })
- })
- })
-})
diff --git a/test/unit/specs/stores/search-store.spec.js b/test/unit/specs/stores/search-store.spec.js
new file mode 100644
index 000000000..c3d01466b
--- /dev/null
+++ b/test/unit/specs/stores/search-store.spec.js
@@ -0,0 +1,460 @@
+import { setActivePinia, createPinia } from 'pinia'
+
+import { nextTick } from '@nuxtjs/composition-api'
+
+import { filterData, mediaFilterKeys } from '~/constants/filters'
+import {
+ ALL_MEDIA,
+ AUDIO,
+ IMAGE,
+ supportedSearchTypes,
+ VIDEO,
+} from '~/constants/media'
+
+import { useSearchStore } from '~/stores/search'
+
+describe('Search Store', () => {
+ beforeEach(() => {
+ setActivePinia(createPinia())
+ })
+ describe('state', () => {
+ it('sets initial filters to filterData', () => {
+ const searchStore = useSearchStore()
+ expect(searchStore.filters).toEqual(filterData)
+ })
+ })
+ describe('getters', () => {
+ /**
+ * Check for some special cases:
+ * - `mature` and `searchBy`.
+ * - several options for single filter.
+ * - media specific filters that are unique (durations).
+ * - media specific filters that have the same API param (extensions)
+ */
+ it.each`
+ query | searchType | filterCount
+ ${{ licenses: ['by'], mature: ['mature'] }} | ${IMAGE} | ${1}
+ ${{ licenses: ['by'], searchBy: ['creator'] }} | ${ALL_MEDIA} | ${2}
+ ${{ licenses: ['cc0', 'pdm', 'by', 'by-nc'] }} | ${ALL_MEDIA} | ${4}
+ ${{ durations: ['medium'] }} | ${AUDIO} | ${1}
+ ${{ imageExtensions: ['svg'] }} | ${IMAGE} | ${1}
+ ${{ audioExtensions: ['mp3'] }} | ${AUDIO} | ${1}
+ `(
+ 'returns correct filter status for $query and searchType $searchType',
+ ({ query, searchType, filterCount }) => {
+ const searchStore = useSearchStore()
+ searchStore.setSearchType(searchType)
+ for (let [filterType, values] of Object.entries(query)) {
+ values.forEach((val) =>
+ searchStore.toggleFilter({ filterType, code: val })
+ )
+ }
+
+ expect(searchStore.appliedFilterCount).toEqual(filterCount)
+ expect(searchStore.isAnyFilterApplied).toBe(filterCount > 0)
+ }
+ )
+ })
+ describe('getters', () => {
+ /**
+ * For non-supported search types, the filters fall back to 'All content' filters.
+ * Number of displayed filters is one less than the number of mediaFilterKeys
+ * because `mature` filter is not displayed.
+ */
+ it.each`
+ searchType | filterTypeCount
+ ${IMAGE} | ${mediaFilterKeys[IMAGE].length}
+ ${AUDIO} | ${mediaFilterKeys[AUDIO].length}
+ ${ALL_MEDIA} | ${mediaFilterKeys[ALL_MEDIA].length}
+ ${VIDEO} | ${mediaFilterKeys[VIDEO].length}
+ `(
+ 'mediaFiltersForDisplay returns $filterTypeCount filters for $searchType',
+ ({ searchType, filterTypeCount }) => {
+ const searchStore = useSearchStore()
+ searchStore.setSearchType(searchType)
+ const filtersForDisplay = searchStore.searchFilters
+ const expectedFilterCount = Math.max(0, filterTypeCount - 1)
+ expect(Object.keys(filtersForDisplay).length).toEqual(
+ expectedFilterCount
+ )
+ }
+ )
+ /**
+ * Check for some special cases:
+ * - `mature` and `searchBy`.
+ * - several options for single filter.
+ * - media specific filters that are unique (durations).
+ * - media specific filters that have the same API param (extensions)
+ * - no 'q' parameter in the query.
+ */
+ it.each`
+ query | searchType
+ ${{ q: 'cat', license: 'by', mature: 'true' }} | ${IMAGE}
+ ${{ license: 'by', mature: 'true' }} | ${IMAGE}
+ ${{ license: '', mature: '' }} | ${IMAGE}
+ ${{ q: 'cat', license: 'by', searchBy: 'creator' }} | ${ALL_MEDIA}
+ ${{ q: 'cat', license: 'pdm,cc0,by,by-nc' }} | ${ALL_MEDIA}
+ ${{ q: 'cat', duration: 'medium' }} | ${AUDIO}
+ ${{ q: 'cat', extension: 'svg' }} | ${IMAGE}
+ ${{ q: 'cat', extension: 'svg' }} | ${AUDIO}
+ ${{ q: 'cat', extension: 'mp3' }} | ${AUDIO}
+ `(
+ 'returns correct searchQueryParams and filter status for $query and searchType $searchType',
+ ({ query, searchType }) => {
+ const searchStore = useSearchStore()
+ const expectedQueryParams = query
+ // It should discard the values that are not applicable for the search type:
+ if (searchType === AUDIO && query.extension === 'svg') {
+ delete expectedQueryParams.extension
+ }
+ searchStore.setSearchStateFromUrl({
+ path: `/search/${searchType === ALL_MEDIA ? '' : searchType}`,
+ urlQuery: { ...expectedQueryParams },
+ })
+ // Edge-case: query parameter value is a blank string
+ for (let param in expectedQueryParams) {
+ if (expectedQueryParams[param] === '')
+ delete expectedQueryParams[param]
+ }
+ // Should add a blank string as `q` value if `q` is not in query
+ if (!('q' in expectedQueryParams)) {
+ expectedQueryParams.q = ''
+ }
+ expect(searchStore.searchQueryParams).toEqual(expectedQueryParams)
+ }
+ )
+ })
+ describe('actions', () => {
+ it.each(['foo', ''])(
+ '`setSearchTerm correctly updates the searchTerm',
+ (searchTerm) => {
+ const searchStore = useSearchStore()
+ const expectedSearchTerm = searchTerm
+ searchStore.setSearchTerm(searchTerm)
+ expect(searchStore.searchTerm).toEqual(expectedSearchTerm)
+ }
+ )
+ it.each(supportedSearchTypes)(
+ 'setSearchType correctly updates the searchType',
+ (type) => {
+ const searchStore = useSearchStore()
+ searchStore.setSearchType(type)
+
+ expect(searchStore.searchType).toEqual(type)
+ }
+ )
+
+ // TODO: add support for video path
+ it.each`
+ searchType | path
+ ${'all'} | ${'/search/'}
+ ${'image'} | ${'/search/image/'}
+ ${'audio'} | ${'/search/audio/'}
+ ${'video'} | ${'/search/video'}
+ `(
+ "`setSearchStateFromUrl` should set searchType '$searchType' from path '$path'",
+ ({ searchType, path }) => {
+ const searchStore = useSearchStore()
+ searchStore.setSearchStateFromUrl({ path: path, urlQuery: {} })
+
+ expect(searchStore.searchType).toEqual(searchType)
+ }
+ )
+
+ it.each`
+ query | path | searchType
+ ${{ license: 'cc0,by', q: 'cat' }} | ${'/search/'} | ${ALL_MEDIA}
+ ${{ searchBy: 'creator', q: 'dog' }} | ${'/search/image/'} | ${IMAGE}
+ ${{ mature: 'true', q: 'galah' }} | ${'/search/audio/'} | ${AUDIO}
+ ${{ duration: 'medium' }} | ${'/search/image'} | ${IMAGE}
+ `(
+ "`setSearchStateFromUrl` should set '$searchType' from query $query and path '$path'",
+ ({ query, path, searchType }) => {
+ const searchStore = useSearchStore()
+ const expectedQuery = { ...searchStore.searchQueryParams, ...query }
+ // The values that are not applicable for the search type should be discarded
+ if (searchType === IMAGE) {
+ delete expectedQuery.duration
+ }
+
+ searchStore.setSearchStateFromUrl({ path: path, urlQuery: query })
+
+ expect(searchStore.searchType).toEqual(searchType)
+ expect(searchStore.searchQueryParams).toEqual(expectedQuery)
+ }
+ )
+
+ it.each`
+ filters | query
+ ${[['licenses', 'by'], ['licenses', 'by-nc-sa']]} | ${['license', 'by,by-nc-sa']}
+ ${[['licenseTypes', 'commercial'], ['licenseTypes', 'modification']]} | ${['license_type', 'commercial,modification']}
+ ${[['searchBy', 'creator']]} | ${['searchBy', 'creator']}
+ ${[['mature', 'mature']]} | ${['mature', 'true']}
+ ${[['sizes', 'large']]} | ${['size', undefined]}
+ `(
+ 'toggleFilter updates the query values to $query',
+ ({ filters, query }) => {
+ const searchStore = useSearchStore()
+ for (const filterItem of filters) {
+ const [filterType, code] = filterItem
+ searchStore.toggleFilter({ filterType, code })
+ }
+ expect(searchStore.searchQueryParams[query[0]]).toEqual(query[1])
+ }
+ )
+
+ it.each([ALL_MEDIA, IMAGE, AUDIO, VIDEO])(
+ 'Clears filters when search type is %s',
+ (searchType) => {
+ const searchStore = useSearchStore()
+ const expectedQueryParams = { q: 'cat' }
+ searchStore.setSearchStateFromUrl({
+ path: `/search/${searchType === ALL_MEDIA ? '' : searchType}`,
+ urlQuery: {
+ q: 'cat',
+ license: 'cc0',
+ sizes: 'large',
+ extension: 'jpg,mp3',
+ },
+ })
+ if (supportedSearchTypes.includes(searchType)) {
+ expect(searchStore.query).not.toEqual(expectedQueryParams)
+ }
+ searchStore.clearFilters()
+ expect(searchStore.searchQueryParams).toEqual(expectedQueryParams)
+ }
+ )
+ })
+ describe('actions', () => {
+ it.each`
+ filterType | codeIdx
+ ${'licenses'} | ${0}
+ ${'licenseTypes'} | ${0}
+ ${'imageExtensions'} | ${0}
+ ${'imageCategories'} | ${0}
+ ${'searchBy'} | ${0}
+ ${'aspectRatios'} | ${0}
+ ${'sizes'} | ${0}
+ ${'mature'} | ${0}
+ `(
+ 'toggleFilter updates $filterType filter state',
+ ({ filterType, codeIdx }) => {
+ const searchStore = useSearchStore()
+
+ searchStore.toggleFilter({ filterType, codeIdx })
+ const filterItem = searchStore.filters[filterType][codeIdx]
+ expect(filterItem.checked).toEqual(true)
+ }
+ )
+
+ it('toggleFilter updates isFilterApplied with provider', () => {
+ const searchStore = useSearchStore()
+ searchStore.setSearchType(IMAGE)
+ searchStore.initProviderFilters({
+ mediaType: IMAGE,
+ providers: [{ source_name: 'met', display_name: 'Met' }],
+ })
+
+ searchStore.toggleFilter({ filterType: 'imageProviders', code: 'met' })
+ expect(searchStore.appliedFilterCount).toEqual(1)
+ expect(searchStore.isAnyFilterApplied).toEqual(true)
+ })
+
+ it('toggleFilter updates isFilterApplied with license type', () => {
+ const searchStore = useSearchStore()
+ searchStore.toggleFilter({ filterType: 'licenseTypes', codeIdx: 0 })
+
+ expect(searchStore.isAnyFilterApplied).toEqual(true)
+ })
+
+ it('initProviderFilters merges with existing provider filters', () => {
+ const searchStore = useSearchStore()
+ const existingProviderFilters = [{ code: 'met', checked: true }]
+
+ searchStore.$patch({
+ filters: { imageProviders: existingProviderFilters },
+ })
+ const providers = [
+ { source_name: 'met', display_name: 'Metropolitan' },
+ { source_name: 'flickr', display_name: 'Flickr' },
+ ]
+
+ searchStore.initProviderFilters({
+ mediaType: 'image',
+ providers: providers,
+ })
+
+ expect(searchStore.filters.imageProviders).toEqual([
+ { code: 'met', name: 'Metropolitan', checked: true },
+ { code: 'flickr', name: 'Flickr', checked: false },
+ ])
+ })
+
+ it('clearFilters resets filters to initial state', () => {
+ const searchStore = useSearchStore()
+ searchStore.toggleFilter({ filterType: 'licenses', code: 'by' })
+ searchStore.toggleFilter({ filterType: 'licenses', code: 'by-nc' })
+ searchStore.toggleFilter({ filterType: 'licenses', code: 'by-nd' })
+
+ searchStore.clearFilters()
+ expect(searchStore.filters).toEqual(filterData)
+ })
+
+ it('clearFilters sets providers filters checked to false', () => {
+ const searchStore = useSearchStore()
+ searchStore.filters.imageProviders = [
+ { code: 'met', name: 'Metropolitan', checked: true },
+ { code: 'flickr', name: 'Flickr', checked: false },
+ ]
+
+ searchStore.clearFilters()
+ const expectedFilters = {
+ ...searchStore.filters,
+ imageProviders: [
+ { code: 'met', name: 'Metropolitan', checked: false },
+ { code: 'flickr', name: 'Flickr', checked: false },
+ ],
+ }
+ expect(searchStore.filters).toEqual(expectedFilters)
+ })
+
+ it.each`
+ filterType | code | idx
+ ${'licenses'} | ${'cc0'} | ${1}
+ ${'licenseTypes'} | ${'modification'} | ${1}
+ ${'imageExtensions'} | ${'svg'} | ${3}
+ ${'imageCategories'} | ${'photograph'} | ${0}
+ ${'searchBy'} | ${'creator'} | ${0}
+ ${'mature'} | ${'mature'} | ${-0}
+ ${'aspectRatios'} | ${'tall'} | ${0}
+ ${'sizes'} | ${'medium'} | ${1}
+ `(
+ "toggleFilter should set filter '$code' of type '$filterType",
+ ({ filterType, code, idx }) => {
+ const searchStore = useSearchStore()
+ searchStore.toggleFilter({ filterType: filterType, code: code })
+
+ const filterItem = searchStore.filters[filterType][idx]
+
+ expect(filterItem.checked).toEqual(true)
+ }
+ )
+ it.each`
+ item | dependency | disabled
+ ${{ code: 'by-nc', filterType: 'licenses' }} | ${{ filterType: 'licenseTypes', code: 'commercial' }} | ${true}
+ ${{ code: 'by-nc-nd', filterType: 'licenses' }} | ${{ filterType: 'licenseTypes', code: 'commercial' }} | ${true}
+ ${{ code: 'by-nc-sa', filterType: 'licenses' }} | ${{ filterType: 'licenseTypes', code: 'commercial' }} | ${true}
+ ${{ code: 'by-nd', filterType: 'licenses' }} | ${{ filterType: 'licenseTypes', code: 'modification' }} | ${true}
+ ${{ code: 'by-nc-nd', filterType: 'licenses' }} | ${{ filterType: 'licenseTypes', code: 'modification' }} | ${true}
+ ${{ code: 'by-nc', filterType: 'licenses' }} | ${{ filterType: 'licenseTypes', code: 'modification' }} | ${false}
+ ${{ code: 'by-nd', filterType: 'licenses' }} | ${{ filterType: 'licenseTypes', code: 'commercial' }} | ${false}
+ ${{ code: 'commercial', filterType: 'licenseTypes' }} | ${{ filterType: 'licenses', code: 'by-nc' }} | ${true}
+ ${{ code: 'commercial', filterType: 'licenseTypes' }} | ${{ filterType: 'licenses', code: 'by-nc-nd' }} | ${true}
+ ${{ code: 'commercial', filterType: 'licenseTypes' }} | ${{ filterType: 'licenses', code: 'by-nc-sa' }} | ${true}
+ ${{ code: 'modification', filterType: 'licenseTypes' }} | ${{ filterType: 'licenses', code: 'by-nd' }} | ${true}
+ ${{ code: 'modification', filterType: 'licenseTypes' }} | ${{ filterType: 'licenses', code: 'by-nc-nd' }} | ${true}
+ `(
+ 'isFilterDisabled for $item.code should return $disabled when $dependency.code is checked',
+ ({ item, dependency, disabled }) => {
+ const searchStore = useSearchStore()
+ searchStore.toggleFilter({
+ filterType: dependency.filterType,
+ code: dependency.code,
+ })
+ const isDisabled = searchStore.isFilterDisabled(item, item.filterType)
+ expect(isDisabled).toBe(disabled)
+ }
+ )
+
+ it('toggleFilter without code or codeIdx parameters warns about it', () => {
+ const searchStore = useSearchStore()
+ const expectedFilters = searchStore.filters
+
+ expect(() =>
+ searchStore.toggleFilter({ filterType: 'licenses' })
+ ).toThrow(
+ 'Cannot toggle filter of type licenses. Use code or codeIdx parameter'
+ )
+
+ expect(searchStore.filters).toEqual(expectedFilters)
+ })
+
+ it.each`
+ searchType | nextSearchType | expectedFilterCount
+ ${AUDIO} | ${IMAGE} | ${25}
+ ${IMAGE} | ${ALL_MEDIA} | ${34}
+ ${ALL_MEDIA} | ${VIDEO} | ${12}
+ ${VIDEO} | ${AUDIO} | ${21}
+ ${ALL_MEDIA} | ${IMAGE} | ${25}
+ `(
+ 'changing searchType clears all but $expectedFilterCount $nextSearchType filters ',
+ async ({ searchType, nextSearchType, expectedFilterCount }) => {
+ const searchStore = useSearchStore()
+ searchStore.setSearchType(searchType)
+ // Set all filters to checked
+ for (let ft in searchStore.filters) {
+ for (let f of searchStore.filters[ft]) {
+ searchStore.toggleFilter({ filterType: ft, code: f.code })
+ }
+ }
+ searchStore.setSearchType(nextSearchType)
+ await nextTick()
+
+ const checkedFilterCount = Object.keys(searchStore.filters)
+ .map(
+ (key) => searchStore.filters[key].filter((f) => f.checked).length
+ )
+ .reduce((partialSum, count) => partialSum + count, 0)
+ expect(checkedFilterCount).toEqual(expectedFilterCount)
+ }
+ )
+
+ /**
+ * Changing the search type to ALL_MEDIA does not fire the watcher that clears the filters
+ * in tests, but does fire it in the app. TODO: Figure out why???
+ */
+ it.each`
+ searchType | nextSearchType | expectedFilterCount
+ ${AUDIO} | ${ALL_MEDIA} | ${34}
+ ${IMAGE} | ${ALL_MEDIA} | ${34}
+ ${ALL_MEDIA} | ${ALL_MEDIA} | ${34}
+ ${VIDEO} | ${ALL_MEDIA} | ${34}
+ `(
+ 'changing searchType clears all but $expectedFilterCount ALL_MEDIA filters',
+ async ({ searchType, nextSearchType, expectedFilterCount }) => {
+ const searchStore = useSearchStore()
+ searchStore.setSearchType(searchType)
+ // Set all filters to checked
+ for (let [fc, filter_items] of Object.entries(searchStore.filters)) {
+ for (let f of filter_items) {
+ searchStore.toggleFilter({ filterType: fc, code: f.code })
+ }
+ }
+ searchStore.setSearchType(nextSearchType)
+ const checkedFilterCount = Object.keys(searchStore.filters)
+ .map(
+ (key) => searchStore.filters[key].filter((f) => f.checked).length
+ )
+ .reduce((partialSum, count) => partialSum + count, 0)
+
+ expect(checkedFilterCount).toEqual(expectedFilterCount)
+ }
+ )
+
+ it('Does not set filter or count filter as applied, and does not raise error for unsupported search types', () => {
+ const searchStore = useSearchStore()
+ searchStore.toggleFilter({
+ filterType: 'licenseTypes',
+ code: 'commercial',
+ })
+ expect(searchStore.isAnyFilterApplied).toEqual(true)
+
+ searchStore.setSearchType(VIDEO)
+ searchStore.toggleFilter({
+ filterType: 'licenseTypes',
+ code: 'commercial',
+ })
+ expect(searchStore.isAnyFilterApplied).toEqual(false)
+ })
+ })
+})
diff --git a/test/unit/specs/utils/search-query-transform.spec.js b/test/unit/specs/utils/search-query-transform.spec.js
index c27e529ba..6d3486eb4 100644
--- a/test/unit/specs/utils/search-query-transform.spec.js
+++ b/test/unit/specs/utils/search-query-transform.spec.js
@@ -7,7 +7,7 @@ import {
} from '~/utils/search-query-transform'
import { AUDIO, IMAGE } from '~/constants/media'
-import { filterData } from '~/constants/filters'
+import { filterData, initFilters } from '~/constants/filters'
describe('searchQueryTransform', () => {
it('converts initial filters to query data', () => {
@@ -18,6 +18,11 @@ describe('searchQueryTransform', () => {
const result = filtersToQueryData(filters)
expect(result).toEqual({})
})
+ it('converts filter to query data', () => {
+ const filters = { ...filterData }
+ const result = filtersToQueryData(filters)
+ expect(result).toEqual({})
+ })
it('converts all filters to query data', () => {
const filters = {
licenses: [
@@ -265,6 +270,58 @@ describe('searchQueryTransform', () => {
})
expect(result).toEqual(filters) // toEqual checks for value equality
})
+
+ it('queryToFilterData discards all image filters when search type is audio', () => {
+ const filters = initFilters()
+ filters.audioProviders = [
+ { code: 'jamendo', checked: false },
+ { code: 'wikimedia_audio', checked: false },
+ ]
+ /**
+ * `categories` and `extension` parameter values will not be used because those
+ * codes (`photograph` and `svg`) only exist for the `imageCategories` and `imageExtensions`
+ * filter categories.
+ * `source` will only use the `wikimedia_audio` and `jamendo` parameters because they
+ * exist in `filters.audioProviders` list before. Other values either exist in
+ * `filters.imageProviders` list, or do not exist at all, so they are discarded.
+ * Valid filter items for categories that exist for all search types
+ * (`license`, `license_type`, `searchBy`, `mature`) are set to checked.
+ * Invalid filter items for valid categories (`nonexistent` in `license`)
+ * are discarded.
+ */
+ const query = {
+ q: 'cat',
+ license: 'cc0,nonexistent',
+ license_type: 'commercial',
+ categories: 'photograph',
+ extension: 'svg',
+ duration: 'medium',
+ source: 'animaldiversity,wikimedia,nonexistent,wikimedia_audio,jamendo',
+ searchBy: 'creator',
+ mature: 'true',
+ }
+ const expectedFilters = clonedeep(filters)
+ const setChecked = (code, filterCategory) => {
+ const idx = expectedFilters[filterCategory].findIndex(
+ (item) => item.code === code
+ )
+ expectedFilters[filterCategory][idx].checked = true
+ }
+ setChecked('cc0', 'licenses')
+ setChecked('commercial', 'licenseTypes')
+ setChecked('medium', 'durations')
+ setChecked('creator', 'searchBy')
+ setChecked('mature', 'mature')
+ setChecked('jamendo', 'audioProviders')
+ setChecked('wikimedia_audio', 'audioProviders')
+
+ const result = queryToFilterData({
+ query,
+ searchType: AUDIO,
+ defaultFilters: filters,
+ })
+ expect(result).toEqual(expectedFilters) // toEqual checks for value equality
+ })
it('queryStringToQueryData', () => {
const expectedQueryData = {
license: 'cc0',
diff --git a/tsconfig.json b/tsconfig.json
index bba68d185..25d0d7185 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -43,6 +43,7 @@
"src/composables/use-media-query.js",
"src/composables/window.js",
"src/constants/screens.js",
+ "src/constants/filters",
"src/data/api-service.js",
"src/utils/deep-freeze.js"
],