Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Replace download button with foreign landing button (#1290)
sarayourfriendf4795981597c
diff --git a/package.json b/package.jsonindex 0d068bb8e..1c60faba8 100644--- a/package.json+++ b/package.json@@ -77,7 +77,6 @@"clipboard": "^2.0.8","core-js": "^3.16.1","express-useragent": "^1.0.15",- "filesize": "^8.0.2","focus-trap": "^6.7.1","focus-trap-vue": "1.1.1","focus-visible": "^5.2.0",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 21aa5eb15..00078bc63 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -56,7 +56,6 @@ specifiers:eslint-plugin-vue: ^8.6.0eslint-plugin-vuejs-accessibility: ^1.1.1express-useragent: ^1.0.15- filesize: ^8.0.2focus-trap: ^6.7.1focus-trap-vue: 1.1.1focus-visible: ^5.2.0@@ -119,7 +118,6 @@ dependencies:clipboard: 2.0.8core-js: 3.21.1express-useragent: 1.0.15- filesize: 8.0.6focus-trap: 6.7.1focus-trap-vue: [email protected]focus-visible: 5.2.0@@ -9977,11 +9975,6 @@ packages:/file-uri-to-path/1.0.0:resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==}- /filesize/8.0.6:- resolution: {integrity: sha512-sHvRqTiwdmcuzqet7iVwsbwF6UrV3wIgDf2SHNdY1Hgl8PC45HZg/0xtdw6U2izIV4lccnrY9ftl6wZFNdjYMg==}- engines: {node: '>= 0.4.0'}- dev: false-/fill-range/4.0.0:resolution: {integrity: sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=}engines: {node: '>=0.10.0'}diff --git a/src/components/VAudioTrack/layouts/VFullLayout.vue b/src/components/VAudioTrack/layouts/VFullLayout.vueindex f2c095dcc..0a2306519 100644--- a/src/components/VAudioTrack/layouts/VFullLayout.vue+++ b/src/components/VAudioTrack/layouts/VFullLayout.vue@@ -58,11 +58,14 @@</div></div>- <VDownloadButton- class="ms-auto order-1 lg:order-2"- :formats="getFormats(audio)"+ <VButton+ as="VLink"+ :href="audio.foreign_landing_url":size="isSmall ? 'small' : 'medium'"- />+ class="ms-auto order-1 lg:order-2 font-bold"+ >+ {{ $t('download-button.download') }}+ </VButton></div></div></template>@@ -70,13 +73,30 @@<script>import { computed, defineComponent } from '@nuxtjs/composition-api'-import VDownloadButton from '~/components/VDownloadButton.vue'+import VButton from '~/components/VButton.vue'import VLink from '~/components/VLink.vue'export default defineComponent({name: 'VFullLayout',- components: { VDownloadButton, VLink },- props: ['audio', 'size', 'status', 'currentTime'],+ components: { VButton, VLink },+ props: {+ audio: {+ type: Object,+ required: true,+ },+ size: {+ type: String,+ validation: (v) => ['s', 'm', 'l'].includes(v),+ },+ status: {+ type: String,+ validation: (v) => ['playing', 'played', 'paused'].includes(v),+ },+ currentTime: {+ type: Number,+ required: true,+ },+ },setup(props) {/*** Format the time as hh:mm:ss, dropping the hour part if it is zero.@@ -92,53 +112,10 @@ export default defineComponent({return '--:--'}- /**- * Returns specific display name for file format if there is a mapping for- * provider's format display names (like Jamendo's `mp32` -> `MP3 V0`).- * Otherwise, returns UpperCase format or ''- * @param {string} provider- * @param {string} [format]- */- const displayFormat = (provider, format) => {- const filetypeMappings = {- jamendo: { mp31: 'MP3 96kbs', mp32: 'MP3 V0' },- }- if (filetypeMappings[provider] && filetypeMappings[provider][format]) {- return filetypeMappings[provider][format]- }- return format ? format.toUpperCase() : ''- }-- /**- * Creates a list of { extension_name, download_url } objects- * for VDownloadButton.- *- * If there are `alt_files` then just use that list. Otherwise,- * create one using the preview URL.- *- * @param {AudioDetail} audio- */- const getFormats = (audio) => {- if (audio.alt_files?.length) {- return audio.alt_files.map((altFile) => ({- extension_name: displayFormat(audio.provider, altFile.filetype),- download_url: altFile.url,- }))- }-- return [- {- extension_name: displayFormat(audio.provider, audio.filetype),- download_url: audio.url,- },- ]- }-const isSmall = computed(() => props.size === 's')return {timeFmt,- getFormats,isSmall,}diff --git a/src/components/VDownloadButton.vue b/src/components/VDownloadButton.vuedeleted file mode 100644index 5ca088670..000000000--- a/src/components/VDownloadButton.vue+++ /dev/null@@ -1,140 +0,0 @@-<template>- <VDropdownButton- v-if="filesizes"- :dropdown-aria-label="$t('download-button.aria.dropdown-label')"- :is-single-item="formats.length === 1"- :size="size"- >- <template #default="{ buttonProps }">- <VLink- v-bind="buttonProps"- class="whitespace-nowrap"- :href="selectedFormat.download_url"- download=""- >- <span>{{ $t('download-button.download') }}</span>- <span class="ms-4 selected-format">- {{ selectedFormat.extension_name }}- </span>- <span class="ms-1 font-normal">{{- getFormatSize(selectedFormat.extension_name)- }}</span>- </VLink>- </template>-- <template- #items="{- activeItemClass,- itemClass,- itemA11yProps,- toggleOpen,- onItemKeydown,- }"- >- <ul>- <li v-for="format in formats" :key="format.name">- <button- class="flex justify-between w-full"- :class="[- itemClass,- selectedFormat.extension_name === format.extension_name- ? activeItemClass- : '',- ]"- type="button"- v-bind="itemA11yProps"- @click="- setSelectedFormat(format)- toggleOpen()- "- @keydown="onItemKeydown($event)"- >- <span class="font-bold me-2">{{ format.extension_name }}</span>- <span>{{ getFormatSize(format.extension_name) }}</span>- </button>- </li>- </ul>- </template>- </VDropdownButton>-</template>--<script>-import filesize from 'filesize'-import axios from 'axios'--import local from '~/utils/local'--import VDropdownButton from '~/components/VDropdownButton.vue'-import VLink from '~/components/VLink.vue'--const LS_DOWNLOAD_FORMAT_EXTENSION_KEY = 'openverse:download-format-extension'--export default {- name: 'VDownloadButton',- components: { VDropdownButton, VLink },- props: {- formats: {- type: Array,- required: true,- validator: (formats) => {- const properties = ['extension_name', 'download_url']- return formats.every((format) => properties.every((p) => p in format))- },- },- size: {- type: /** @type {import('@nuxtjs/composition-api').PropType<'medium' | 'small'>} */ (- String- ),- default: 'medium',- validator: (v) => ['medium', 'small'].includes(v),- },- },- data() {- const savedFormatExtension =- local.getItem(LS_DOWNLOAD_FORMAT_EXTENSION_KEY) ?? null- let format = this.formats[0]- if (savedFormatExtension) {- const found = this.formats.find(- (format) => format.extension_name === savedFormatExtension- )- if (found) {- format = found- }- }-- return { selectedFormat: format, filesizes: null }- },- async fetch() {- const extensionsToFilesizes = await Promise.all(- this.formats.map(async (format) => {- try {- const response = await axios.head(format.download_url)- return [format.extension_name, response.headers['content-length']]- } catch (e) {- return [format.extension_name, undefined]- }- })- )-- this.filesizes = extensionsToFilesizes.reduce(- (acc, [extensionName, filesize]) => ({- ...acc,- [extensionName]: filesize,- }),- {}- )- },- methods: {- getFormatSize(extensionName) {- const size = this.filesizes?.[extensionName] ?? undefined- if (typeof size === 'undefined') return ''-- return filesize(size, { locale: this.$i18n.locale })- },- setSelectedFormat(format) {- local.setItem(LS_DOWNLOAD_FORMAT_EXTENSION_KEY, format.extension_name)- this.selectedFormat = format- },- },-}-</script>diff --git a/src/components/VDropdownButton.vue b/src/components/VDropdownButton.vuedeleted file mode 100644index 72bcb59d7..000000000--- a/src/components/VDropdownButton.vue+++ /dev/null@@ -1,223 +0,0 @@-<template>- <div class="relative block max-w-min text-sm md:text-base">- <!-- rounded-X-none is required to fight Edge UA styles that apply a 2px border radius to all `button` elements -->- <div class="flex">- <slot- :button-props="{- class: `dropdown-button rounded-s-sm ${- isSingleItem ? 'rounded-e-sm' : 'rounded-e-none'- } dropdown-button-${size}`,- type: 'button',- }"- />- <button- v-if="!isSingleItem"- ref="dropdownButton"- type="button"- class="dropdown-button ms-1 rounded-e-sm rounded-s-none w-14"- :class="[- isOpen && 'dropdown-button-active',- `dropdown-icon-button-${size}`,- ]"- aria-haspopup="menu"- :aria-label="safeDropdownAriaLabel"- :aria-expanded="isOpen"- @click="toggleOpen"- @keydown.space.prevent="toggleOpen"- >- <VIcon :icon-path="icons.caretDown" />- </button>- </div>-- <div- ref="dropdownContainer"- class="dropdown-container"- :class="{ hidden: !isOpen }"- role="menu"- :aria-hidden="!isOpen"- @focusout="onFocusout"- >- <slot- name="items"- :item-class="'dropdown-item'"- :item-a11y-props="{ role: 'menuitem' }"- :toggle-open="toggleOpen"- :active-item-class="'dropdown-item-active'"- :on-item-keydown="onItemKeydown"- />- </div>- </div>-</template>--<script>-import { defineComponent } from '@nuxtjs/composition-api'--import { keycodes } from '~/constants/key-codes'--import VIcon from '~/components/VIcon/VIcon.vue'--import caretDown from '~/assets/icons/caret-down.svg'--const VDropdownButton = defineComponent({- name: 'VDropdownButton',- components: { VIcon },- props: {- dropdownAriaLabel: {- type: String,- required: false,- },- isSingleItem: {- type: Boolean,- required: false,- },- size: {- type: /** @type {import('@nuxtjs/composition-api').PropType<'medium' | 'small'>} */ (- String- ),- default: 'medium',- validator: (v) => ['medium', 'small'].includes(v),- },- },- data() {- return {- isOpen: false,- icons: {- caretDown,- },- safeDropdownAriaLabel:- this.dropdownAriaLabel || this.$t('dropdown-button.aria.arrow-label'),- }- },- computed: {- sizeClass() {- return `dropdown-button-${this.size}`- },- },- mounted() {- document.addEventListener('click', this.onClickout)- },- beforeDestroy() {- document.removeEventListener('click', this.onClickout)- },- methods: {- getItems() {- return Array.from(- this.$refs.dropdownContainer.querySelectorAll('[role="menuitem"]')- )- },- onClickout(event) {- if (- event.target !== this.$refs.dropdownButton &&- !this.$refs.dropdownContainer.contains(event.target)- ) {- this.isOpen = false- }- },- onFocusout(event) {- if (!this.$el.contains(event.relatedTarget)) {- this.toggleOpen()- }- },- toggleOpen() {- this.isOpen = !this.isOpen- if (this.isOpen) {- this.focusElement(this.getItems()[0])- } else {- this.focusElement(this.$refs.dropdownButton)- }- },- focusElement(element) {- window.setTimeout(() => element.focus(), 0)- },- onItemKeydown(event) {- const items = this.getItems()- const itemIndex = items.findIndex((item) => item === event.target)- switch (event.key) {- case keycodes.ArrowUp: {- if (itemIndex === 0) {- // don't do anything if pressing up on the first item- return- }- this.focusElement(items[itemIndex - 1])- break- }- case keycodes.ArrowDown: {- if (itemIndex === items.length - 1) {- // don't do anything if pressing down on the last item- return- }- this.focusElement(items[itemIndex + 1])- break- }- case keycodes.Escape: {- this.toggleOpen()- break- }- case keycodes.Home:- case keycodes.PageUp: {- this.focusElement(items[0])- break- }- case keycodes.End:- case keycodes.PageDown: {- this.focusElement(items[items.length - 1])- break- }- }- },- },-})--export default VDropdownButton-</script>--<style scoped>-.dropdown-button {- @apply flex items-center justify-center bg-pink text-white font-bold transition-shadow duration-100 ease-linear disabled:opacity-70 focus:outline-none focus-visible:ring focus-visible:ring-offset-2 focus-visible:ring-pink hover:bg-dark-pink no-underline appearance-none;-}--.dropdown-icon-button-medium,-.dropdown-button-medium {- @apply py-4 px-6 leading-6;-}--/*-Note the bespoke `py-[0.86rem]` class used below is necessary-to match the height of the small Audio play/pause button.--This is currently the only application of the DropdownButton-component (via the VDownloadButton component) so as a stop-gap-solution to get the redesign out the door in a timely manner it-is necessary.--In the future it would be nice to coordinate these sizes across-all our buttons, regardless of content (icon vs text for example)-so that don't have to worry about things like this. We should feel-free to use sizes like 0.86rem if they're the right size, but it is-good to avoid the long term effects of scattering too many ad-hoc-sizes throughout the codebase.-*/-.dropdown-button-small {- @apply px-4 py-[0.86rem] leading-3;-}--.dropdown-icon-button-small {- @apply px-0 py-[0.86rem] leading-3 w-10;-}--.dropdown-button-active {- @apply bg-dark-pink;-}--.dropdown-container {- @apply absolute right-0 z-50 bg-white border border-light-gray rounded-sm px-2 pt-2 pb-1 mt-2 max-w-min whitespace-nowrap shadow;-}--.dropdown-item {- @apply hover:bg-light-gray px-2 py-1 mb-1 rounded-sm focus:outline-none focus:ring focus:ring-offset-2 focus:ring-pink;-}--.dropdown-item-active {- @apply bg-light-gray;-}-</style>diff --git a/src/components/meta/VDownloadButton.stories.js b/src/components/meta/VDownloadButton.stories.jsdeleted file mode 100644index 677cb7d5c..000000000--- a/src/components/meta/VDownloadButton.stories.js+++ /dev/null@@ -1,31 +0,0 @@-import VDownloadButton from '~/components/VDownloadButton.vue'--export default {- title: 'Components/VDownloadButton',- component: VDownloadButton,-}--export const Default = () => ({- template: `<VDownloadButton :formats="formats" />`,- components: { VDownloadButton },- data: () => ({- formats: [- {- extension_name: 'MP3 98kbs',- download_url: 'https://mp3d.jamendo.com/download/track/1532771/mp31/',- },- {- extension_name: 'MP3 VBR',- download_url: 'https://mp3d.jamendo.com/download/track/1532771/mp32/',- },- {- extension_name: 'FLAC',- download_url: 'https://mp3d.jamendo.com/download/track/1532771/flac/',- },- {- extension_name: 'OGG',- download_url: 'https://mp3d.jamendo.com/download/track/1532771/ogg/',- },- ],- }),-})diff --git a/src/components/meta/VDropdownButton.stories.js b/src/components/meta/VDropdownButton.stories.jsdeleted file mode 100644index a6a9d258f..000000000--- a/src/components/meta/VDropdownButton.stories.js+++ /dev/null@@ -1,62 +0,0 @@-import { log } from '~/utils/console'--import VDropdownButton from '~/components/VDropdownButton.vue'--export default {- title: 'Components/VDropdownButton',- component: VDropdownButton,- argTypes: {- size: {- type: 'select',- options: ['medium', 'small'],- },- },-}--export const Default = (args, { argTypes }) => ({- template: `- <div>- <VDropdownButton v-bind="$props">- <template #default="{ buttonProps }">- <button v-bind="buttonProps" class="whitespace-nowrap" @click="onClick">Download {{ activeItem?.name ?? '' }}</button>- </template>-- <template #items="{ activeItemClass, itemClass, itemA11yProps, toggleOpen, onItemKeydown }">- <ul>- <li v-for="item in items" :key="item.name">- <button :class="{ [itemClass]: true, [activeItemClass]: item.active }" type="button" v-bind="itemA11yProps" @click="setActive(item); toggleOpen()" @keydown="onItemKeydown">{{ item.name }}</button>- </li>- </ul>- </template>- </VDropdownButton>- Test element below- </div>- `,- props: Object.keys(argTypes).filter((i) => i !== 'items'),- data() {- return {- items: [- { name: 'Item 1', active: false },- { name: 'Item 2', active: false },- ],- }- },- computed: {- activeItem() {- log(this)- return this.items.find((item) => item.active)- },- },- methods: {- onClick(event) {- log(event)- alert('clicked!')- },- setActive(toActivate) {- this.items = this.items.map((item) => ({- ...item,- active: item === toActivate,- }))- },- },-})diff --git a/src/locales/po-files/openverse.pot b/src/locales/po-files/openverse.potindex d7532db69..9e1331af4 100644--- a/src/locales/po-files/openverse.pot+++ b/src/locales/po-files/openverse.pot@@ -4,7 +4,7 @@ msgid ""msgstr """Project-Id-Version: Openverse \n""Report-Msgid-Bugs-To: https://github.com/wordpress/openverse/issues \n"-"POT-Creation-Date: 2022-04-15T05:40:30+00:00\n"+"POT-Creation-Date: 2022-04-18T13:47:09+00:00\n""MIME-Version: 1.0\n""Content-Type: text/plain; charset=UTF-8\n""Content-Transfer-Encoding: 8bit\n"@@ -98,12 +98,11 @@ msgctxt "modal.close"msgid "Close"msgstr ""-#: src/components/VDownloadButton.vue:15+#: src/components/VAudioTrack/layouts/VFullLayout.vue:67msgctxt "download-button.download"msgid "Download"msgstr ""-#: src/components/VDownloadButton.vue:4msgctxt "download-button.aria.dropdown-label"msgid "Select the download file format"msgstr ""@@ -125,7 +124,6 @@ msgctxt "migration-notice.read"msgid "Read more"msgstr ""-#: src/components/VDropdownButton.vue:88msgctxt "dropdown-button.aria.arrow-label"msgid "Dropdown"msgstr ""diff --git a/test/unit/fixtures/audio.js b/test/unit/fixtures/audio.jsnew file mode 100644index 000000000..84d035568--- /dev/null+++ b/test/unit/fixtures/audio.js@@ -0,0 +1,45 @@+export const getAudioObj = (overrides = {}) =>+ Object.assign(+ {+ id: 'e19345b8-6937-49f7-a0fd-03bf057efc28',+ title: 'La vie des bêtes',+ foreign_landing_url: 'https://www.jamendo.com/track/11188',+ creator: 'AS-POTIRONT!',+ creator_url: 'https://www.jamendo.com/artist/264/as-potiront',+ url: 'https://mp3d.jamendo.com/download/track/11188/mp32',+ license: 'by-nc-sa',+ license_version: '2.5',+ license_url: 'https://creativecommons.org/licenses/by-nc-sa/2.5/',+ provider: 'jamendo',+ source: 'jamendo',+ filetype: 'mp32',+ tags: [+ {+ name: 'vocal',+ },+ {+ name: 'male',+ },+ {+ name: 'speed_medium',+ },+ {+ name: 'party',+ },+ {+ name: 'cuivres',+ },+ ],+ fields_matched: ['tags.name'],+ thumbnail:+ 'https://localhost:8000/v1/audio/e19345b8-6937-49f7-a0fd-03bf057efc28/thumb',+ waveform:+ 'https://localhost:8000/v1/audio/e19345b8-6937-49f7-a0fd-03bf057efc28/waveform',+ genres: ['pop', 'rock', 'manouche'],+ detail_url:+ 'http://localhost:8000/v1/audio/e19345b8-6937-49f7-a0fd-03bf057efc28',+ related_url:+ 'http://localhost:8000/v1/audio/e19345b8-6937-49f7-a0fd-03bf057efc28/recommendations',+ },+ overrides+ )diff --git a/test/unit/specs/components/AudioTrack/v-audio-track.spec.js b/test/unit/specs/components/AudioTrack/v-audio-track.spec.jsindex 8ab8db572..850cdadfa 100644--- a/test/unit/specs/components/AudioTrack/v-audio-track.spec.js+++ b/test/unit/specs/components/AudioTrack/v-audio-track.spec.js@@ -2,6 +2,8 @@ import { render } from '@testing-library/vue'import Vuei18n from 'vue-i18n'import { setActivePinia, createPinia, PiniaVuePlugin } from 'pinia'+import { getAudioObj } from '~~/test/unit/fixtures/audio'+import { useActiveMediaStore } from '~/stores/active-media'import VAudioTrack from '~/components/VAudioTrack/VAudioTrack.vue'@@ -55,7 +57,6 @@ const configureVue = (vue) => {}const stubs = {- VDownloadButton: true,VPlayPause: true,NuxtLink: true,VLicense: true,@@ -68,47 +69,7 @@ describe('AudioTrack', () => {beforeEach(() => {props = {- audio: {- id: 'e19345b8-6937-49f7-a0fd-03bf057efc28',- title: 'La vie des bêtes',- foreign_landing_url: 'https://www.jamendo.com/track/11188',- creator: 'AS-POTIRONT!',- creator_url: 'https://www.jamendo.com/artist/264/as-potiront',- url: 'https://mp3d.jamendo.com/download/track/11188/mp32',- license: 'by-nc-sa',- license_version: '2.5',- license_url: 'https://creativecommons.org/licenses/by-nc-sa/2.5/',- provider: 'jamendo',- source: 'jamendo',- filetype: 'mp32',- tags: [- {- name: 'vocal',- },- {- name: 'male',- },- {- name: 'speed_medium',- },- {- name: 'party',- },- {- name: 'cuivres',- },- ],- fields_matched: ['tags.name'],- thumbnail:- 'https://localhost:8000/v1/audio/e19345b8-6937-49f7-a0fd-03bf057efc28/thumb',- waveform:- 'https://localhost:8000/v1/audio/e19345b8-6937-49f7-a0fd-03bf057efc28/waveform',- genres: ['pop', 'rock', 'manouche'],- detail_url:- 'http://localhost:8000/v1/audio/e19345b8-6937-49f7-a0fd-03bf057efc28',- related_url:- 'http://localhost:8000/v1/audio/e19345b8-6937-49f7-a0fd-03bf057efc28/recommendations',- },+ audio: getAudioObj(),}options = {diff --git a/test/unit/specs/components/AudioTrack/v-full-layout.spec.js b/test/unit/specs/components/AudioTrack/v-full-layout.spec.jsnew file mode 100644index 000000000..e89aadca5--- /dev/null+++ b/test/unit/specs/components/AudioTrack/v-full-layout.spec.js@@ -0,0 +1,22 @@+import { render, screen } from '@testing-library/vue'++import { getAudioObj } from '~~/test/unit/fixtures/audio'++import VFullLayout from '~/components/VAudioTrack/layouts/VFullLayout.vue'++describe('VFullLayout', () => {+ it('should render the download button with the foreign landing url', () => {+ const audio = getAudioObj()+ render(VFullLayout, {+ props: {+ audio,+ size: 's',+ status: 'playing',+ currentTime: 1,+ },+ })++ const downloadButton = screen.getByText('download-button.download')+ expect(downloadButton).toHaveAttribute('href', audio.foreign_landing_url)+ })+})diff --git a/test/unit/specs/components/v-download-button.spec.js b/test/unit/specs/components/v-download-button.spec.jsdeleted file mode 100644index 57c4a776d..000000000--- a/test/unit/specs/components/v-download-button.spec.js+++ /dev/null@@ -1,98 +0,0 @@-import { mount } from '@vue/test-utils'-import axios from 'axios'-import MockAdapter from 'axios-mock-adapter'--import local from '~/utils/local'--import VDownloadButton from '~/components/VDownloadButton.vue'--import render from '../../test-utils/render'--jest.mock('~/utils/local', () => ({- getItem: jest.fn(),- setItem: jest.fn(),-}))--const mockFilesizes = {- 'MP3 98kbs': 1000,- 'MP3 VBR': 1500,- FLAC: 2500,- OGG: 2000,-}--const formats = [- {- extension_name: 'MP3 98kbs',- download_url: 'https://mp3d.jamendo.com/download/track/1532771/mp31/',- },- {- extension_name: 'MP3 VBR',- download_url: 'https://mp3d.jamendo.com/download/track/1532771/mp32/',- },- {- extension_name: 'FLAC',- download_url: 'https://mp3d.jamendo.com/download/track/1532771/flac/',- },- {- extension_name: 'OGG',- download_url: 'https://mp3d.jamendo.com/download/track/1532771/ogg/',- },-]--const mockAxios = new MockAdapter(axios)--formats.forEach((format) =>- mockAxios- .onHead(format.download_url)- .reply(() => [- 200,- {},- { 'content-length': mockFilesizes[format.extension_name] },- ])-)--const doRender = async () => {- const wrapper = render(VDownloadButton, { propsData: { formats } }, mount)- await VDownloadButton.fetch.call(wrapper.vm)- return wrapper-}--describe('VDownloadButton', () => {- beforeEach(() => {- mockAxios.resetHistory()- })-- // TODO(@sarayourfriend) convert this to testing-library once it's possible to get the `vm` from the wrapper- it('should default to the first format', async () => {- const wrapper = await doRender()- const downloadLink = wrapper.element.querySelector('a')- expect(downloadLink.getAttribute('href')).toEqual(formats[0].download_url)- })-- it('should use the local storage default on first render', async () => {- local.getItem.mockImplementationOnce(() => formats[1].extension_name)- const wrapper = await doRender()- const downloadLink = wrapper.element.querySelector('a')- expect(downloadLink.getAttribute('href')).toEqual(formats[1].download_url)- })-- it('should set the local storage default when a format is selected', async () => {- const wrapper = await doRender()- wrapper.find('[aria-haspopup="menu"]').trigger('click')- wrapper.findAll('[role="menuitem"]').wrappers[1].trigger('click')- expect(local.setItem).toHaveBeenCalledWith(- expect.any(String),- formats[1].extension_name- )- })-- it('should retrieve the filesizes using a head request', async () => {- await doRender()- expect(mockAxios.history.head.length).toBe(4) // there are four formats to check- formats.forEach(({ download_url }) =>- expect(- mockAxios.history.head.find((request) => request.url === download_url)- ).toBeDefined()- )- })-})diff --git a/test/unit/specs/components/v-dropdown-button.spec.js b/test/unit/specs/components/v-dropdown-button.spec.jsdeleted file mode 100644index e5cebd69b..000000000--- a/test/unit/specs/components/v-dropdown-button.spec.js+++ /dev/null@@ -1,133 +0,0 @@-import Vue from 'vue'-import { render, screen, fireEvent } from '@testing-library/vue'-import userEvent from '@testing-library/user-event'--import VDropdownButton from '~/components/VDropdownButton.vue'--const TestWrapper = Vue.component('TestWrapper', {- components: { VDropdownButton },- data: () => ({- items: new Array(4)- .fill(null)- .map((_, i) => ({ name: `Item ${i}`, active: false })),- }),- computed: {- activeItem() {- return this.items.find((item) => item.active)- },- },- methods: {- setActive(toActivate) {- this.items = this.items.map((item) => ({- ...item,- active: item === toActivate,- }))- },- },- template: `- <VDropdownButton>- <template #default="{ buttonProps }">- <button v-bind="buttonProps">Action {{ activeItem?.name ?? '' }}</button>- </template>-- <template #items="{ activeItemClass, itemClass, itemA11yProps, toggleOpen, onItemKeydown }">- <ul>- <li v-for="item in items" :key="item.name">- <button :class="{ [itemClass]: true, [activeItemClass]: item.active }" type="button" v-bind="itemA11yProps" @click="setActive(item); toggleOpen()" @keydown="onItemKeydown">{{ item.name }}</button>- </li>- </ul>- </template>- </VDropdownButton>- `,-})--const getVDropdownButton = () =>- screen.getByLabelText('dropdown-button.aria.arrow-label')-const getDropdownContainer = () => screen.queryByRole('menu')-const getFirstDropdownItem = () => screen.getAllByRole('menuitem')[0]-const getLastDropdownItem = () => screen.getAllByRole('menuitem').slice(-1)[0]-const getDropdownItem = (idx) => screen.getAllByRole('menuitem')[idx]--const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))--const openDropdown = async () => {- await fireEvent.click(getVDropdownButton())- // sleep for 1 ms to allow focus to settle- await sleep(1)-}--describe('VDropdownButton', () => {- it('should render a clickable dropdown button', async () => {- render(TestWrapper)- await openDropdown()- expect(getDropdownContainer()).not.toBe(null)- })-- it('should not render the dropdown by default', () => {- render(TestWrapper)- expect(getDropdownContainer()).toBe(null)- })-- it('should close the dropdown when clicking an item', async () => {- // this test verges on the edge of testing the implementation of the test wrappper, but the important part is that the test wrapper calls `toggleOpen` and we want to test that it will close the dropdown- render(TestWrapper)- await openDropdown()- await userEvent.click(getFirstDropdownItem())- expect(getDropdownContainer()).toBe(null)- })-- it('should focus the first item when dropdown is open', async () => {- render(TestWrapper)- await openDropdown()- expect(getFirstDropdownItem()).toHaveFocus()- })-- it('should allow keyboard navigation in the dropdown', async () => {- render(TestWrapper)- await openDropdown()- expect(getFirstDropdownItem()).toHaveFocus()- await userEvent.keyboard('{arrowdown}')- await sleep(1)- expect(getDropdownItem(1)).toHaveFocus()-- await userEvent.keyboard('{arrowup}')- await sleep(1)- expect(getFirstDropdownItem()).toHaveFocus()-- await userEvent.keyboard('{end}')- await sleep(1)- expect(getLastDropdownItem()).toHaveFocus()-- await userEvent.keyboard('{home}')- await sleep(1)- expect(getFirstDropdownItem()).toHaveFocus()-- // pageup/pagedown don't exist in userEvent :(- })-- it('should close the dropdown if Escape is pressed and return focus', async () => {- render(TestWrapper)- await openDropdown()- expect(getFirstDropdownItem()).toHaveFocus()- await userEvent.keyboard('{escape}')- await sleep(1)- expect(getVDropdownButton()).toHaveFocus()- })-- it('should open the dropdown with space', async () => {- render(TestWrapper)- getVDropdownButton().focus()- await userEvent.keyboard('{space}')- await sleep(1)- expect(getDropdownContainer()).not.toBe(null)- })-- // This test doesn't work for some reason, but testing in storybook confirms it should pass- it.skip('should open the dropdown with enter', async () => {- render(TestWrapper)- getVDropdownButton().focus()- await userEvent.keyboard('{enter}')- await sleep(1)- expect(getDropdownContainer()).not.toBe(null)- })-})