Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Extract filter store from the search store and convert it to Pinia (#1039)
Olga Bulat64b9c0eb56b4
diff --git a/src/components/VFilters/VFilterChecklist.vue b/src/components/VFilters/VFilterChecklist.vueindex cd7311b59..09cf4f62f 100644--- a/src/components/VFilters/VFilterChecklist.vue+++ b/src/components/VFilters/VFilterChecklist.vue@@ -56,6 +56,8 @@</template><script>+import { useFilterStore } from '~/stores/filter'+import VLicenseExplanation from '~/components/VFilters/VLicenseExplanation.vue'import VCheckbox from '~/components/VCheckbox/VCheckbox.vue'import VLicense from '~/components/License/VLicense.vue'@@ -108,31 +110,11 @@ export default {filterType: this.filterType,})},- getFilterTypeValue(filterKey, val) {- return this.$store.state.search.filters[filterKey].filter((item) =>- item.code.includes(val)- )- },isDisabled(item) {- if (this.filterType === 'licenseTypes') {- const nc = this.getFilterTypeValue('licenses', 'nc')- const nd = this.getFilterTypeValue('licenses', 'nd')- return (- (item.code === 'commercial' && nc.some((li) => li.checked)) ||- (item.code === 'modification' && nd.some((li) => li.checked))- )- } else if (this.filterType === 'licenses') {- const commercial = this.getFilterTypeValue('licenseTypes', 'commercial')- const modification = this.getFilterTypeValue(- 'licenseTypes',- 'modification'- )- return (- (commercial[0].checked && item.code.includes('nc')) ||- (modification[0].checked && item.code.includes('nd'))- )- }- return this.disabled+ return (+ useFilterStore().isFilterDisabled(item, this.filterType) ??+ this.disabled+ )},},}diff --git a/src/components/VFilters/VSearchGridFilter.vue b/src/components/VFilters/VSearchGridFilter.vueindex a1957236f..bb47b8a0a 100644--- a/src/components/VFilters/VSearchGridFilter.vue+++ b/src/components/VFilters/VSearchGridFilter.vue@@ -46,6 +46,7 @@import { computed, useContext, useRouter } from '@nuxtjs/composition-api'import { kebab } from 'case'+import { useFilterStore } from '~/stores/filter'import {CLEAR_FILTERS,FETCH_MEDIA,@@ -61,14 +62,14 @@ export default {VFilterChecklist,},setup() {+ const filterStore = useFilterStore()const { i18n, store } = useContext()const router = useRouter()- const isAnyFilterApplied = computed(- () => store.getters[`${SEARCH}/isAnyFilterApplied`]- )+ const isAnyFilterApplied = computed(() => filterStore.isAnyFilterApplied)+const filters = computed(() => {- return store.getters[`${SEARCH}/mediaFiltersForDisplay`] || {}+ return store.getters[`${SEARCH}/searchFilters`]})const filterTypes = computed(() => Object.keys(filters.value))const filterTypeTitle = (filterType) => {diff --git a/src/components/VHeader/VFilterButton.vue b/src/components/VHeader/VFilterButton.vueindex 77a5e6ad1..452aefd06 100644--- a/src/components/VHeader/VFilterButton.vue+++ b/src/components/VHeader/VFilterButton.vue@@ -26,6 +26,8 @@ import {useContext,} from '@nuxtjs/composition-api'+import { useFilterStore } from '~/stores/filter'+import VButton from '~/components/VButton.vue'import VIcon from '~/components/VIcon/VIcon.vue'@@ -44,13 +46,12 @@ const VFilterButton = defineComponent({},},setup(props, { emit }) {- const { i18n, store } = useContext()+ const { i18n } = useContext()+ const filterStore = useFilterStore()const { pressed } = toRefs(props)const isMinScreenMd = inject('isMinScreenMd', false)const isHeaderScrolled = inject('isHeaderScrolled', false)- const filterCount = computed(- () => store.getters['search/appliedFilterTags'].length- )+ const filterCount = computed(() => filterStore.appliedFilterCount)const filtersAreApplied = computed(() => filterCount.value > 0)/**diff --git a/src/components/VLicenseElements.vue b/src/components/VLicenseElements.vueindex 5839cd028..185472a17 100644--- a/src/components/VLicenseElements.vue+++ b/src/components/VLicenseElements.vue@@ -23,6 +23,8 @@<script>import { computed, defineComponent } from '@nuxtjs/composition-api'+import VIcon from '~/components/VIcon/VIcon.vue'+import by from '~/assets/licenses/by.svg'import cc0 from '~/assets/licenses/cc0.svg'import nc from '~/assets/licenses/nc.svg'@@ -34,6 +36,7 @@ import samplingPlus from '~/assets/licenses/sampling-plus.svg'export default defineComponent({name: 'VLicenseElements',+ components: { VIcon },props: {license: {type: String,diff --git a/src/constants/mutation-types.js b/src/constants/mutation-types.jsindex 0f6263c78..775311e08 100644--- a/src/constants/mutation-types.js+++ b/src/constants/mutation-types.js@@ -5,13 +5,9 @@ export const SET_PROVIDER_FETCH_ERROR = 'SET_PROVIDER_FETCH_ERROR'export const FETCH_MEDIA_ERROR = 'FETCH_MEDIA_ERROR'export const MEDIA_NOT_FOUND = 'MEDIA_NOT_FOUND'export const FETCH_START_MEDIA = 'FETCH_START_MEDIA'-export const SET_FILTER = 'SET_FILTER'export const SET_MEDIA_ITEM = 'SET_MEDIA_ITEM'export const SET_MEDIA_PROVIDERS = 'SET_MEDIA_PROVIDERS'-export const SET_PROVIDERS_FILTERS = 'SET_PROVIDERS_FILTERS'export const SET_MEDIA = 'SET_MEDIA'export const SET_SEARCH_TYPE = 'SET_SEARCH_TYPE'-export const CLEAR_OTHER_MEDIA_TYPE_FILTERS = 'CLEAR_OTHER_MEDIA_TYPE_FILTERS'export const RESET_MEDIA = 'RESET_MEDIA'-export const REPLACE_FILTERS = 'REPLACE_FILTERS'export const SET_QUERY = 'SET_QUERY'diff --git a/src/locales/po-files/openverse.pot b/src/locales/po-files/openverse.potindex 5676dd6a0..bb89fdc61 100644--- a/src/locales/po-files/openverse.pot+++ b/src/locales/po-files/openverse.pot@@ -916,7 +916,7 @@ msgctxt "filters.license-explanation.more.read-more"msgid "Read more"msgstr ""-#: src/components/VFilters/VFilterChecklist.vue:95+#: src/components/VFilters/VFilterChecklist.vue:97msgctxt "filters.search-by.title"msgid "Search By"msgstr ""@@ -1848,7 +1848,7 @@ msgid "Filters"msgstr ""#. Do not translate words between ### ###.-#: src/components/VHeader/VFilterButton.vue:82+#: src/components/VHeader/VFilterButton.vue:83msgctxt "header.filter-button.with-count"msgid "###count### Filter"msgid_plural "###count### Filters"diff --git a/src/pages/search.vue b/src/pages/search.vueindex 6a89154e5..88f082b30 100644--- a/src/pages/search.vue+++ b/src/pages/search.vue@@ -36,7 +36,7 @@ import {UPDATE_QUERY,SET_SEARCH_STATE_FROM_URL,} from '~/constants/action-types'-import { ALL_MEDIA, supportedSearchTypes } from '~/constants/media'+import { supportedSearchTypes } from '~/constants/media'import { MEDIA, SEARCH } from '~/constants/store-modules'import { isMinScreen } from '~/composables/use-media-query.js'import { useFilterSidebarVisibility } from '~/composables/use-filter-sidebar-visibility'@@ -79,11 +79,8 @@ const BrowsePage = {},computed: {...mapState(SEARCH, ['query', 'searchType']),- ...mapGetters(SEARCH, ['searchQueryParams', 'isAnyFilterApplied']),+ ...mapGetters(SEARCH, ['searchQueryParams']),...mapGetters(MEDIA, ['results', 'resultCount', 'fetchState']),- mediaType() {- return this.searchType ?? ALL_MEDIA- },/*** Number of search results. Returns 0 for unsupported types.* @returns {number}diff --git a/src/store/provider.js b/src/store/provider.jsindex 56b6e3790..9e172a0ec 100644--- a/src/store/provider.js+++ b/src/store/provider.js@@ -1,5 +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 {@@ -11,9 +13,7 @@ import {FETCH_MEDIA_PROVIDERS_END,FETCH_MEDIA_PROVIDERS_START,SET_MEDIA_PROVIDERS,- SET_PROVIDERS_FILTERS,} from '~/constants/mutation-types'-import { SEARCH } from '~/constants/store-modules'import { warn } from '~/utils/console'const AudioProviderService = MediaProviderService(AUDIO)@@ -61,6 +61,7 @@ export const createActions = (services) => ({},[FETCH_MEDIA_TYPE_PROVIDERS]({ commit }, params) {const { mediaType } = params+ const filterStore = useFilterStore()commit(SET_PROVIDER_FETCH_ERROR, { mediaType, error: false })commit(FETCH_MEDIA_PROVIDERS_START, { mediaType })const providerService = services[mediaType]@@ -82,14 +83,10 @@ export const createActions = (services) => ({mediaType,providers: sortedProviders,})- commit(- `${SEARCH}/${SET_PROVIDERS_FILTERS}`,- {- mediaType,- providers: sortedProviders,- },- { root: true }- )+ filterStore.initProviderFilters({+ mediaType,+ providers: sortedProviders,+ })})},})diff --git a/src/store/search.js b/src/store/search.jsindex 1362c3f65..e63373619 100644--- a/src/store/search.js+++ b/src/store/search.js@@ -1,17 +1,8 @@-import findIndex from 'lodash.findindex'-import clonedeep from 'lodash.clonedeep'-import {filtersToQueryData,queryStringToSearchType,- queryToFilterData,} from '~/utils/search-query-transform'-import {- ALL_MEDIA,- AUDIO,- IMAGE,- supportedSearchTypes,-} from '~/constants/media'+import { ALL_MEDIA } from '~/constants/media'import {UPDATE_QUERY,SET_SEARCH_STATE_FROM_URL,@@ -19,52 +10,10 @@ import {UPDATE_QUERY_FROM_FILTERS,CLEAR_FILTERS,} from '~/constants/action-types'+import { SET_QUERY, SET_SEARCH_TYPE } from '~/constants/mutation-types'-import {- SET_FILTER,- SET_PROVIDERS_FILTERS,- CLEAR_OTHER_MEDIA_TYPE_FILTERS,- REPLACE_FILTERS,- SET_QUERY,- SET_SEARCH_TYPE,-} from '~/constants/mutation-types'--import {- filterData,- mediaFilterKeys,- mediaUniqueFilterKeys,-} from '~/constants/filters.ts'--/**- * Returns true if any of the filters' checked property is true- * except for `mature` filter, as it is not displayed as a tag- * @param filters- * @returns {boolean}- */-const anyFilterApplied = (filters = {}) =>- Object.keys(filters).some((filterKey) => {- if (filterKey === 'mature') {- return false- } // this is hardcoded to "false" because we do not show mature in `FilterDisplay.vue` like the other filters-- return (- filters[filterKey] && filters[filterKey].some((filter) => filter.checked)- )- })+import { useFilterStore } from '~/stores/filter'-const getBaseFiltersWithProviders = (state) => {- const resetProviders = (mediaType) => {- return state.filters[`${mediaType}Providers`].map((provider) => ({- ...provider,- checked: false,- }))- }- return {- ...clonedeep(filterData),- audioProviders: resetProviders(AUDIO),- imageProviders: resetProviders(IMAGE),- }-}/*** `query` has the API request parameters for search filtering. Locally, some filters* have different names, and some query parameters correspond to different filter parameters@@ -74,12 +23,11 @@ const getBaseFiltersWithProviders = (state) => {* @return {import('./types').SearchState}*/export const state = () => ({- filters: clonedeep(filterData),searchType: ALL_MEDIA,query: {q: '',- license: '',license_type: '',+ license: '',categories: '',extension: '',duration: '',@@ -115,60 +63,8 @@ export const getters = {}return params},- /**- * Returns all applied filters in unified format- * Mature filter is not returned because it is not displayed- * as a filter tag.- *- * @param {import('./types').SearchState} state- * @returns {{code: string, name: string, filterType: string}[]}- */- appliedFilterTags: (state) => {- let appliedFilters = []- const filterKeys = mediaFilterKeys[state.searchType]- filterKeys.forEach((filterType) => {- if (filterType !== 'mature') {- const newFilters = state.filters[filterType]- .filter((f) => f.checked)- .map((f) => {- return {- code: f.code,- name: f.name,- filterType: filterType,- }- })- appliedFilters = [...appliedFilters, ...newFilters]- }- })-- return appliedFilters- },- /**- * Returns true if any filter except `mature` is applied.- *- * @param {import('./types').SearchState} state- * @return {boolean}- */- isAnyFilterApplied: (state) => {- return anyFilterApplied(- getMediaTypeFilters({- filters: state.filters,- mediaType: state.searchType,- })- )- },- /**- * Returns the array of the filters applicable for current search type- * for display on the Filter sidebar.- * @param {import('./types').SearchState} state- * @return {{}}- */- mediaFiltersForDisplay: (state) => {- return getMediaTypeFilters({- filters: state.filters,- mediaType: state.searchType,- includeMature: false,- })+ searchFilters: (state) => {+ return useFilterStore().getMediaTypeFilters({ mediaType: state.searchType })},}@@ -190,7 +86,7 @@ const actions = {}if (searchType && searchType !== state.searchType) {commit(SET_SEARCH_TYPE, { searchType })- commit(CLEAR_OTHER_MEDIA_TYPE_FILTERS, { searchType })+ useFilterStore().clearOtherMediaTypeFilters({ searchType })}await dispatch(UPDATE_QUERY_FROM_FILTERS, queryParams)},@@ -199,12 +95,8 @@ const actions = {* @param {import('vuex').ActionContext} context* @param params*/- async [TOGGLE_FILTER]({ commit, dispatch, state }, params) {- const { filterType, code } = params- const filters = state.filters[filterType]- const codeIdx = findIndex(filters, (f) => f.code === code)-- commit(SET_FILTER, { codeIdx, ...params })+ async [TOGGLE_FILTER]({ dispatch }, params) {+ useFilterStore().toggleFilter(params)await dispatch(UPDATE_QUERY_FROM_FILTERS)},@@ -214,10 +106,8 @@ const actions = {* handled separately.* @param {import('vuex').ActionContext} context*/- async [CLEAR_FILTERS]({ commit, dispatch, state }) {- commit(REPLACE_FILTERS, {- newFilterData: getBaseFiltersWithProviders(state),- })+ async [CLEAR_FILTERS]({ dispatch }) {+ useFilterStore().clearFilters()await dispatch(UPDATE_QUERY_FROM_FILTERS, { q: '' })},@@ -227,22 +117,16 @@ const actions = {* @param {string} path* @param {Object} query*/- async [SET_SEARCH_STATE_FROM_URL](- { commit, dispatch, state },- { path, query }- ) {+ async [SET_SEARCH_STATE_FROM_URL]({ commit, dispatch }, { path, query }) {const searchType = queryStringToSearchType(path)const queryParams = {}if (query.q) {queryParams.q = query.q}- const newFilterData = queryToFilterData({- query,- searchType,- defaultFilters: getBaseFiltersWithProviders(state),- })- commit(REPLACE_FILTERS, { newFilterData })+commit(SET_SEARCH_TYPE, { searchType })+ useFilterStore().updateFiltersFromUrl(query, searchType)+await dispatch(UPDATE_QUERY_FROM_FILTERS, queryParams)},/**@@ -254,121 +138,29 @@ const actions = {*/async [UPDATE_QUERY_FROM_FILTERS]({ state, commit }, params = {}) {const queryFromFilters = filtersToQueryData(- state.filters,+ useFilterStore().filters,params.mediaType || state.searchType,- false+ true)- const query = { ...queryFromFilters }- query.q = params?.q || state.query.q- commit(SET_QUERY, { query })- },-}-function getMediaTypeFilters({ filters, mediaType, includeMature = false }) {- if (!supportedSearchTypes.includes(mediaType)) {- mediaType = ALL_MEDIA- }- let filterKeys = mediaFilterKeys[mediaType]- if (!includeMature) {- filterKeys = filterKeys.filter((filterKey) => filterKey !== 'mature')- }- const mediaTypeFilters = {}- filterKeys.forEach((filterKey) => {- mediaTypeFilters[filterKey] = filters[filterKey]- })- return mediaTypeFilters-}--const mutations = {- /**- * After a search type is changed, unchecks all the filters that are not- * applicable for this Media type.- * @param {import('./types').SearchState} state- * @param {import('./types').SearchType} searchType- */- [CLEAR_OTHER_MEDIA_TYPE_FILTERS](state, { searchType }) {- const mediaTypesToClear = supportedSearchTypes.filter(- (type) => type !== searchType+ // 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+ }, {}))-- let filterKeysToClear = []- mediaTypesToClear.forEach((mediaType) => {- const filterKeys = mediaUniqueFilterKeys[mediaType]- filterKeysToClear = [...filterKeysToClear, ...filterKeys]- })-- Object.keys(state.filters).forEach((filterType) => {- if (filterKeysToClear.includes(filterType)) {- state.filters[filterType] = state.filters[filterType].map((f) => ({- ...f,- checked: false,- }))- }- })+ commit(SET_QUERY, { query: updatedQuery })},- /**- * Replaces filters with the newFilterData parameter, making sure that- * audio/image provider filters are handled correctly.- *- * @param {import('./types').SearchState} state- * @param {import('./types').Filters} newFilterData- */- [REPLACE_FILTERS](state, { newFilterData }) {- Object.keys(state.filters).forEach((filterType) => {- if (filterType === 'mature') {- state.filters.mature = newFilterData.mature- } else if (['audioProviders', 'imageProviders'].includes(filterType)) {- newFilterData[filterType].forEach((provider) => {- const idx = state.filters[filterType].findIndex(- (p) => p.code === provider.code- )- if (idx > -1) {- state.filters[filterType][idx].checked = provider.checked- }- })- } else {- state.filters[filterType] = newFilterData[filterType]- }- })- },- /**- * Toggles the filter's checked value.- *- * @param {import('./types').SearchState} state- * @param {import('vuex').MutationPayload} params- * @param {string} params.filterType- * @param {number} params.codeIdx- */- [SET_FILTER](state, params) {- const { filterType, codeIdx } = params- const filters = state.filters[filterType]- filters[codeIdx].checked = !filters[codeIdx].checked- },- [SET_PROVIDERS_FILTERS](state, params) {- const { mediaType, providers } = params- // merge providers from API response with the filters that came from the- // browse URL search query string and match the checked properties- // in the store- const providersKey = `${mediaType}Providers`- const currentProviders = [...state.filters[providersKey]]- state.filters[providersKey] = providers.map((provider) => {- const existingProviderFilterIdx = findIndex(- currentProviders,- (p) => p.code === provider.source_name- )-- const checked =- existingProviderFilterIdx >= 0- ? currentProviders[existingProviderFilterIdx].checked- : false+}- return {- code: provider.source_name,- name: provider.display_name,- checked,- }- })- },+const mutations = {/*** Sets the content type to search.* @param {import('./types').SearchState} state@@ -376,6 +168,7 @@ const mutations = {*/[SET_SEARCH_TYPE](state, { searchType }) {state.searchType = searchType+ useFilterStore().setSearchType(searchType)},/*** Replaces the query object that is used for API calls.diff --git a/src/store/types.ts b/src/store/types.tsindex 405d75b2d..f3ed7e577 100644--- a/src/store/types.ts+++ b/src/store/types.ts@@ -36,10 +36,9 @@ export interface MediaResult<}export type Query = {- mediaType: SupportedMediaTypeq: string- license: stringlicense_type: string+ license: stringextension: stringsize: stringaspect_ratio: string@@ -141,7 +140,6 @@ export interface FetchState {export interface SearchState {searchType: SupportedSearchTypequery: Query- filters: Filters}export interface ActiveMediaState {diff --git a/src/stores/filter.js b/src/stores/filter.jsnew file mode 100644index 000000000..b08bc74a1--- /dev/null+++ b/src/stores/filter.js@@ -0,0 +1,280 @@+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('../store/types').SearchType} */ (+ ref(ALL_MEDIA)+ )++ /**+ * @param {import('../store/types').SearchType} type+ */+ const setSearchType = (type) => (searchType.value = type)+ /**+ *+ * @param {{ mediaType: import('../store/types').SearchType, includeMature?: boolean }} params+ * @returns {Partial<import('../store/types').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('../store/types').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/test/e2e/filters.spec.js b/test/e2e/filters.spec.jsindex 446f69368..ede60affd 100644--- a/test/e2e/filters.spec.js+++ b/test/e2e/filters.spec.js@@ -1,16 +1,69 @@const { test, expect } = require('@playwright/test')const {- assertCheckboxCheckedStatus,+ assertCheckboxStatus,openFilters,mockProviderApis,changeContentType,} = require('./utils')+// Cannot require media constants because they use `export`+const ALL_MEDIA = 'all'+const AUDIO = 'audio'+const IMAGE = 'image'+const supportedSearchTypes = [ALL_MEDIA, AUDIO, IMAGE]+test.beforeEach(async ({ context }) => {await mockProviderApis(context)})+/**+ * @param page+ * @param {'checked'|'notChecked'|'total'} checked+ * @param {number} count+ * @returns {Promise<void>}+ */+const assertCheckboxCount = async (page, checked, count) => {+ let checkedString = {+ checked: ':checked',+ notChecked: ':not(:checked)',+ total: '',+ }[checked]+ const locatorString = `input[type="checkbox"]${checkedString}`+ await expect(page.locator(locatorString)).toHaveCount(count, { timeout: 200 })+}++const FILTER_COUNTS = {+ [ALL_MEDIA]: 11,+ [AUDIO]: 23,+ [IMAGE]: 70,+}++for (const searchType of supportedSearchTypes) {+ test(`correct total number of filters is displayed for ${searchType}`, async ({+ page,+ }) => {+ const searchTypePath = searchType === ALL_MEDIA ? '' : searchType+ const searchUrl = `/search/${searchTypePath}/?q=cat`+ await page.goto(searchUrl)++ await openFilters(page)++ await assertCheckboxCount(page, 'total', FILTER_COUNTS[searchType])+ })+}++test('initial filters are applied based on the url', async ({ page }) => {+ await page.goto(+ '/search/?q=cat&license_type=commercial&license=cc0&searchBy=creator'+ )+ await openFilters(page)+ const expectedFilters = ['cc0', 'commercial', 'creator']++ for (let checkbox of expectedFilters) {+ await assertCheckboxStatus(page, checkbox)+ }+})test('common filters are retained when media type changes from all media to single type', async ({page,}) => {@@ -18,18 +71,15 @@ test('common filters are retained when media type changes from all media to sing'/search/?q=cat&license_type=commercial&license=cc0&searchBy=creator')await openFilters(page)+ const expectedFilters = ['cc0', 'commercial', 'creator']- for (let checkbox of ['cc0', 'commercial', 'creator']) {- await assertCheckboxCheckedStatus(page, checkbox)- }await changeContentType(page, 'Images')await expect(page).toHaveURL('/search/image?q=cat&license_type=commercial&license=cc0&searchBy=creator')-- for (let checkbox of ['cc0', 'commercial', 'creator']) {- await assertCheckboxCheckedStatus(page, checkbox)+ for (let checkbox of expectedFilters) {+ await assertCheckboxStatus(page, checkbox)}})@@ -42,7 +92,7 @@ test('common filters are retained when media type changes from single type to alawait openFilters(page)for (let checkbox of ['cc0', 'commercial', 'creator']) {- await assertCheckboxCheckedStatus(page, checkbox)+ await assertCheckboxStatus(page, checkbox)}await changeContentType(page, 'All content')@@ -52,15 +102,39 @@ test('common filters are retained when media type changes from single type to al)for (let checkbox of ['cc0', 'commercial', 'creator']) {- await assertCheckboxCheckedStatus(page, checkbox)+ await assertCheckboxStatus(page, checkbox)}})++test('selecting some filters can disable dependent filters', async ({+ page,+}) => {+ await page.goto('/search/audio?q=cat&license_type=commercial')+ await openFilters(page)++ // by-nc is special because we normally test for fuzzy match, and by-nc matches 3 labels.+ const byNc = page.locator('input[value="by-nc"]')+ await expect(byNc).toBeDisabled()+ for (let checkbox of ['by-nc-sa', 'by-nc-nd']) {+ await assertCheckboxStatus(page, checkbox, 'disabled')+ }+ await assertCheckboxStatus(page, 'commercial')++ await page.click('label:has-text("commercial")')++ await assertCheckboxStatus(page, 'commercial', 'unchecked')+ await expect(byNc).not.toBeDisabled()+ for (let checkbox of ['commercial', 'by-nc-sa', 'by-nc-nd']) {+ await assertCheckboxStatus(page, checkbox, 'unchecked')+ }+})+test('filters are updated when media type changes', async ({ page }) => {await page.goto('/search/image?q=cat&aspect_ratio=tall&license=cc0')await openFilters(page)- await assertCheckboxCheckedStatus(page, 'Tall')- await assertCheckboxCheckedStatus(page, 'cc0')+ await assertCheckboxStatus(page, 'tall')+ await assertCheckboxStatus(page, 'cc0')await changeContentType(page, 'Audio')@@ -69,7 +143,7 @@ test('filters are updated when media type changes', async ({ page }) => {await expect(page.locator('label:has-text("Tall")')).toHaveCount(0, {timeout: 300,})- await assertCheckboxCheckedStatus(page, 'cc0')+ await assertCheckboxStatus(page, 'cc0')})test('new media request is sent when a filter is selected', async ({@@ -77,15 +151,17 @@ test('new media request is sent when a filter is selected', async ({}) => {await page.goto('/search/image?q=cat')await openFilters(page)- await assertCheckboxCheckedStatus(page, 'cc0', false)++ await assertCheckboxStatus(page, 'cc0', 'unchecked')+const [response] = await Promise.all([page.waitForResponse((response) => response.url().includes('cc0')),page.click('label:has-text("CC0")'),])++ await assertCheckboxStatus(page, 'cc0')// Remove the host url and path because when proxied, the 'http://localhost:49152' is used instead of the// real API urlconst queryString = response.url().split('/images/')[1]expect(queryString).toEqual('?q=cat&license=cc0')- await assertCheckboxCheckedStatus(page, 'cc0', true)- await expect(page).toHaveURL('/search/image?q=cat&license=cc0')})diff --git a/test/e2e/image-detail.spec.js b/test/e2e/image-detail.spec.jsindex f456f146a..1523eb44f 100644--- a/test/e2e/image-detail.spec.js+++ b/test/e2e/image-detail.spec.js@@ -35,7 +35,9 @@ test('shows the main image with its title as alt text', async ({ page }) => {test('does not show back to search results breadcrumb', async ({ page }) => {await goToCustomImagePage(page)- await expect(page.locator('text="Back to search results"')).not.toBeVisible()+ await expect(page.locator('text="Back to search results"')).not.toBeVisible({+ timeout: 300,+ })})test('redirects from old /photos/:id route to /image/:id', async ({ page }) => {diff --git a/test/e2e/search-query-server.spec.js b/test/e2e/search-query-server.spec.jsindex cf854b89c..d40c09cfd 100644--- a/test/e2e/search-query-server.spec.js+++ b/test/e2e/search-query-server.spec.js@@ -1,7 +1,7 @@const { test, expect } = require('@playwright/test')const { mockProviderApis, openFilters } = require('./utils')-const { currentContentType, assertCheckboxCheckedStatus } = require('./utils')+const { currentContentType, assertCheckboxStatus } = require('./utils')/*** URL is correctly converted into search state:@@ -57,9 +57,9 @@ test('url query to filter, all tab, one parameter per filter type', async ({)await openFilters(page)- await assertCheckboxCheckedStatus(page, 'cc0')- await assertCheckboxCheckedStatus(page, 'commercial')- await assertCheckboxCheckedStatus(page, 'creator')+ for (let checkbox of ['cc0', 'commercial', 'creator']) {+ await assertCheckboxStatus(page, checkbox)+ }})test('url query to filter, image tab, several filters for one filter type selected', async ({@@ -71,7 +71,7 @@ test('url query to filter, image tab, several filters for one filter type selectawait openFilters(page)const checkboxes = ['jpeg', 'png', 'gif', 'svgs']for (let checkbox of checkboxes) {- await assertCheckboxCheckedStatus(page, checkbox)+ await assertCheckboxStatus(page, checkbox)}})diff --git a/test/e2e/search-types.spec.js b/test/e2e/search-types.spec.jsindex a19ef7e12..6d73cb9ad 100644--- a/test/e2e/search-types.spec.js+++ b/test/e2e/search-types.spec.js@@ -52,6 +52,8 @@ const searchTypes = [async function checkLoadMore(page, searchType) {const loadMoreSection = await page.locator('[data-testid="load-more"]')if (!searchType.canLoadMore) {+ // When we expect the section not to be here, the test becomes very slow because+ // it waits until the end of the timeout (5 seconds).await expect(loadMoreSection).toHaveCount(0, { timeout: 300 })} else {await expect(loadMoreSection).toHaveCount(1)diff --git a/test/e2e/utils.js b/test/e2e/utils.jsindex 585cce6e3..7823b9278 100644--- a/test/e2e/utils.js+++ b/test/e2e/utils.js@@ -11,12 +11,22 @@ const openFilters = async (page) => {}}-const assertCheckboxCheckedStatus = async (page, label, checked = true) => {- const checkbox = page.locator(`label:has-text("${label}")`)- if (checked) {- await expect(checkbox).toBeChecked()- } else {- await expect(checkbox).not.toBeChecked()+const assertCheckboxStatus = async (page, label, status = 'checked') => {+ const checkbox = page.locator(`label:has-text('${label}')`)+ switch (status) {+ case 'checked': {+ await expect(checkbox).not.toBeDisabled()+ await expect(checkbox).toBeChecked()+ break+ }+ case 'unchecked': {+ await expect(checkbox).not.toBeDisabled()+ await expect(checkbox).not.toBeChecked()+ break+ }+ case 'disabled': {+ await expect(checkbox).toBeDisabled()+ }}}@@ -46,6 +56,6 @@ module.exports = {openFilters,changeContentType,currentContentType,- assertCheckboxCheckedStatus,+ assertCheckboxStatus,mockProviderApis,}diff --git a/test/tapes/response-50.json5 b/test/tapes/response-50.json5new file mode 100644index 000000000..37d2586fb--- /dev/null+++ b/test/tapes/response-50.json5@@ -0,0 +1,410 @@+{+ meta: {+ createdAt: '2022-03-03T06:50:45.582Z',+ host: 'https://api.openverse.engineering/v1',+ resHumanReadable: true,+ },+ req: {+ headers: {+ accept: 'application/json, text/plain, */*',+ connection: 'close',+ },+ url: '/audio/?q=cat&license_type=commercial',+ method: 'GET',+ body: '',+ },+ res: {+ status: 200,+ headers: {+ date: [+ 'Thu, 03 Mar 2022 06:50:45 GMT',+ ],+ 'content-type': [+ 'application/json',+ ],+ 'transfer-encoding': [+ 'chunked',+ ],+ connection: [+ 'close',+ ],+ vary: [+ 'Accept-Encoding, Accept, Authorization, Origin',+ ],+ allow: [+ 'GET, HEAD, OPTIONS',+ ],+ 'x-frame-options': [+ 'DENY',+ ],+ 'x-content-type-options': [+ 'nosniff',+ ],+ 'referrer-policy': [+ 'same-origin',+ ],+ 'cache-control': [+ 'max-age=14400',+ ],+ 'cf-cache-status': [+ 'HIT',+ ],+ age: [+ '163995',+ ],+ 'last-modified': [+ 'Tue, 01 Mar 2022 09:17:30 GMT',+ ],+ 'expect-ct': [+ 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',+ ],+ 'strict-transport-security': [+ 'max-age=15552000; includeSubDomains; preload',+ ],+ server: [+ 'cloudflare',+ ],+ 'cf-ray': [+ '6e6070948b556277-OTP',+ ],+ 'alt-svc': [+ 'h3=":443"; ma=86400, h3-29=":443"; ma=86400',+ ],+ },+ body: {+ result_count: 8,+ page_count: 0,+ page_size: 20,+ page: 1,+ results: [+ {+ id: '2ecd5631-c48c-4a5f-89c4-83c44dbbd365',+ title: 'Lucky Cat',+ foreign_landing_url: 'https://www.jamendo.com/track/24850',+ creator: 'Bruce H. McCosar',+ creator_url: 'https://www.jamendo.com/artist/3737/bruce.h.mccosar',+ url: 'https://mp3d.jamendo.com/download/track/24850/mp32',+ license: 'by-sa',+ license_version: '3.0',+ license_url: 'https://creativecommons.org/licenses/by-sa/3.0/',+ provider: 'jamendo',+ source: 'jamendo',+ category: 'music',+ tags: [+ {+ name: 'instrumental',+ },+ {+ name: 'neutral',+ },+ {+ name: 'speed_medium',+ },+ {+ name: 'neutral',+ },+ ],+ fields_matched: [+ 'title',+ ],+ genres: [+ 'pop',+ 'jazz',+ ],+ duration: 335000,+ thumbnail: 'http://api.openverse.engineering/v1/audio/2ecd5631-c48c-4a5f-89c4-83c44dbbd365/thumb/',+ waveform: 'http://api.openverse.engineering/v1/audio/2ecd5631-c48c-4a5f-89c4-83c44dbbd365/waveform/',+ detail_url: 'http://api.openverse.engineering/v1/audio/2ecd5631-c48c-4a5f-89c4-83c44dbbd365/',+ related_url: 'http://api.openverse.engineering/v1/audio/2ecd5631-c48c-4a5f-89c4-83c44dbbd365/related/',+ },+ {+ id: '1bb94f50-009c-4371-a605-dd289562a9f5',+ title: 'Cat Meow.aif',+ foreign_landing_url: 'https://freesound.org/people/Wrenasmir/sounds/455493',+ creator: 'Wrenasmir',+ creator_url: 'https://freesound.org/people/Wrenasmir',+ url: 'https://freesound.org/data/previews/455/455493_1138747-hq.mp3',+ license: 'cc0',+ license_version: '1.0',+ license_url: 'https://creativecommons.org/publicdomain/zero/1.0/',+ provider: 'freesound',+ source: 'freesound',+ category: 'sound',+ tags: [+ {+ name: 'Meow',+ },+ {+ name: 'Cat',+ },+ {+ name: 'Voice-Acting',+ },+ ],+ fields_matched: [+ 'description',+ 'tags.name',+ 'title',+ ],+ duration: 6750,+ bit_rate: 128000,+ thumbnail: 'http://api.openverse.engineering/v1/audio/1bb94f50-009c-4371-a605-dd289562a9f5/thumb/',+ waveform: 'http://api.openverse.engineering/v1/audio/1bb94f50-009c-4371-a605-dd289562a9f5/waveform/',+ detail_url: 'http://api.openverse.engineering/v1/audio/1bb94f50-009c-4371-a605-dd289562a9f5/',+ related_url: 'http://api.openverse.engineering/v1/audio/1bb94f50-009c-4371-a605-dd289562a9f5/related/',+ },+ {+ id: '71a2cf71-cdb0-49d6-94d0-d0f757e37799',+ title: "Mahler's Cat",+ foreign_landing_url: 'https://www.jamendo.com/track/35663',+ creator: 'softspace',+ creator_url: 'https://www.jamendo.com/artist/4965/softspace',+ url: 'https://mp3d.jamendo.com/download/track/35663/mp32',+ license: 'by',+ license_version: '3.0',+ license_url: 'https://creativecommons.org/licenses/by/3.0/',+ provider: 'jamendo',+ source: 'jamendo',+ category: 'music',+ tags: [+ {+ name: 'instrumental',+ },+ {+ name: 'speed_medium',+ },+ {+ name: 'soundscape',+ },+ ],+ fields_matched: [+ 'title',+ ],+ genres: [+ 'electronic',+ 'ambient',+ 'experimental',+ ],+ duration: 382000,+ thumbnail: 'http://api.openverse.engineering/v1/audio/71a2cf71-cdb0-49d6-94d0-d0f757e37799/thumb/',+ waveform: 'http://api.openverse.engineering/v1/audio/71a2cf71-cdb0-49d6-94d0-d0f757e37799/waveform/',+ detail_url: 'http://api.openverse.engineering/v1/audio/71a2cf71-cdb0-49d6-94d0-d0f757e37799/',+ related_url: 'http://api.openverse.engineering/v1/audio/71a2cf71-cdb0-49d6-94d0-d0f757e37799/related/',+ },+ {+ id: 'cc04c4a8-f5b1-4d2f-9644-c25dd3b862f4',+ title: 'EclipseBeforeDuringAfter.flac',+ foreign_landing_url: 'https://freesound.org/people/zimbot/sounds/400175',+ creator: 'zimbot',+ creator_url: 'https://freesound.org/people/zimbot',+ url: 'https://freesound.org/data/previews/400/400175_1449999-hq.mp3',+ license: 'by',+ license_version: '3.0',+ license_url: 'https://creativecommons.org/licenses/by/3.0/',+ provider: 'freesound',+ source: 'freesound',+ category: 'sound',+ tags: [+ {+ name: 'summer',+ },+ {+ name: 'field-recording',+ },+ {+ name: 'insects',+ },+ {+ name: 'eclipse',+ },+ {+ name: 'water',+ },+ {+ name: 'solar-eclipse',+ },+ {+ name: 'birds',+ },+ ],+ fields_matched: [+ 'description',+ ],+ duration: 321616,+ bit_rate: 128000,+ thumbnail: 'http://api.openverse.engineering/v1/audio/cc04c4a8-f5b1-4d2f-9644-c25dd3b862f4/thumb/',+ waveform: 'http://api.openverse.engineering/v1/audio/cc04c4a8-f5b1-4d2f-9644-c25dd3b862f4/waveform/',+ detail_url: 'http://api.openverse.engineering/v1/audio/cc04c4a8-f5b1-4d2f-9644-c25dd3b862f4/',+ related_url: 'http://api.openverse.engineering/v1/audio/cc04c4a8-f5b1-4d2f-9644-c25dd3b862f4/related/',+ },+ {+ id: 'a3ff8120-23e7-426d-9aa5-dc929e7e1665',+ title: 'gato.mp3',+ foreign_landing_url: 'https://freesound.org/people/Sofia_Erzini/sounds/411665',+ creator: 'Sofia_Erzini',+ creator_url: 'https://freesound.org/people/Sofia_Erzini',+ url: 'https://freesound.org/data/previews/411/411665_7325786-hq.mp3',+ license: 'cc0',+ license_version: '1.0',+ license_url: 'https://creativecommons.org/publicdomain/zero/1.0/',+ provider: 'freesound',+ source: 'freesound',+ category: 'sound',+ tags: [+ {+ name: 'voice',+ },+ {+ name: 'call',+ },+ {+ name: 'Cat',+ },+ ],+ fields_matched: [+ 'tags.name',+ ],+ duration: 40112,+ bit_rate: 128000,+ thumbnail: 'http://api.openverse.engineering/v1/audio/a3ff8120-23e7-426d-9aa5-dc929e7e1665/thumb/',+ waveform: 'http://api.openverse.engineering/v1/audio/a3ff8120-23e7-426d-9aa5-dc929e7e1665/waveform/',+ detail_url: 'http://api.openverse.engineering/v1/audio/a3ff8120-23e7-426d-9aa5-dc929e7e1665/',+ related_url: 'http://api.openverse.engineering/v1/audio/a3ff8120-23e7-426d-9aa5-dc929e7e1665/related/',+ },+ {+ id: '8f440118-dd97-4853-9760-69c37cea2db9',+ title: 'Far summer camp children NL 170815_1207.flac',+ foreign_landing_url: 'https://freesound.org/people/klankbeeld/sounds/399567',+ creator: 'klankbeeld',+ creator_url: 'https://freesound.org/people/klankbeeld',+ url: 'https://freesound.org/data/previews/399/399567_1648170-hq.mp3',+ license: 'by',+ license_version: '3.0',+ license_url: 'https://creativecommons.org/licenses/by/3.0/',+ provider: 'freesound',+ source: 'freesound',+ category: 'sound',+ tags: [+ {+ name: 'field-recording',+ },+ {+ name: 'announcer',+ },+ {+ name: 'summer',+ },+ {+ name: 'Netherlands',+ },+ {+ name: 'Dutch',+ },+ {+ name: 'village',+ },+ {+ name: 'daytime',+ },+ {+ name: 'ambient',+ },+ {+ name: 'ambience',+ },+ {+ name: 'megaphone',+ },+ {+ name: 'Holland',+ },+ {+ name: 'garden',+ },+ ],+ fields_matched: [+ 'description',+ ],+ duration: 614381,+ bit_rate: 128000,+ thumbnail: 'http://api.openverse.engineering/v1/audio/8f440118-dd97-4853-9760-69c37cea2db9/thumb/',+ waveform: 'http://api.openverse.engineering/v1/audio/8f440118-dd97-4853-9760-69c37cea2db9/waveform/',+ detail_url: 'http://api.openverse.engineering/v1/audio/8f440118-dd97-4853-9760-69c37cea2db9/',+ related_url: 'http://api.openverse.engineering/v1/audio/8f440118-dd97-4853-9760-69c37cea2db9/related/',+ },+ {+ id: 'dcc5d424-526d-41c2-97c2-d4521b0444f4',+ title: 'pfsss.aif',+ foreign_landing_url: 'https://freesound.org/people/brunchik/sounds/401597',+ creator: 'brunchik',+ creator_url: 'https://freesound.org/people/brunchik',+ url: 'https://freesound.org/data/previews/401/401597_3516609-hq.mp3',+ license: 'cc0',+ license_version: '1.0',+ license_url: 'https://creativecommons.org/publicdomain/zero/1.0/',+ provider: 'freesound',+ source: 'freesound',+ category: 'sound',+ tags: [+ {+ name: 'psss',+ },+ {+ name: 'come-here-kitty',+ },+ {+ name: 'pfsss',+ },+ {+ name: 'cat',+ },+ ],+ fields_matched: [+ 'description',+ 'tags.name',+ ],+ duration: 7833,+ bit_rate: 128000,+ thumbnail: 'http://api.openverse.engineering/v1/audio/dcc5d424-526d-41c2-97c2-d4521b0444f4/thumb/',+ waveform: 'http://api.openverse.engineering/v1/audio/dcc5d424-526d-41c2-97c2-d4521b0444f4/waveform/',+ detail_url: 'http://api.openverse.engineering/v1/audio/dcc5d424-526d-41c2-97c2-d4521b0444f4/',+ related_url: 'http://api.openverse.engineering/v1/audio/dcc5d424-526d-41c2-97c2-d4521b0444f4/related/',+ },+ {+ id: '7956ce8d-a029-4a86-9474-90fe9f765fd6',+ title: 'gato 3.mp3',+ foreign_landing_url: 'https://freesound.org/people/Sofia_Erzini/sounds/411666',+ creator: 'Sofia_Erzini',+ creator_url: 'https://freesound.org/people/Sofia_Erzini',+ url: 'https://freesound.org/data/previews/411/411666_7325786-hq.mp3',+ license: 'cc0',+ license_version: '1.0',+ license_url: 'https://creativecommons.org/publicdomain/zero/1.0/',+ provider: 'freesound',+ source: 'freesound',+ category: 'sound',+ tags: [+ {+ name: 'voice',+ },+ {+ name: 'call',+ },+ {+ name: 'Cat',+ },+ ],+ fields_matched: [+ 'tags.name',+ ],+ duration: 9000,+ bit_rate: 128000,+ thumbnail: 'http://api.openverse.engineering/v1/audio/7956ce8d-a029-4a86-9474-90fe9f765fd6/thumb/',+ waveform: 'http://api.openverse.engineering/v1/audio/7956ce8d-a029-4a86-9474-90fe9f765fd6/waveform/',+ detail_url: 'http://api.openverse.engineering/v1/audio/7956ce8d-a029-4a86-9474-90fe9f765fd6/',+ related_url: 'http://api.openverse.engineering/v1/audio/7956ce8d-a029-4a86-9474-90fe9f765fd6/related/',+ },+ ],+ },+ },+}\ No newline at end of filediff --git a/test/unit/specs/components/VHeader/v-filter-button.spec.js b/test/unit/specs/components/VHeader/v-filter-button.spec.jsindex 9fd274170..981e03a78 100644--- a/test/unit/specs/components/VHeader/v-filter-button.spec.js+++ b/test/unit/specs/components/VHeader/v-filter-button.spec.js@@ -1,23 +1,47 @@import { render, screen } from '@testing-library/vue'import { createLocalVue } from '@vue/test-utils'-import Vuex from 'vuex'import VueI18n from 'vue-i18n'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 { IMAGE } from '~/constants/media'+import VFilterButton from '~/components/VHeader/VFilterButton.vue'-import messages from '../../../../../src/locales/en.json'+function applyNFilters(filterCount, filterStore) {+ 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({+ filterType,+ codeIdx: filterIdx,+ })+ filterIdx += 1+ if (filterData[filterType].length === filterIdx) {+ filterTypeIdx += 1+ filterIdx = 0+ }+ }+}describe('VFilterButton', () => {let options = {}- let storeMocklet localVue- let appliedFilters = []let props = {}let provided = {isMinScreenMd: ref(true),isHeaderScrolled: ref(false),}+ let pinia+ let filterStoreconst i18n = new VueI18n({locale: 'en',@@ -27,25 +51,20 @@ describe('VFilterButton', () => {})beforeEach(() => {localVue = createLocalVue()- localVue.use(Vuex)localVue.use(VueI18n)+ localVue.use(PiniaVuePlugin)+ pinia = createPinia()+ filterStore = useFilterStore(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)- storeMock = new Vuex.Store({- modules: {- search: {- namespaced: true,- getters: {- isAnyFilterApplied: () => appliedFilters.length > 0,- appliedFilterTags: () => appliedFilters,- },- },- },- })options = {localVue,propsData: props,- mocks: { $nuxt: { context: { store: storeMock, i18n } } },+ mocks: { $nuxt: { context: { i18n } } },provide: provided,+ pinia,}})@@ -63,17 +82,16 @@ describe('VFilterButton', () => {it('shows the count and text when filters are applied', () => {provided.isMinScreenMd.value = true// +2 to guarantee it's plural- const filterCount = Math.floor(Math.random() * 10) + 2- appliedFilters = Array(filterCount).fill('')- render(VFilterButton, options)-- const button = screen.getByText(`${filterCount} Filters`)+ const filterCount = Math.floor(Math.random() * 9) + 2+ applyNFilters(filterCount, filterStore)+ const wrapper = render(VFilterButton, options)+ const button = wrapper.getByText(`${filterCount} Filters`)expect(button).toBeVisible()})it('does not show the icon when filters are applied', () => {provided.isMinScreenMd.value = true- appliedFilters = ['mockfilter1', 'mockfilter2']+ filterStore.toggleFilter({ filterType: 'licenses', codeIdx: 0 })const { container } = render(VFilterButton, options)const icon = container.querySelector('svg')@@ -85,7 +103,6 @@ describe('VFilterButton', () => {describe('below the medium breakpoint', () => {it('only shows the filter icon by default', () => {provided.isMinScreenMd.value = false- appliedFilters = []const { container } = render(VFilterButton, options)const icon = container.querySelector('svg')@@ -98,7 +115,7 @@ describe('VFilterButton', () => {provided.isMinScreenMd.value = false// +2 to guarantee it's pluralconst filterCount = Math.floor(Math.random() * 10) + 2- appliedFilters = Array(filterCount).fill('')+ applyNFilters(filterCount, filterStore)const { container } = render(VFilterButton, options)const icon = container.querySelector('svg')@@ -112,7 +129,7 @@ describe('VFilterButton', () => {provided.isHeaderScrolled.value = true// +2 to guarantee it's pluralconst filterCount = Math.floor(Math.random() * 10) + 2- appliedFilters = Array(filterCount).fill('')+ applyNFilters(filterCount, filterStore)const { container } = render(VFilterButton, options)const icon = container.querySelector('svg')diff --git a/test/unit/specs/components/filter-checklist.spec.js b/test/unit/specs/components/v-filter-checklist.spec.jssimilarity index 87%rename from test/unit/specs/components/filter-checklist.spec.jsrename to test/unit/specs/components/v-filter-checklist.spec.jsindex 170d5760b..8043ad600 100644--- a/test/unit/specs/components/filter-checklist.spec.js+++ b/test/unit/specs/components/v-filter-checklist.spec.js@@ -1,15 +1,21 @@import { createLocalVue } from '@vue/test-utils'import { fireEvent, render, screen } from '@testing-library/vue'+import { PiniaVuePlugin, createPinia } from 'pinia'+import FilterChecklist from '~/components/VFilters/VFilterChecklist'describe('FilterChecklist', () => {let options = {}let props = nulllet localVue = null+ let piniabeforeEach(() => {localVue = createLocalVue()+ localVue.use(PiniaVuePlugin)+ pinia = createPinia()+props = {options: [{ code: 'foo', name: 'bar', checked: false }],title: 'Foo',@@ -18,6 +24,7 @@ describe('FilterChecklist', () => {}options = {localVue,+ pinia,propsData: props,}})diff --git a/test/unit/specs/components/search-grid-filter.spec.js b/test/unit/specs/components/v-search-grid-filter.spec.jssimilarity index 59%rename from test/unit/specs/components/search-grid-filter.spec.jsrename to test/unit/specs/components/v-search-grid-filter.spec.jsindex fbf37278f..48bd16540 100644--- a/test/unit/specs/components/search-grid-filter.spec.js+++ b/test/unit/specs/components/v-search-grid-filter.spec.js@@ -1,9 +1,9 @@import Vuex from 'vuex'import { fireEvent, render, screen } from '@testing-library/vue'import { createLocalVue } from '@vue/test-utils'-import clonedeep from 'lodash.clonedeep'import VueI18n from 'vue-i18n'+import { createPinia, PiniaVuePlugin } from 'pinia'import { IMAGE } from '~/constants/media'import store from '~/store/search'@@ -11,56 +11,35 @@ import { FETCH_MEDIA } from '~/constants/action-types'import messages from '~/locales/en.json'-import SearchGridFilter from '~/components/VFilters/VSearchGridFilter.vue'+import { useFilterStore } from '~/stores/filter'-const initialFilters = {- licenseTypes: [- {- code: 'commercial',- name: 'Commercial usage',- checked: false,- },- {- code: 'modification',- name: 'Modify or adapt',- checked: false,- },- ],- licenses: [{ code: 'by', name: 'CC-BY', checked: false }],- imageCategories: [{ code: 'photo', name: 'Photographs', checked: false }],- imageExtensions: [{ code: 'jpg', name: 'JPG', checked: false }],- imageProviders: [{ code: 'met', name: 'Metropolitan', checked: false }],- audioProviders: [{ code: 'jamendo', name: 'Jamendo', checked: false }],- sizes: [{ code: 'small', name: 'small', checked: false }],- aspectRatios: [],- searchBy: [{ code: 'creator', checked: false }],- mature: [{ code: 'mature', name: 'mature', checked: false }],-}+import VSearchGridFilter from '~/components/VFilters/VSearchGridFilter.vue'-describe('SearchGridFilter', () => {+describe('VSearchGridFilter', () => {let options = {}let storeMocklet localVue- let filters+ let pinia+ let filterStoreconst routerMock = { push: jest.fn() }beforeEach(() => {localVue = createLocalVue()localVue.use(Vuex)+ localVue.use(PiniaVuePlugin)+ pinia = createPinia()localVue.use(VueI18n)const i18n = new VueI18n({locale: 'en',fallbackLocale: 'en',messages: { en: messages },})- filters = clonedeep(initialFilters)storeMock = new Vuex.Store({modules: {search: {namespaced: true,state: {searchType: IMAGE,- filters,query: { q: '' },},mutations: store.mutations,@@ -81,6 +60,7 @@ describe('SearchGridFilter', () => {options = {localVue,+ pinia,i18n,mocks: {$router: routerMock,@@ -92,30 +72,23 @@ describe('SearchGridFilter', () => {},},},- stubs: { VIcon: true },}- })-- it('should show search filters when isFilterVisible is true', async () => {- storeMock.state.search.isFilterVisible = true- await render(SearchGridFilter, options)- expect(screen.getByTestId('filters-list')).toBeVisible()+ filterStore = useFilterStore(pinia)})it('toggles filter', async () => {- render(SearchGridFilter, options)+ render(VSearchGridFilter, options)const checked = screen.queryAllByRole('checkbox', { checked: true })expect(checked.length).toEqual(0)-await fireEvent.click(screen.queryByLabelText(/commercial/i))// `getBy` serves as expect because it throws an error if no element is foundscreen.getByRole('checkbox', { checked: true })- screen.getByLabelText('Commercial usage', { checked: true })+ screen.getByLabelText(/commercial/, { checked: true })})it('clears filters', async () => {- storeMock.state.search.filters.licenses[0].checked = true- await render(SearchGridFilter, options)+ filterStore.toggleFilter({ filterType: 'licenses', code: 'by' })+ await render(VSearchGridFilter, options)// if no checked checkboxes were found, this would raise an errorscreen.getByRole('checkbox', { checked: true })@@ -124,8 +97,9 @@ describe('SearchGridFilter', () => {const uncheckedFilters = screen.queryAllByRole('checkbox', {checked: false,})+expect(checkedFilters.length).toEqual(0)// Filters are reset with the initial `filterData`- expect(uncheckedFilters.length).toEqual(25)+ expect(uncheckedFilters.length).toEqual(24)})})diff --git a/test/unit/specs/pages/browse-page.spec.js b/test/unit/specs/pages/browse-page.spec.jsindex a9589975c..e87753820 100644--- a/test/unit/specs/pages/browse-page.spec.js+++ b/test/unit/specs/pages/browse-page.spec.js@@ -20,10 +20,6 @@ describe('SearchIndex', () => {query: { q: 'foo' },searchType: 'image',},- getters: {- isAnyFilterApplied: () => false,- appliedFilterTags: () => [],- },},media: {namespaced: true,diff --git a/test/unit/specs/store/filter-store.spec.js b/test/unit/specs/store/filter-store.spec.jsnew file mode 100644index 000000000..0909f5b25--- /dev/null+++ b/test/unit/specs/store/filter-store.spec.js@@ -0,0 +1,269 @@+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'} | ${0}+ ${'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/provider.spec.js b/test/unit/specs/store/provider.spec.jsindex ef5b3faea..7db8bef8b 100644--- a/test/unit/specs/store/provider.spec.js+++ b/test/unit/specs/store/provider.spec.js@@ -1,3 +1,5 @@+import { createPinia, setActivePinia } from 'pinia'+import { state, mutations, createActions } from '~/store/provider'import {FETCH_MEDIA_PROVIDERS_END,@@ -65,7 +67,9 @@ describe('Image Provider Store', () => {const services = { [IMAGE]: imageProviderServiceMock }const commit = jest.fn()const dispatch = jest.fn()+it('FETCH_MEDIA_TYPE_PROVIDERS on success', (done) => {+ setActivePinia(createPinia())const action = createActions(services)[FETCH_MEDIA_TYPE_PROVIDERS]action({ commit, dispatch }, { mediaType: 'image' }).then(() => {expect(commit).toBeCalledWith(SET_PROVIDER_FETCH_ERROR, {diff --git a/test/unit/specs/store/search-store.spec.js b/test/unit/specs/store/search-store.spec.jsindex d533ed663..738324463 100644--- a/test/unit/specs/store/search-store.spec.js+++ b/test/unit/specs/store/search-store.spec.js@@ -1,37 +1,49 @@+import { createPinia, setActivePinia } from 'pinia'+import store from '~/store/search'import {CLEAR_FILTERS,SET_SEARCH_STATE_FROM_URL,- TOGGLE_FILTER,UPDATE_QUERY_FROM_FILTERS,} from '~/constants/action-types'-import {- SET_FILTER,- SET_PROVIDERS_FILTERS,- REPLACE_FILTERS,- SET_SEARCH_TYPE,- SET_QUERY,-} from '~/constants/mutation-types'+import { SET_SEARCH_TYPE, SET_QUERY } from '~/constants/mutation-types'import { ALL_MEDIA, AUDIO, IMAGE } from '~/constants/media'-import { filterData } from '~/constants/filters.ts'--describe('Filter Store', () => {+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('state contains all filters', () => {+ it('initial state is set correctly', () => {const defaultState = store.state()-- expect(defaultState.filters).toEqual(filterData)+ expect(defaultState).toEqual(initialState)})})describe('mutations', () => {let state = nulllet mutations = null- let getters = nullbeforeEach(() => {+ setActivePinia(createPinia())+state = {search: {searchType: 'image',@@ -40,7 +52,6 @@ describe('Filter Store', () => {...store.state(),}mutations = store.mutations- getters = store.getters})it('SET_QUERY updates state', () => {@@ -55,71 +66,6 @@ describe('Filter Store', () => {mutations[SET_SEARCH_TYPE](state, { searchType: AUDIO })expect(state.searchType).toEqual(AUDIO)})-- it.each`- filterType | codeIdx- ${'licenses'} | ${0}- ${'licenseTypes'} | ${0}- ${'imageExtensions'} | ${0}- ${'imageCategories'} | ${0}- ${'searchBy'} | ${0}- ${'aspectRatios'} | ${0}- ${'sizes'} | ${0}- `(- 'SET_FILTER updates $filterType filter state',- ({ filterType, codeIdx }) => {- mutations[SET_FILTER](state, { filterType, codeIdx })-- expect(state.filters[filterType][codeIdx].checked).toBeTruthy()- }- )-- it('SET_FILTER updates mature', () => {- mutations[SET_FILTER](state, { filterType: 'mature', codeIdx: 0 })-- expect(state.filters.mature[0].checked).toBeTruthy()- })-- it('SET_FILTER toggles mature', () => {- state.filters.mature[0].checked = true- mutations[SET_FILTER](state, { filterType: 'mature', codeIdx: 0 })-- expect(state.filters.mature[0].checked).toBeFalsy()- })-- it('SET_FILTER updates isFilterApplied with provider', () => {- state.filters.imageProviders = [{ code: 'met', checked: false }]- mutations[SET_FILTER](state, { filterType: 'imageProviders', codeIdx: 0 })-- expect(getters.isAnyFilterApplied).toBeTruthy()- })-- it('SET_FILTER updates isFilterApplied with license type', () => {- mutations[SET_FILTER](state, { filterType: 'licenseTypes', codeIdx: 0 })-- expect(getters.isAnyFilterApplied).toBeTruthy()- })-- it('SET_PROVIDERS_FILTERS merges with existing provider filters', () => {- const existingProviderFilters = [{ code: 'met', checked: true }]-- const providers = [- { source_name: 'met', display_name: 'Metropolitan' },- { source_name: 'flickr', display_name: 'Flickr' },- ]-- state.filters.imageProviders = existingProviderFilters-- mutations[SET_PROVIDERS_FILTERS](state, {- mediaType: 'image',- providers: providers,- })-- expect(state.filters.imageProviders).toEqual([- { code: 'met', name: 'Metropolitan', checked: true },- { code: 'flickr', name: 'Flickr', checked: false },- ])- })})describe('actions', () => {@@ -185,104 +131,18 @@ describe('Filter Store', () => {)it('CLEAR_FILTERS resets filters to initial state', async () => {- state.filters.licenses = [- { code: 'by', checked: true },- { code: 'by-nc', checked: true },- { code: 'by-nd', checked: true },- ]+ 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(commitMock).toHaveBeenCalledWith(REPLACE_FILTERS, {- newFilterData: filterData,- })expect(dispatchMock).toHaveBeenCalledWith(UPDATE_QUERY_FROM_FILTERS, {q: '',})})-- it('CLEAR_FILTERS sets providers filters checked to false', async () => {- state.filters.imageProviders = [- { code: 'met', name: 'Metropolitan', checked: true },- { code: 'flickr', name: 'Flickr', checked: false },- ]-- actions[CLEAR_FILTERS]({- commit: commitMock,- dispatch: dispatchMock,- state,- })- const expectedFilters = {- ...state.filters,- imageProviders: [- { code: 'met', name: 'Metropolitan', checked: false },- { code: 'flickr', name: 'Flickr', checked: false },- ],- }- expect(commitMock).toHaveBeenCalledWith(REPLACE_FILTERS, {- newFilterData: expectedFilters,- })- expect(dispatchMock).toHaveBeenCalledWith(UPDATE_QUERY_FROM_FILTERS, {- q: '',- })- })-- it.each`- filterType | code | idx- ${'licenses'} | ${'cc0'} | ${0}- ${'licenseTypes'} | ${'modification'} | ${1}- ${'imageExtensions'} | ${'svg'} | ${3}- ${'imageCategories'} | ${'photograph'} | ${0}- ${'searchBy'} | ${'creator'} | ${0}- ${'mature'} | ${undefined} | ${-1}- ${'aspectRatios'} | ${'tall'} | ${0}- ${'sizes'} | ${'medium'} | ${1}- `(- "TOGGLE_FILTER should set filter '$code' of type '$filterType",- ({ filterType, code, idx }) => {- actions[TOGGLE_FILTER](- { commit: commitMock, dispatch: dispatchMock, state },- { filterType: filterType, code: code }- )- expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {- filterType: filterType,- code: code,- codeIdx: idx,- })-- expect(dispatchMock).toHaveBeenCalledWith(UPDATE_QUERY_FROM_FILTERS)- }- )-- it('TOGGLE_FILTER updates mature', () => {- actions[TOGGLE_FILTER](- { commit: commitMock, dispatch: dispatchMock, state },- { filterType: 'mature' }- )-- expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {- filterType: 'mature',- codeIdx: -1,- })-- expect(dispatchMock).toHaveBeenCalledWith(UPDATE_QUERY_FROM_FILTERS)- })-- it('TOGGLE_FILTER toggles mature', () => {- state.filters.mature = true- actions[TOGGLE_FILTER](- { commit: commitMock, dispatch: dispatchMock, state },- { filterType: 'mature' }- )-- expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {- filterType: 'mature',- codeIdx: -1,- })-- expect(dispatchMock).toHaveBeenCalledWith(UPDATE_QUERY_FROM_FILTERS)- })})})