Skip to content

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

Convert search store to an options store (#1259)

Olga Bulatb9f3d996f274
diff --git a/src/pages/index.vue b/src/pages/index.vue
index 9f9868331..c1c1893c3 100644
--- a/src/pages/index.vue
+++ b/src/pages/index.vue
@@ -132,7 +132,7 @@
</template>
<script>
-import { ref, useContext, useRouter } from '@nuxtjs/composition-api'
+import { onMounted, ref, useContext, useRouter } from '@nuxtjs/composition-api'
import { ALL_MEDIA, supportedSearchTypes } from '~/constants/media'
import { isMinScreen } from '~/composables/use-media-query'
@@ -177,6 +177,13 @@ const HomePage = {
const mediaStore = useMediaStore()
const searchStore = useSearchStore()
+ /**
+ * Reset the search type, search term and filters when the user navigates [back] to the homepage.
+ */
+ onMounted(() => {
+ searchStore.$reset()
+ })
+
const featuredSearches = imageInfo.sets.map((setItem) => ({
...setItem,
images: setItem.images.map((imageItem) => ({
diff --git a/src/stores/search.ts b/src/stores/search.ts
index 042bfe7bd..3b3b736c1 100644
--- a/src/stores/search.ts
+++ b/src/stores/search.ts
@@ -1,11 +1,5 @@
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
@@ -17,6 +11,7 @@ import {
AUDIO,
IMAGE,
SupportedMediaType,
+ SupportedSearchType,
supportedSearchTypes,
} from '~/constants/media'
import {
@@ -32,308 +27,283 @@ import {
mediaFilterKeys,
mediaUniqueFilterKeys,
} from '~/constants/filters'
-import type { SupportedSearchType } from '~/constants/media'
import type { ApiQueryParams } 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))
+export interface SearchState {
+ searchType: SupportedSearchType
+ searchTerm: string
+ filters: Filters
+}
- // 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)
- })
+function computeQueryParams(
+ searchType: SupportedSearchType,
+ filters: Filters,
+ searchTerm: string
+) {
+ const query = { ...filtersToQueryData(filters, searchType) }
- const computeQueryParams = (
- searchType: SupportedSearchType,
- filters: Filters = state.filters
- ) => {
- const query = { ...filtersToQueryData(filters, searchType) }
-
- const queryKeys = Object.keys(query) as (keyof ApiQueryParams)[]
- return queryKeys.reduce(
- (obj, key: keyof ApiQueryParams) => {
- 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),
- }
- }
+ const queryKeys = Object.keys(query) as (keyof ApiQueryParams)[]
+ return queryKeys.reduce(
+ (obj, key) => {
+ if (key !== 'q' && query[key]?.length) {
+ obj[key] = query[key]
+ }
+ return obj
+ },
+ // Ensure that q filter always comes first
+ { q: searchTerm.trim() } as ApiQueryParams
+ )
+}
- /**
- * 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
+export const useSearchStore = defineStore('search', {
+ state: (): SearchState => ({
+ searchType: ALL_MEDIA,
+ searchTerm: '',
+ filters: clonedeep(filterData),
+ }),
+ getters: {
+ filterCategories(state) {
+ return Object.keys(state.filters) as FilterCategory[]
+ },
+ /**
+ * Returns the search query parameters for API request:
+ * drops all parameters with blank values.
+ */
+ searchQueryParams(state) {
+ return computeQueryParams(
+ state.searchType,
+ state.filters,
+ state.searchTerm
)
- }, 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,
- })
+ },
+ /**
+ * Returns the number of checked filters, excluding the `mature` filter.
+ */
+ appliedFilterCount(state) {
+ const filterKeys = mediaFilterKeys[state.searchType].filter(
+ (f) => f !== 'mature'
+ )
+ return filterKeys.reduce((count, filterCategory) => {
+ return (
+ count + state.filters[filterCategory].filter((f) => f.checked).length
)
- }
- })
- }
-
- /**
- * 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
+ }, 0)
+ },
+ /**
+ * Returns the object with filters for selected search type, with codes, names for i18n labels, and checked status.
+ */
+ searchFilters(state) {
+ return mediaFilterKeys[state.searchType]
+ .filter((filterKey) => filterKey !== 'mature')
+ .reduce((obj, filterKey) => {
+ obj[filterKey] = this.filters[filterKey]
+ return obj
+ }, {} as Filters)
+ },
+ /**
+ * True if any filter for selected search type except `mature` is checked.
+ */
+ isAnyFilterApplied() {
+ const filterEntries = Object.entries(this.searchFilters) as [
+ string,
+ FilterItem[]
+ ][]
+ return filterEntries.some(
+ ([filterKey, filterItems]) =>
+ filterKey !== 'mature' && filterItems.some((filter) => filter.checked)
)
- const checked =
- existingProviderFilterIdx >= 0
- ? currentProviders[existingProviderFilterIdx].checked
- : false
-
+ },
+ },
+ actions: {
+ setSearchType(type: SupportedSearchType) {
+ this.searchType = type
+ this.clearOtherMediaTypeFilters(type)
+ },
+ setSearchTerm(term: string) {
+ this.searchTerm = term.trim()
+ },
+ computeQueryParams(type: SupportedSearchType) {
+ return computeQueryParams(type, this.filters, this.searchTerm)
+ },
+ /**
+ * 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.
+ */
+ getBaseFiltersWithProviders() {
+ const resetProviders = (mediaType: SupportedMediaType): FilterItem[] => {
+ return this.filters[`${mediaType}Providers`].map((provider) => ({
+ ...provider,
+ checked: false,
+ }))
+ }
return {
- code: provider.source_name,
- name: provider.display_name,
- checked,
+ ...clonedeep(filterData),
+ audioProviders: resetProviders(AUDIO),
+ imageProviders: resetProviders(IMAGE),
}
- })
- }
- /**
- * 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
- }
+ },
+ /**
+ * 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.
+ */
+ initProviderFilters({
+ mediaType,
+ providers,
+ }: {
+ mediaType: SupportedMediaType
+ providers: { source_name: string; display_name: string }[]
+ }) {
+ const providersKey: FilterCategory = `${mediaType}Providers`
+ const currentProviders = this.filters[providersKey]
+ ? [...this.filters[providersKey]]
+ : []
+ this.filters[providersKey] = providers.map((provider) => {
+ const existingProviderFilterIdx = currentProviders.findIndex(
+ (p) => p.code === provider.source_name
+ )
+ const checked =
+ existingProviderFilterIdx >= 0
+ ? currentProviders[existingProviderFilterIdx].checked
+ : false
- /**
- * 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
+ return {
+ code: provider.source_name,
+ name: provider.display_name,
+ checked,
+ }
+ })
+ },
+ /**
+ * Toggles a filter's checked parameter. Requires either codeIdx or code.
+ */
+ 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 = this.filters[filterType]
+ const idx = codeIdx ?? filterItems.findIndex((f) => f.code === code)
+ this.filters[filterType][idx].checked = !filterItems[idx].checked
+ },
- /**
- * 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')
+ /**
+ * Resets all filters to initial values.
+ * Provider filters are not in the initial filters, so they need to be
+ * handled separately.
+ *
+ */
+ clearFilters() {
+ for (const filterCategory of this.filterCategories) {
+ for (const filterItem of this.filters[filterCategory]) {
+ filterItem.checked = false
+ }
}
- 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)
- }
+ /**
+ * After a search type is changed, unchecks all the filters that are not
+ * applicable for this Media type.
+ */
+ clearOtherMediaTypeFilters(searchType: SupportedSearchType) {
+ const mediaTypesToClear = supportedSearchTypes.filter(
+ (type) => type !== searchType
+ )
+ const filterKeysToClear = mediaTypesToClear.reduce((acc, type) => {
+ return [...acc, ...mediaUniqueFilterKeys[type]]
+ }, [] as FilterCategory[])
- return {
- searchTerm,
- searchType,
- filters,
+ this.filterCategories.forEach((filterCategory) => {
+ if (filterKeysToClear.includes(filterCategory)) {
+ this.filters[filterCategory] = this.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.
+ */
+ replaceFilters(newFilterData: Filters) {
+ this.filterCategories.forEach((filterCategory) => {
+ this.filters[filterCategory] = newFilterData[filterCategory]
+ })
+ },
+ /**
+ * Called when a /search path is server-rendered.
+ */
+ setSearchStateFromUrl({
+ path,
+ urlQuery,
+ }: {
+ path: string
+ urlQuery: Record<string, string>
+ }) {
+ if (urlQuery.q) {
+ this.setSearchTerm(urlQuery.q.trim())
+ }
+ this.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
+ }
- appliedFilterCount,
- isAnyFilterApplied,
- searchFilters,
- searchQueryParams,
+ const newFilterData = queryToFilterData({
+ query,
+ searchType: this.searchType,
+ defaultFilters: this.getBaseFiltersWithProviders(),
+ })
+ this.replaceFilters(newFilterData)
+ },
- setSearchTerm,
- setSearchType,
- setSearchStateFromUrl,
- initProviderFilters,
- isFilterDisabled,
- clearFilters,
- toggleFilter,
- computeQueryParams,
- }
+ /**
+ * 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.
+ */
+ 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 this.filters.licenses.some(
+ (item: FilterItem) => 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 this.filters.licenseTypes.some(
+ (item: FilterItem) =>
+ dependentFilters.includes(item.code) && item.checked
+ )
+ }
+ },
+ },
})
diff --git a/test/unit/specs/stores/search-store.spec.js b/test/unit/specs/stores/search-store.spec.js
index 46eb40529..27eebda86 100644
--- a/test/unit/specs/stores/search-store.spec.js
+++ b/test/unit/specs/stores/search-store.spec.js
@@ -382,7 +382,7 @@ describe('Search Store', () => {
it.each`
searchType | nextSearchType | expectedFilterCount
${AUDIO} | ${IMAGE} | ${25}
- ${IMAGE} | ${ALL_MEDIA} | ${37}
+ ${IMAGE} | ${ALL_MEDIA} | ${12}
${ALL_MEDIA} | ${VIDEO} | ${12}
${VIDEO} | ${AUDIO} | ${24}
${ALL_MEDIA} | ${IMAGE} | ${25}
@@ -409,38 +409,6 @@ describe('Search Store', () => {
}
)
- /**
- * 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} | ${37}
- ${IMAGE} | ${ALL_MEDIA} | ${37}
- ${ALL_MEDIA} | ${ALL_MEDIA} | ${37}
- ${VIDEO} | ${ALL_MEDIA} | ${37}
- `(
- '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({