Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Add ImageGrid component and use it for RelatedImages (#281)
Olga Bulat62d20fde56e2
diff --git a/nuxt.config.js b/nuxt.config.jsindex 2181ccbdb..88e79130c 100644--- a/nuxt.config.js+++ b/nuxt.config.js@@ -130,6 +130,7 @@ export default {'~/components/ContentReport','~/components/Filters','~/components/ImageDetails',+ '~/components/ImageGrid','~/components/MediaInfo','~/components/MetaSearch','~/components/MediaTag',diff --git a/src/components/AudioDetails/Related.vue b/src/components/AudioDetails/Related.vueindex b3c10dfdf..b72d77ac8 100644--- a/src/components/AudioDetails/Related.vue+++ b/src/components/AudioDetails/Related.vue@@ -3,22 +3,56 @@<h4 class="b-header mb-6">{{ $t('audio-details.related-audios') }}</h4>- <AudioTrack- v-for="audio in relatedAudios"- :key="audio.id"- :audio="audio"- :is-compact="true"- layout="row"- class="mb-12"- />+ <template v-if="!$fetchState.error">+ <AudioTrack+ v-for="audio in audios"+ :key="audio.id"+ :audio="audio"+ layout="row"+ size="m"+ class="mb-12"+ />+ <LoadingIcon v-show="$fetchState.pending" />+ </template>+ <p v-show="!!$fetchState.error">+ {{ $t('media-details.related-error') }}+ </p></aside></template><script>+import { ref } from '@nuxtjs/composition-api'+import { AUDIO } from '~/constants/media'+import useRelated from '~/composables/use-related'+export default {name: 'RelatedAudios',props: {- relatedAudios: {},+ audioId: {+ type: String,+ required: true,+ },+ service: {},+ },+ /**+ * Fetches related audios on `audioId` change+ * @param {object} props+ * @param {string} props.audioId+ * @param {any} props.service+ * @return {{ audios: Ref<AudioDetail[]> }}+ */+ setup(props) {+ const mainAudioId = ref(props.audioId)+ const relatedOptions = {+ mediaType: AUDIO,+ mediaId: mainAudioId,+ }+ // Using service prop to be able to mock when testing+ if (props.service) {+ relatedOptions.service = props.service+ }+ const { media: audios } = useRelated(relatedOptions)+ return { audios }},}</script>diff --git a/src/components/ImageDetails/RelatedImages.vue b/src/components/ImageDetails/RelatedImages.vuenew file mode 100644index 000000000..b3daaaaf7--- /dev/null+++ b/src/components/ImageDetails/RelatedImages.vue@@ -0,0 +1,57 @@+<template>+ <aside+ :aria-label="$t('photo-details.aria.related')"+ class="p-4 my-6 photo_related-images"+ >+ <h3 class="b-header">+ {{ $t('photo-details.related-images') }}+ </h3>+ <ImageGrid+ :images="images"+ :can-load-more="false"+ :is-fetching="$fetchState.pending"+ :fetching-error="$fetchState.error"+ :error-message-text="null"+ />+ </aside>+</template>++<script>+import { ref } from '@nuxtjs/composition-api'+import useRelated from '~/composables/use-related'+import { IMAGE } from '~/constants/media'+import ImageGrid from '~/components/ImageGrid/ImageGrid'++export default {+ name: 'RelatedImages',+ components: { ImageGrid },+ props: {+ imageId: {+ type: String,+ required: true,+ },+ service: {},+ },+ /**+ * Fetches related images on `imageId` change+ * @param {object} props+ * @param {string} props.imageId+ * @param {any} props.service+ * @return {{ images: Ref<ImageDetail[]> }}+ */+ setup(props) {+ const mainImageId = ref(props.imageId)+ const relatedOptions = {+ mediaType: IMAGE,+ mediaId: mainImageId,+ }+ // Using service prop to be able to mock when testing+ if (props.service) {+ relatedOptions.service = props.service+ }+ const { media: images } = useRelated(relatedOptions)++ return { images }+ },+}+</script>diff --git a/src/components/ImageGrid/ImageCell.vue b/src/components/ImageGrid/ImageCell.vuenew file mode 100644index 000000000..635eda874--- /dev/null+++ b/src/components/ImageGrid/ImageCell.vue@@ -0,0 +1,223 @@+<template>+ <div+ :aria-label="image.title"+ class="search-grid_item-container"+ :style="`width: ${containerAspect * widthBasis}px;+ flex-grow: ${containerAspect * widthBasis}`"+ >+ <figure class="search-grid_item">+ <i :style="`padding-bottom:${iPadding}%`" />+ <NuxtLink+ :to="localePath('/photos/' + image.id)"+ class="search-grid_image-ctr"+ :style="`width: ${imageWidth}%; top: ${imageTop}%; left:${imageLeft}%;`"+ @click="onGotoDetailPage($event, image)"+ >+ <img+ ref="img"+ loading="lazy"+ :class="{+ 'search-grid_image': true,+ 'search-grid_image__fill': !shouldContainImage,+ }"+ :alt="image.title"+ :src="getImageUrl(image)"+ @load="getImgDimension"+ @error="onImageLoadError($event, image)"+ />+ </NuxtLink>+ <figcaption class="overlay overlay__top p-2">+ <LicenseIcons :license="image.license" />+ </figcaption>+ <figcaption class="overlay overlay__bottom py-2 px-4">+ <span class="caption font-semibold">{{ image.title }}</span>+ </figcaption>+ </figure>+ </div>+</template>++<script>+import getProviderLogo from '~/utils/get-provider-logo'++const errorImage = require('~/assets/image_not_available_placeholder.png')++const minAspect = 3 / 4+const maxAspect = 16 / 9+const panaromaAspect = 21 / 9+const minRowWidth = 450++const toAbsolutePath = (url, prefix = 'https://') => {+ if (url.indexOf('http://') >= 0 || url.indexOf('https://') >= 0) {+ return url+ }+ return `${prefix}${url}`+}++export default {+ name: 'ImageCell',+ props: ['image', 'shouldContainImage'],+ data() {+ return {+ widthBasis: minRowWidth / maxAspect,+ imgHeight: this.image.height || 100,+ imgWidth: this.image.width || 100,+ }+ },+ computed: {+ imageAspect() {+ return this.imgWidth / this.imgHeight+ },+ containerAspect() {+ if (this.imageAspect > maxAspect) return maxAspect+ if (this.imageAspect < minAspect) return minAspect+ return this.imageAspect+ },+ iPadding() {+ if (this.imageAspect < minAspect) return (1 / minAspect) * 100+ if (this.imageAspect > maxAspect) return (1 / maxAspect) * 100+ return (1 / this.imageAspect) * 100+ },+ imageWidth() {+ if (this.imageAspect < maxAspect) return 100+ return (this.imageAspect / maxAspect) * 100+ },+ imageTop() {+ if (this.imageAspect > minAspect) return 0+ return (+ ((minAspect - this.imageAspect) /+ (this.imageAspect * minAspect * minAspect)) *+ -50+ )+ },+ imageLeft() {+ if (this.imageAspect < maxAspect) return 0+ return ((this.imageAspect - maxAspect) / maxAspect) * -50+ },+ },+ methods: {+ getImageUrl(image) {+ if (!image) {+ return ''+ }+ const url = image.thumbnail || image.url+ if (this.imageAspect > panaromaAspect) return toAbsolutePath(url)+ return toAbsolutePath(url)+ },+ getImageForeignUrl(image) {+ return toAbsolutePath(image.foreign_landing_url)+ },+ getProviderLogo(providerName) {+ return getProviderLogo(providerName)+ },+ onGotoDetailPage(event, image) {+ if (!event.metaKey && !event.ctrlKey) {+ event.preventDefault()+ const detailRoute = this.localeRoute({+ name: 'photo-detail-page',+ params: { id: image.id, location: window.scrollY },+ })+ this.$router.push(detailRoute)+ }+ },+ onImageLoadError(event, image) {+ const element = event.target+ if (element.src !== image.url) {+ element.src = image.url+ } else {+ element.src = errorImage+ }+ },+ getImgDimension(e) {+ this.imgHeight = e.target.naturalHeight+ this.imgWidth = e.target.naturalWidth+ },+ },+}+</script>++<!-- Add "scoped" attribute to limit CSS to this component only -->+<style lang="scss" scoped>+.search-grid_image-ctr {+ background: #ebece4;+ display: block;+ width: 100%;+}++.search-grid_item-container {+ margin: 10px;+}++.search-grid_item {+ position: relative;+ width: 100%;+ overflow: hidden;++ i {+ display: block;+ }++ a {+ position: absolute;+ vertical-align: bottom;+ img {+ width: 100%;+ }+ }++ &:hover .overlay {+ opacity: 1;+ bottom: 0;+ }+}++.overlay {+ position: absolute;+ opacity: 0;+ transition: all 0.4s ease;+ color: #fff;+ display: block;+ top: -100%;++ &__top {+ top: 0;+ width: 100%;+ height: 2rem;+ }++ &__bottom {+ background-color: #000;+ bottom: -100%;+ top: auto;+ text-overflow: ellipsis;+ white-space: nowrap;+ overflow: hidden;+ max-width: 100%;+ }++ // Show on touch devices+ @media (hover: none) {+ position: absolute;+ opacity: 1;+ bottom: 0;+ }+}++.search-grid_item {+ width: 100%;+ position: relative;+ display: block;+ float: left;+ flex: 0 0 auto;+ flex-grow: 1;+ cursor: pointer;+}++.search-grid_image {+ margin: auto;+ display: block;+}++.search-grid_image__fill {+ width: 100%;+}+</style>diff --git a/src/components/ImageGrid/ImageGrid.vue b/src/components/ImageGrid/ImageGrid.vuenew file mode 100644index 000000000..f2dbd6248--- /dev/null+++ b/src/components/ImageGrid/ImageGrid.vue@@ -0,0 +1,95 @@+<template>+ <section class="image-grid">+ <div class="image-grid__cells">+ <ImageCell v-for="(image, index) in images" :key="index" :image="image" />+ </div>+ <h5 v-if="isError" class="image-grid__notification py-4">+ {{ errorMessageText }}+ </h5>+ <LoadMoreButton+ v-if="canLoadMore"+ :is-error="isError"+ :is-fetching="isFetching"+ :is-finished="isFinished"+ data-testid="load-more"+ @onLoadMore="onLoadMoreImages"+ />+ </section>+</template>++<script>+/**+ * This component receives an array of images as prop, and+ * is responsible for displaying them as a grid.+ * It can also fetch more images when 'Load More' clicked,+ * or display 'No More Media'.+ * Used to display both image search results, and related images.+ */+import LoadMoreButton from '~/components/ImageGrid/LoadMoreButton'+import ImageCell from '~/components/ImageGrid/ImageCell'++export default {+ name: 'ImageGrid',+ components: { LoadMoreButton, ImageCell },+ props: {+ images: {+ default: () => [],+ },+ canLoadMore: {+ type: Boolean,+ default: true,+ },+ isFetching: {+ type: Boolean,+ default: false,+ },+ fetchingError: {+ default: null,+ },+ errorMessageText: {+ type: String,+ default: '',+ },+ isFinished: {+ type: Boolean,+ default: false,+ },+ },++ computed: {+ isError() {+ return !!this.fetchingError+ },+ fetchingErrorHeading() {+ const type = this.$t('browse-page.search-form.image')+ return this.$t('browse-page.fetching-error', { type })+ },+ },+ methods: {+ onLoadMoreImages() {+ this.$emit('onLoadMoreImages')+ },+ },+}+</script>++<style lang="scss" scoped>+.image-grid {+ &__notification {+ display: flex;+ justify-content: center;+ }+ &__cells {+ display: flex;+ flex-wrap: wrap;+ margin: 10px;++ @include tablet {+ &:after {+ content: '';+ flex-grow: 999999999;+ }+ }+ }+}+</style>diff --git a/src/components/ImageGrid/LoadMoreButton.vue b/src/components/ImageGrid/LoadMoreButton.vuenew file mode 100644index 000000000..ee1bd7f12--- /dev/null+++ b/src/components/ImageGrid/LoadMoreButton.vue@@ -0,0 +1,82 @@+<template>+ <div v-show="!isError" class="load-more pb-6">+ <button+ v-show="!isFetching"+ class="button"+ :disabled="isFinished"+ @click="onLoadMore"+ @keyup.enter="onLoadMore"+ >+ <span>{{ buttonLabel }}</span>+ </button>+ <LoadingIcon :should-show="isFetching" />+ </div>+</template>+<script>+import LoadingIcon from '~/components/LoadingIcon'++export default {+ name: 'LoadMoreButton',+ components: { LoadingIcon },+ props: {+ isFetching: {+ type: Boolean,+ default: true,+ },+ isFinished: {+ type: Boolean,+ default: false,+ },+ isError: {+ type: Boolean,+ default: false,+ },+ },+ computed: {+ finishedLabel() {+ const type = this.$t('browse-page.search-form.image')+ return this.$t('browse-page.no-more', { type })+ },+ buttonLabel() {+ return this.isFinished ? this.finishedLabel : this.$t('browse-page.load')+ },+ },+ methods: {+ onLoadMore() {+ this.$emit('onLoadMore')+ },+ },+}+</script>+<style lang="scss" scoped>+.load-more {+ display: flex;+ justify-content: center;+}+button {+ color: #23282d;+ margin-top: 2rem;+ border: 1px solid rgba(35, 40, 45, 0.2);+ font-size: 1.2em;++ &:hover {+ color: white;+ }++ &:disabled {+ opacity: 1;++ &:hover {+ color: black;+ }+ }++ @include mobile {+ padding: 0.5rem;++ span {+ font-size: 0.9rem;+ }+ }+}+</style>diff --git a/src/components/RelatedImages.vue b/src/components/RelatedImages.vuedeleted file mode 100644index ec27036d8..000000000--- a/src/components/RelatedImages.vue+++ /dev/null@@ -1,33 +0,0 @@-<template>- <aside- :aria-label="$t('photo-details.aria.related')"- class="p-4 my-6 photo_related-images"- >- <h3 class="b-header">- {{ $t('photo-details.related-images') }}- </h3>- <SearchGridManualLoad- v-if="isPrimaryImageLoaded === true"- :images-count="imagesCount"- :images="relatedImages"- :query="query"- :filter="filter"- :include-analytics="false"- :use-infinite-scroll="false"- :include-add-to-list="false"- />- </aside>-</template>--<script>-export default {- name: 'RelatedImages',- props: [- 'relatedImages',- 'imagesCount',- 'query',- 'filter',- 'isPrimaryImageLoaded',- ],-}-</script>diff --git a/src/composables/use-related.js b/src/composables/use-related.jsnew file mode 100644index 000000000..73e126d77--- /dev/null+++ b/src/composables/use-related.js@@ -0,0 +1,26 @@+import AudioService from '~/data/audio-service'+import ImageService from '~/data/image-service'+import { ref, useFetch } from '@nuxtjs/composition-api'+import { AUDIO, IMAGE } from '~/constants/media'++const services = { [AUDIO]: AudioService, [IMAGE]: ImageService }++export default function useRelated({+ mediaType,+ mediaId,+ service = services[mediaType],+}) {+ const media = ref([])+ // fetch and fetchState are available as this.$fetch and this.$fetchState+ // in components, so there's no need to export them,+ // see https://composition-api.nuxtjs.org/lifecycle/usefetch/+ // eslint-disable-next-line no-unused-vars+ const { fetch } = useFetch(async () => {+ const response = await service.getRelatedMedia({+ id: mediaId.value,+ })+ media.value = response.data.results+ })+ fetch()+ return { media }+}diff --git a/src/locales/en.json b/src/locales/en.jsonindex 3a7d06636..6ca154124 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -488,7 +488,8 @@},"provider-label": "Provider","source-label": "Source",- "loading": "Loading..."+ "loading": "Loading...",+ "related-error": "Error fetching related media"},"photo-details": {"back": "Back to search results",diff --git a/src/locales/po-files/openverse.pot b/src/locales/po-files/openverse.potindex cf5265ffa..48d19784a 100644--- a/src/locales/po-files/openverse.pot+++ b/src/locales/po-files/openverse.pot@@ -4,7 +4,7 @@ msgid ""msgstr """Project-Id-Version: Openverse \n""Report-Msgid-Bugs-To: https://github.com/wordpress/openverse/issues \n"-"POT-Creation-Date: 2021-10-05T11:03:37+00:00\n"+"POT-Creation-Date: 2021-10-06T12:05:17+00:00\n""MIME-Version: 1.0\n""Content-Type: text/plain; charset=UTF-8\n""Content-Transfer-Encoding: 8bit\n"@@ -948,7 +948,7 @@ msgid "An error occurred"msgstr ""#. Do not translate words between ### ###.-#: src/pages/photos/_id.vue:100+#: src/pages/photos/_id.vue:66msgctxt "error.image-not-found"msgid "Couldn't find image with id ###id###"msgstr ""@@ -1580,6 +1580,11 @@ msgctxt "feedback.loading"msgid "Loading..."msgstr ""+#: src/components/AudioDetails/Related.vue:51+msgctxt "media-details.related-error"+msgid "Error fetching related media"+msgstr ""+#: src/components/ImageDetails/PhotoDetails.vue:12msgctxt "photo-details.back"msgid "Back to search results"diff --git a/src/locales/scripts/valid-locales.json b/src/locales/scripts/valid-locales.jsonindex 6b22b5200..d808b5ff4 100644--- a/src/locales/scripts/valid-locales.json+++ b/src/locales/scripts/valid-locales.json@@ -20,6 +20,13 @@"wpLocale": "en_AU","file": "en-au.json"},+ {+ "code": "en-ca",+ "name": "English (Canada)",+ "iso": "en",+ "wpLocale": "en_CA",+ "file": "en-ca.json"+ },{"code": "en-gb","name": "English (UK)",diff --git a/src/pages/audio/_id.vue b/src/pages/audio/_id.vueindex 7620b00d5..48055bd80 100644--- a/src/pages/audio/_id.vue+++ b/src/pages/audio/_id.vue@@ -15,21 +15,16 @@class="my-16 px-4 desk:px-0"/><AudioDetailsRelated- v-if="!$fetchState.pending"- :related-audios="relatedAudios"+ v-if="audio.id"class="my-16 px-4 desk:px-0"+ :audio-id="audio.id"/>- <p v-else>{{ $t('media-details.loading') }}</p></div></template><script>import { mapActions, mapState } from 'vuex'-import {- FETCH_AUDIO,- FETCH_RELATED_MEDIA,- RESET_RELATED_MEDIA,-} from '~/constants/action-types'+import { FETCH_AUDIO } from '~/constants/action-types'import iframeHeight from '~/mixins/iframe-height'import { AUDIO } from '~/constants/media'import attributionHtml from '~/utils/attribution-html'@@ -48,20 +43,17 @@ const AudioDetailPage = {thumbnailURL: null,breadCrumbURL: '',shouldShowBreadcrumb: false,+ id: null,}},computed: {...mapState(['query', 'audio']),- ...mapState('related', { relatedAudios: 'audios' }),filter() {return this.query.filter},tags() {return this.audio.tags},- relatedAudiosCount() {- return this.relatedAudios.length- },fullLicenseName() {return getFullLicenseName(this.audio.license, this.audio.license_version)},@@ -70,20 +62,11 @@ const AudioDetailPage = {},},watch: {- audio() {- this.getRelatedAudios()+ audio(newAudio) {+ this.id = newAudio.id},},- async fetch() {- // Load the related images- await this[FETCH_RELATED_MEDIA]({- mediaType: AUDIO,- id: this.$route.params.id,- })- },async asyncData({ env, store, route, error, app }) {- // Clear related audios if present- await store.dispatch(RESET_RELATED_MEDIA, { mediaType: AUDIO })try {await store.dispatch(FETCH_AUDIO, { id: route.params.id })return {@@ -109,16 +92,11 @@ const AudioDetailPage = {})},methods: {- ...mapActions([FETCH_AUDIO, FETCH_RELATED_MEDIA]),+ ...mapActions([FETCH_AUDIO]),attributionHtml() {const licenseUrl = `${this.licenseUrl}&atype=html`return attributionHtml(this.audio, licenseUrl, this.fullLicenseName)},- getRelatedAudios() {- if (this.audio && this.audio.id) {- this[FETCH_RELATED_MEDIA]({ mediaType: AUDIO, id: this.audio.id })- }- },},}diff --git a/src/pages/photos/_id.vue b/src/pages/photos/_id.vueindex 8e8511fe7..e4d3a9c5e 100644--- a/src/pages/photos/_id.vue+++ b/src/pages/photos/_id.vue@@ -11,24 +11,15 @@:image-type="imageType"@onImageLoaded="onImageLoaded"/>- <PhotoTags :tags="tags" :show-header="true" class="p-4 my-6" />- <RelatedImages- :related-images="relatedImages"- :images-count="relatedImagesCount"- :query="query"- :filter="filter"- :is-primary-image-loaded="isPrimaryImageLoaded"- />+ <RelatedImages :image-id="imageId" /></div></template><script>import axios from 'axios'import { mapActions, mapMutations, mapState } from 'vuex'-import { FETCH_IMAGE, FETCH_RELATED_MEDIA } from '~/constants/action-types'-import { SET_IMAGE, SET_RELATED_MEDIA } from '~/constants/mutation-types'-import { IMAGE } from '~/constants/media'-import { RELATED } from '~/constants/store-modules'+import { FETCH_IMAGE } from '~/constants/action-types'+import { SET_IMAGE } from '~/constants/mutation-types'const PhotoDetailPage = {name: 'PhotoDetailPage',@@ -37,12 +28,6 @@ const PhotoDetailPage = {? 'embedded-with-nav-search': 'with-nav-search'},- props: {- id: {- type: String,- default: '',- },- },data() {return {breadCrumbURL: '',@@ -52,6 +37,8 @@ const PhotoDetailPage = {imageWidth: 0,imageHeight: 0,imageType: 'Unknown',+ thumbnailURL: '',+ imageId: null,}},computed: {@@ -62,42 +49,23 @@ const PhotoDetailPage = {tags() {return this.image.tags},- relatedImages() {- return this.$store.state.related.images- },- relatedImagesCount() {- return this.relatedImages.length- },- },- watch: {- image() {- this.getRelatedImages()- },},async asyncData({ env, route }) {- return { thumbnailURL: `${env.apiUrl}thumbs/${route.params.id}` }- },- async fetch({ store, route, error, app }) {- // Clear related images if present- if (store.state.related.images && store.state.related.images.length > 0) {- store.commit(`${RELATED}/${SET_RELATED_MEDIA}`, {- mediaType: IMAGE,- relatedMedia: [],- })+ return {+ thumbnailURL: `${env.apiUrl}thumbs/${route.params.id}`,+ imageId: route.params.id,}+ },+ async fetch() {try {- // Load the image + related images in parallel- await Promise.all([- store.dispatch(`${FETCH_IMAGE}`, { id: route.params.id }),- store.dispatch(`${RELATED}/${FETCH_RELATED_MEDIA}`, {- mediaType: IMAGE,- id: route.params.id,- }),- ])+ // Load the image+ await this.$store.dispatch(`${FETCH_IMAGE}`, { id: this.imageId })} catch (err) {- error({+ this.$nuxt.error({statusCode: 404,- message: app.i18n.t('error.image-not-found', { id: route.params.id }),+ message: this.$t('error.image-not-found', {+ id: this.imageId,+ }).toString(),})}},@@ -110,7 +78,6 @@ const PhotoDetailPage = {})},methods: {- ...mapActions({ fetchRelatedMedia: `${RELATED}/${FETCH_RELATED_MEDIA}` }),...mapActions([FETCH_IMAGE]),...mapMutations([SET_IMAGE]),onImageLoaded(event) {@@ -121,11 +88,6 @@ const PhotoDetailPage = {this.imageType = res.headers['content-type']})},- getRelatedImages() {- if (this.image && this.image.id) {- this.fetchRelatedMedia({ mediaType: IMAGE, id: this.image.id })- }- },},}diff --git a/src/store/related.js b/src/store/related.jsdeleted file mode 100644index 86ceeac32..000000000--- a/src/store/related.js+++ /dev/null@@ -1,82 +0,0 @@-import {- FETCH_END_MEDIA,- FETCH_START_MEDIA,- SET_RELATED_MEDIA,-} from '~/constants/mutation-types'-import {- FETCH_RELATED_MEDIA,- HANDLE_NO_MEDIA,- HANDLE_MEDIA_ERROR,-} from '~/constants/action-types'-import AudioService from '~/data/audio-service'-import ImageService from '~/data/image-service'-import { AUDIO, IMAGE } from '~/constants/media'--export const state = () => ({- images: [],- audios: [],-})--export const createActions = (services) => ({- [FETCH_RELATED_MEDIA]({ commit, dispatch }, params) {- const { mediaType } = params- commit(FETCH_START_MEDIA, { mediaType }, { root: true })- if (!Object.keys(services).includes(mediaType)) {- throw new Error(- `Unsupported media type ${mediaType} for related media fetching`- )- }- const service = services[mediaType]- return service- .getRelatedMedia(params)- .then(({ data }) => {- commit(FETCH_END_MEDIA, { mediaType }, { root: true })- commit(SET_RELATED_MEDIA, {- mediaType,- relatedMedia: data.results,- })- dispatch(- HANDLE_NO_MEDIA,- {- mediaCount: data.results.length,- mediaType,- },- { root: true }- )- })- .catch((error) => {- dispatch(- HANDLE_MEDIA_ERROR,- {- mediaType,- error,- },- { root: true }- )- })- },-})--const services = {- [AUDIO]: AudioService,- [IMAGE]: ImageService,-}--export const actions = createActions(services)--export const mutations = {- /**- * @param _state- * @param {'image'|'audio'} mediaType- * @param {Array} relatedMedia- */- [SET_RELATED_MEDIA](_state, { mediaType, relatedMedia }) {- _state[`${mediaType}s`] = relatedMedia- },-}--export default {- state,- mutations,- actions,-}diff --git a/test/unit/specs/components/image-grid.spec.js b/test/unit/specs/components/image-grid.spec.jsnew file mode 100644index 000000000..6e3ba6952--- /dev/null+++ b/test/unit/specs/components/image-grid.spec.js@@ -0,0 +1,46 @@+import ImageGrid from '~/components/ImageGrid/ImageGrid'+import { render, screen } from '@testing-library/vue'++const propsData = {+ images: [+ { id: 'i1', url: 'http://localhost:8080/i1.png', title: 'image1' },+ { id: 'i2', url: 'http://localhost:8080/i2.jpg', title: 'image2' },+ { id: 'i3', url: 'http://localhost:8080/i3.svg', title: 'image3' },+ ],+ canLoadMore: false,+}+const options = {+ props: propsData,+ stubs: ['NuxtLink', 'LicenseIcons'],+}+describe('ImageGrid', () => {+ it('renders images without load more button if canLoadMore is false', () => {+ options.props.canLoadMore = false+ render(ImageGrid, options)+ expect(screen.queryAllByRole('img').length).toEqual(propsData.images.length)+ expect(screen.queryAllByRole('figure').length).toEqual(+ propsData.images.length+ )+ expect(screen.queryByRole('button')).not.toBeInTheDocument()+ })++ it('renders images and load more button if canLoadMore is true', async () => {+ options.props.canLoadMore = true+ render(ImageGrid, options)+ expect(screen.queryAllByRole('img').length).toEqual(propsData.images.length)+ expect(screen.queryAllByRole('figure').length).toEqual(+ propsData.images.length+ )+ const loadMoreButton = screen.queryByRole('button')+ expect(loadMoreButton).toBeVisible()+ expect(loadMoreButton).toHaveTextContent('browse-page.load')+ })++ it('shows LoadingIcon instead of LoadMoreButton when isFetching', async () => {+ options.props.canLoadMore = true+ options.props.isFetching = true+ render(ImageGrid, options)+ // getByRole('button') does not find the button+ expect(screen.getByText('browse-page.load')).not.toBeVisible()+ })+})diff --git a/test/unit/specs/components/related-audios.spec.js b/test/unit/specs/components/related-audios.spec.jsnew file mode 100644index 000000000..288de7767--- /dev/null+++ b/test/unit/specs/components/related-audios.spec.js@@ -0,0 +1,46 @@+import RelatedAudios from '~/components/AudioDetails/Related'+import render from '../../test-utils/render'+import { createLocalVue, mount } from '@vue/test-utils'+import Vuex from 'vuex'+import VueI18n from 'vue-i18n'++const audioResults = [{ id: 'audio1' }, { id: 'audio2' }]+const serviceMock = {+ getRelatedMedia: jest.fn(() =>+ Promise.resolve({ data: { results: audioResults } })+ ),+}++const localVue = createLocalVue()+localVue.use(Vuex)+localVue.use(VueI18n)+localVue.prototype.$nuxt = {+ nbFetching: 0,+}++const doRender = async () => {+ return render(+ RelatedAudios,+ {+ localVue,+ propsData: { audioId: 'foo', service: serviceMock },+ mocks: { $fetchState: { pending: false, error: null, timestamp: null } },+ stubs: { LoadingIcon: true, AudioTrack: true },+ },+ mount+ )+}++describe('RelatedAudios', () => {+ it('should render content when finished loading related audios', async () => {+ const wrapper = await doRender()++ const header = wrapper.find('h4').text()+ expect(header).toEqual('audio-details.related-audios')++ const audioTracks = wrapper.findAll('audiotrack-stub')+ expect(audioTracks.length).toEqual(audioResults.length)++ expect(serviceMock.getRelatedMedia).toHaveBeenCalledTimes(1)+ })+})diff --git a/test/unit/specs/components/related-images.spec.js b/test/unit/specs/components/related-images.spec.jsindex bfc2a0379..bde9d3ac5 100644--- a/test/unit/specs/components/related-images.spec.js+++ b/test/unit/specs/components/related-images.spec.js@@ -1,14 +1,62 @@-import RelatedImage from '~/components/RelatedImages'-import render from '../../test-utils/render'+import Vuex from 'vuex'+import VueI18n from 'vue-i18n'+import { createLocalVue } from '@vue/test-utils'+import { render, screen } from '@testing-library/vue'+import RelatedImages from '~/components/ImageDetails/RelatedImages'++const serviceMock = jest.fn(() =>+ Promise.resolve({+ data: {+ results: [+ { id: 'img1', url: 'https://wp.org/img1.jpg' },+ { id: 'img2', url: 'https://wp.org/img2.jpg' },+ ],+ },+ })+)+const failedMock = jest.fn(() => Promise.reject('No result'))++const localVue = createLocalVue()+localVue.use(Vuex)+localVue.use(VueI18n)+// without nbFetching property on $nuxt, Nuxt's `fetch` hook throws an error:+// [Vue warn]: Error in beforeMount hook (Promise/async):+// "TypeError: Cannot read property 'nbFetching' of undefined"+localVue.prototype.$nuxt = {+ nbFetching: 0,+}describe('RelatedImage', () => {- it('should render content when related images are present', () => {- const options = {- propsData: {- relatedImages: ['img1', 'img2'],- },+ let props = null+ let options = null+ beforeEach(() => {+ props = {+ imageId: 'foo',+ service: { getRelatedMedia: serviceMock },+ }+ options = {+ localVue,+ propsData: props,+ stubs: ['LicenseIcons', 'NuxtLink'],}- const wrapper = render(RelatedImage, options)- expect(wrapper.find('.photo_related-images').element).toBeDefined()+ })+ it('should render an image grid', async () => {+ // await `render` to get the component after Nuxt's `fetch` call+ await render(RelatedImages, options)+ expect(screen.getByRole('heading').textContent).toContain(+ 'photo-details.related-images'+ )+ expect(screen.queryAllByRole('img').length).toEqual(2)+ expect(screen.queryAllByRole('figure').length).toEqual(2)+ })++ it('should not render data service rejects with an error', async () => {+ options.propsData.service.getRelatedMedia = failedMock+ // await `render` to get the component after Nuxt's `fetch` call+ await render(RelatedImages, options)+ expect(screen.getByRole('heading').textContent).toContain(+ 'photo-details.related-images'+ )+ expect(screen.queryAllByRole('img').length).toEqual(0)})})diff --git a/test/unit/specs/store/related-media-store.spec.js b/test/unit/specs/store/related-media-store.spec.jsdeleted file mode 100644index 03215d88e..000000000--- a/test/unit/specs/store/related-media-store.spec.js+++ /dev/null@@ -1,95 +0,0 @@-import store, { createActions } from '~/store/related'-import {- FETCH_END_MEDIA,- FETCH_START_MEDIA,- SET_RELATED_MEDIA,-} from '~/constants/mutation-types'-import { FETCH_RELATED_MEDIA } from '~/constants/action-types'-import { IMAGE } from '~/constants/media'--describe('Related Images Store', () => {- describe('state', () => {- it('exports default state', () => {- const state = store.state()- expect(state.audios).toHaveLength(0)- expect(state.images).toHaveLength(0)- })- })-- describe('mutations', () => {- let state = null- const mutations = store.mutations-- beforeEach(() => {- state = { images: [], audios: [] }- })-- it('SET_RELATED_MEDIA updates state', () => {- const params = {- mediaType: IMAGE,- relatedMedia: ['foo'],- }- mutations[SET_RELATED_MEDIA](state, params)- expect(state.images).toBe(params.relatedMedia)- })- })-- describe('actions', () => {- const searchData = { results: ['foo'], result_count: 1 }- let imageServiceMock = null- let commit = null- let dispatch = null-- beforeEach(() => {- imageServiceMock = {- getRelatedMedia: jest.fn(() => Promise.resolve({ data: searchData })),- }- commit = jest.fn()- dispatch = jest.fn()- })-- it('FETCH_RELATED_MEDIA on success', (done) => {- const params = { id: 'foo', mediaType: IMAGE }- const actions = createActions({- [IMAGE]: imageServiceMock,- })- const action = actions[FETCH_RELATED_MEDIA]- action({ commit, dispatch }, params).then(() => {- expect(commit).toBeCalledWith(- FETCH_START_MEDIA,- { mediaType: IMAGE },- { root: true }- )- expect(commit).toBeCalledWith(- FETCH_END_MEDIA,- { mediaType: IMAGE },- { root: true }- )-- expect(commit).toBeCalledWith(SET_RELATED_MEDIA, {- mediaType: IMAGE,- relatedMedia: searchData.results,- })-- expect(imageServiceMock.getRelatedMedia).toBeCalledWith(params)- done()- })- })-- it('FETCH_RELATED_IMAGES on error', (done) => {- const imageServiceMock = {- getRelatedMedia: jest.fn(() => Promise.reject('error')),- }- const params = { id: 'foo', mediaType: IMAGE }- const actions = createActions({- [IMAGE]: imageServiceMock,- })- const action = actions[FETCH_RELATED_MEDIA]- action({ commit, dispatch }, params).catch((error) => {- expect(commit).toBeCalledWith(FETCH_START_MEDIA, { mediaType: IMAGE })- expect(dispatch).toBeCalledWith('HANDLE_IMAGE_ERROR', error)- })- done()- })- })-})