Skip to content

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

Refactor the usage of i18n result count computation (#707)

Olga Bulatc9fa17e1815d
diff --git a/src/components/VContentLink/VContentLink.vue b/src/components/VContentLink/VContentLink.vue
index bf1c5988a..f6b6d21d3 100644
--- a/src/components/VContentLink/VContentLink.vue
+++ b/src/components/VContentLink/VContentLink.vue
@@ -17,17 +17,18 @@
<script>
import { computed, defineComponent } from '@nuxtjs/composition-api'
-import { resultsCount } from '~/composables/use-i18n-utilities'
-import {
- AUDIO,
- IMAGE,
- supportedMediaTypes as mediaTypes,
-} from '~/constants/media'
+import { useI18nResultsCount } from '~/composables/use-i18n-utilities'
+import { AUDIO, IMAGE, supportedMediaTypes } from '~/constants/media'
import VIcon from '~/components/VIcon/VIcon.vue'
import audioIcon from '~/assets/icons/audio-wave.svg'
import imageIcon from '~/assets/icons/image.svg'
+const iconMapping = {
+ [AUDIO]: audioIcon,
+ [IMAGE]: imageIcon,
+}
+
export default defineComponent({
name: 'VContentLink',
components: { VIcon },
@@ -38,7 +39,7 @@ export default defineComponent({
mediaType: {
type: String,
required: true,
- validator: (val) => mediaTypes.includes(val),
+ validator: (val) => supportedMediaTypes.includes(val),
},
/**
* The number of results that the search returned.
@@ -49,20 +50,11 @@ export default defineComponent({
},
},
setup(props) {
- const iconMapping = {
- [AUDIO]: audioIcon,
- [IMAGE]: imageIcon,
- }
const iconPath = computed(() => iconMapping[props.mediaType])
- const resultsCountLabel = computed(() => resultsCount(props.resultsCount))
+ const { getI18nCount } = useI18nResultsCount()
+ const resultsCountLabel = computed(() => getI18nCount(props.resultsCount))
return { iconPath, imageIcon, resultsCountLabel }
},
})
</script>
-
-<style scoped>
-button[aria-checked='true'] {
- @apply bg-dark-charcoal text-white;
-}
-</style>
diff --git a/src/components/VHeader/VHeader.vue b/src/components/VHeader/VHeader.vue
index 35b913056..760ae3571 100644
--- a/src/components/VHeader/VHeader.vue
+++ b/src/components/VHeader/VHeader.vue
@@ -85,13 +85,14 @@ import {
FETCH_MEDIA,
UPDATE_QUERY,
} from '~/constants/action-types'
-import { ALL_MEDIA, AUDIO, IMAGE } from '~/constants/media'
+import { AUDIO, IMAGE } from '~/constants/media'
import { isMinScreen } from '~/composables/use-media-query'
import {
useMatchSearchRoutes,
useMatchHomeRoute,
} from '~/composables/use-match-routes'
import { useFilterSidebarVisibility } from '~/composables/use-filter-sidebar-visibility'
+import { useI18nResultsCount } from '~/composables/use-i18n-utilities'
import closeIcon from '~/assets/icons/close.svg'
import OpenverseLogoText from '~/assets/icons/openverse-logo-text.svg?inline'
@@ -101,23 +102,6 @@ import VHeaderFilter from '~/components/VHeader/VHeaderFilter.vue'
import VLogoLoader from '~/components/VLogoLoader/VLogoLoader.vue'
import VSearchBar from '~/components/VHeader/VSearchBar/VSearchBar.vue'
-const i18nKeys = {
- [ALL_MEDIA]: {
- noResult: 'browse-page.all-no-results',
- result: 'browse-page.all-result-count',
- more: 'browse-page.all-result-count-more',
- },
- [AUDIO]: {
- noResult: 'browse-page.audio-no-results',
- result: 'browse-page.audio-result-count',
- more: 'browse-page.audio-result-count-more',
- },
- [IMAGE]: {
- noResult: 'browse-page.image-no-results',
- result: 'browse-page.image-result-count',
- more: 'browse-page.image-result-count-more',
- },
-}
const menus = {
FILTERS: 'filters',
CONTENT_SWITCHER: 'content-switcher',
@@ -180,30 +164,15 @@ const VHeader = defineComponent({
return store.getters['media/fetchState'].isFetching
})
- /**
- * Return a text representation of the result count.
- * @param {number} count
- * @returns {string}
- */
- const mediaCount = (count) => {
- if (store.getters['media/unsupportedMediaType']) return ''
-
- const countKey =
- count === 0 ? 'noResult' : count >= 10000 ? 'more' : 'result'
- const i18nKey = i18nKeys[store.state.search.searchType][countKey]
- const localeCount = count.toLocaleString(i18n.locale)
- return i18n.tc(i18nKey, count, { localeCount })
- }
-
/** @type {import('@nuxtjs/composition-api').ComputedRef<number>} */
const resultsCount = computed(() => store.getters['media/resultCount'])
-
+ const { getI18nCount } = useI18nResultsCount()
/**
* Status is hidden below the medium breakpoint.
* It shows Loading... or Number of results on bigger screens.
* @returns {string}
*/
- const setInitialStatus = () => {
+ const setStatus = () => {
if (
!isMinScreenMd.value ||
!isSearchRoute.value ||
@@ -211,24 +180,12 @@ const VHeader = defineComponent({
)
return ''
if (isFetching.value) return i18n.t('header.loading')
- return mediaCount(resultsCount.value)
+ return getI18nCount(resultsCount.value)
}
- const searchStatus = ref(setInitialStatus())
+ const searchStatus = ref(setStatus())
- watchEffect(() => {
- if (isMinScreenMd.value) {
- if (isFetching.value) {
- searchStatus.value = i18n.t('header.loading')
- } else if (!isSearchRoute.value) {
- searchStatus.value = ''
- } else {
- searchStatus.value = mediaCount(resultsCount.value)
- }
- } else {
- searchStatus.value = ''
- }
- })
+ watchEffect(() => setStatus())
const localSearchTerm = ref(store.state.search.query.q)
const searchTerm = computed({
diff --git a/src/components/VSearchGrid.vue b/src/components/VSearchGrid.vue
index 9075e2f84..a71798d4c 100644
--- a/src/components/VSearchGrid.vue
+++ b/src/components/VSearchGrid.vue
@@ -27,7 +27,6 @@
<script>
import { computed } from '@nuxtjs/composition-api'
-import { resultsCount } from '~/composables/use-i18n-utilities'
import { supportedContentTypes } from '~/constants/media'
import VMetaSearchForm from '~/components/VMetaSearch/VMetaSearchForm.vue'
@@ -57,17 +56,6 @@ export default {
},
},
setup(props) {
- /**
- * The translated string showing how many results were found for
- * this media type.
- *
- * @returns {string}
- */
- const mediaCount = computed(() => {
- if (!props.supported) return
- return resultsCount(props.resultsCount, props.query.mediaType)
- })
-
const noresult = computed(() => {
// noresult is hard-coded for search types that are not currently
// supported by Openverse built-in search
@@ -86,7 +74,6 @@ export default {
})
return {
- mediaCount,
noresult,
isSupported,
metaSearchFormType,
diff --git a/src/composables/use-i18n-utilities.js b/src/composables/use-i18n-utilities.js
index 38d1e2e58..aa12b4b20 100644
--- a/src/composables/use-i18n-utilities.js
+++ b/src/composables/use-i18n-utilities.js
@@ -1,24 +1,38 @@
import { useContext } from '@nuxtjs/composition-api'
-import { ALL_MEDIA } from '~/constants/media'
/**
- * Returns the localized text for the number of search results according to the
- * media type.
- *
- * @param {number} resultsCount
- * @param {string} mediaType
- * @returns {string}
+ * Not using dynamically-generated keys to ensure that
+ * correct line is shown in the 'po' locale files
*/
-export function resultsCount(resultsCount, mediaType = ALL_MEDIA) {
- const { i18n } = useContext()
+const i18nKeys = {
+ noResult: 'browse-page.all-no-results',
+ result: 'browse-page.all-result-count',
+ more: 'browse-page.all-result-count-more',
+}
- const countKey =
- resultsCount === 0
- ? 'no-results'
- : resultsCount >= 10000
- ? 'result-count-more'
- : 'result-count'
- const fullKey = `browse-page.${mediaType}-${countKey}`
- const localeCount = resultsCount.toLocaleString(i18n.locale)
- return i18n.tc(fullKey, resultsCount, { localeCount })
+/**
+ * Returns the localized text for the number of search results.
+ */
+export function useI18nResultsCount() {
+ const { i18n } = useContext()
+ /**
+ * @param {number} resultsCount
+ * @returns {string}
+ */
+ const getI18nCount = (resultsCount) => {
+ const countKey =
+ resultsCount === 0
+ ? 'noResult'
+ : resultsCount >= 10000
+ ? 'more'
+ : 'result'
+ const fullKey = i18nKeys[countKey]
+ const countLocale =
+ i18n.localeProperties?.dir === 'rtl' ? 'en' : i18n.locale
+ const localeCount = resultsCount.toLocaleString(countLocale)
+ return i18n.tc(fullKey, resultsCount, { localeCount })
+ }
+ return {
+ getI18nCount,
+ }
}
diff --git a/src/locales/en.json b/src/locales/en.json
index 020c02968..8f1184a30 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -404,14 +404,8 @@
},
"browse-page": {
"all-no-results": "No results",
- "audio-no-results": "No audio results",
- "image-no-results": "No image results",
"all-result-count": "{localeCount} result|{localeCount} results",
- "audio-result-count": "{localeCount} audio result|{localeCount} audio results",
- "image-result-count": "{localeCount} image result|{localeCount} image results",
"all-result-count-more": "Over {localeCount} results",
- "audio-result-count-more": "Over {localeCount} audio results",
- "image-result-count-more": "Over {localeCount} image results",
"load": "Load more results",
"fetching-error": "Error fetching {type}:",
"search-rating": {
diff --git a/src/locales/po-files/openverse.pot b/src/locales/po-files/openverse.pot
index 8fc4fc245..ea4009255 100644
--- a/src/locales/po-files/openverse.pot
+++ b/src/locales/po-files/openverse.pot
@@ -720,14 +720,6 @@ msgctxt "browse-page.all-no-results"
msgid "No results"
msgstr ""
-msgctxt "browse-page.audio-no-results"
-msgid "No audio results"
-msgstr ""
-
-msgctxt "browse-page.image-no-results"
-msgid "No image results"
-msgstr ""
-
#. Do not translate words between ### ###.
msgctxt "browse-page.all-result-count"
msgid "###localeCount### result"
@@ -735,20 +727,6 @@ msgid_plural "###localeCount### results"
msgstr[0] ""
msgstr[1] ""
-#. Do not translate words between ### ###.
-msgctxt "browse-page.audio-result-count"
-msgid "###localeCount### audio result"
-msgid_plural "###localeCount### audio results"
-msgstr[0] ""
-msgstr[1] ""
-
-#. Do not translate words between ### ###.
-msgctxt "browse-page.image-result-count"
-msgid "###localeCount### image result"
-msgid_plural "###localeCount### image results"
-msgstr[0] ""
-msgstr[1] ""
-
#. Do not translate words between ### ###.
msgctxt "browse-page.all-result-count-more"
msgid "Over ###localeCount### results"
@@ -756,20 +734,6 @@ msgid_plural "Over ###localeCount### results"
msgstr[0] ""
msgstr[1] ""
-#. Do not translate words between ### ###.
-msgctxt "browse-page.audio-result-count-more"
-msgid "Over ###localeCount### audio results"
-msgid_plural "Over ###localeCount### audio results"
-msgstr[0] ""
-msgstr[1] ""
-
-#. Do not translate words between ### ###.
-msgctxt "browse-page.image-result-count-more"
-msgid "Over ###localeCount### image results"
-msgid_plural "Over ###localeCount### image results"
-msgstr[0] ""
-msgstr[1] ""
-
#: src/components/VLoadMore.vue:26
msgctxt "browse-page.load"
msgid "Load more results"
@@ -2007,7 +1971,7 @@ msgctxt "header.api-nav-item"
msgid "API"
msgstr ""
-#: src/components/VHeader/VHeader.vue:213
+#: src/components/VHeader/VHeader.vue:182
msgctxt "header.loading"
msgid "Loading..."
msgstr ""
diff --git a/src/pages/search.vue b/src/pages/search.vue
index 5fd6ee346..a01854688 100644
--- a/src/pages/search.vue
+++ b/src/pages/search.vue
@@ -25,14 +25,14 @@
</template>
<script>
+import { mapActions, mapGetters, mapState } from 'vuex'
import {
FETCH_MEDIA,
UPDATE_QUERY,
SET_SEARCH_STATE_FROM_URL,
UPDATE_SEARCH_TYPE,
} from '~/constants/action-types'
-import { ALL_MEDIA, AUDIO, IMAGE } from '~/constants/media'
-import { mapActions, mapGetters, mapState } from 'vuex'
+import { ALL_MEDIA, supportedContentTypes } from '~/constants/media'
import { MEDIA, SEARCH } from '~/constants/store-modules'
import { queryStringToSearchType } from '~/utils/search-query-transform'
@@ -91,7 +91,7 @@ const BrowsePage = {
return this.supported ? this.resultCount : 0 ?? 0
},
supported() {
- return [IMAGE, AUDIO, ALL_MEDIA].includes(this.searchType)
+ return supportedContentTypes.includes(this.searchType)
},
},
methods: {
diff --git a/test/e2e/homepage.spec.js b/test/e2e/homepage.spec.js
index 8e7167b1a..ecb2f48e5 100644
--- a/test/e2e/homepage.spec.js
+++ b/test/e2e/homepage.spec.js
@@ -44,9 +44,7 @@ test('can search for all results from homepage', async ({ page }) => {
await expect(page.locator('img')).toHaveCount(20)
})
-test.skip('can search for images from homepage, and then load more results', async ({
- page,
-}) => {
+test('can search for images from homepage', async ({ page }) => {
await page.goto('/')
await page.click('[aria-label="All content"]')
await page.click('button[role="radio"]:has-text("Images")')
@@ -58,6 +56,4 @@ test.skip('can search for images from homepage, and then load more results', asy
await expect(page).toHaveURL('search/image?q=cat')
await expect(page.locator('img')).toHaveCount(20)
- // await page.click('button:has-text("Load more")')
- // await expect(page.locator('img')).toHaveCount(40)
})
diff --git a/test/unit/specs/composables/use-i18n-utilities.spec.js b/test/unit/specs/composables/use-i18n-utilities.spec.js
new file mode 100644
index 000000000..204e0277c
--- /dev/null
+++ b/test/unit/specs/composables/use-i18n-utilities.spec.js
@@ -0,0 +1,31 @@
+import { useI18nResultsCount } from '~/composables/use-i18n-utilities'
+jest.mock('@nuxtjs/composition-api', () => ({
+ useContext: () => ({
+ i18n: {
+ tc: (fullKey, resultsCount, { localeCount }) => ({
+ fullKey,
+ resultsCount,
+ localeCount,
+ }),
+ },
+ locale: 'en',
+ }),
+}))
+
+describe('i18nResultsCount', () => {
+ it.each`
+ resultCount | expectedResult
+ ${0} | ${{ fullKey: 'browse-page.all-no-results', resultsCount: 0, localeCount: '0' }}
+ ${1} | ${{ fullKey: 'browse-page.all-result-count', resultsCount: 1, localeCount: '1' }}
+ ${10} | ${{ fullKey: 'browse-page.all-result-count', resultsCount: 10, localeCount: '10' }}
+ ${10000} | ${{ fullKey: 'browse-page.all-result-count-more', resultsCount: 10000, localeCount: '10,000' }}
+ `(
+ 'Should show correct result for $resultCount of type $mediaType',
+ ({ resultCount, expectedResult }) => {
+ const { getI18nCount } = useI18nResultsCount()
+ const result = getI18nCount(resultCount)
+
+ expect(result).toEqual(expectedResult)
+ }
+ )
+})