Skip to content

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

Use cookie for banners state (#1957)

Olga Bulat4bd35dc8f7e7
diff --git a/src/components/VBanner/VBanners.vue b/src/components/VBanner/VBanners.vue
new file mode 100644
index 000000000..c22bf77b5
--- /dev/null
+++ b/src/components/VBanner/VBanners.vue
@@ -0,0 +1,49 @@
+<template>
+ <div>
+ <VMigrationNotice
+ v-if="shouldShowMigrationBanner"
+ @close="dismissBanner('cc-referral')"
+ />
+ <VTranslationStatusBanner
+ v-if="shouldShowTranslationBanner"
+ :banner-key="translationBannerId"
+ @close="dismissBanner(translationBannerId)"
+ />
+ </div>
+</template>
+
+<script lang="ts">
+import { computed, defineComponent } from '@nuxtjs/composition-api'
+
+import { useUiStore } from '~/stores/ui'
+import { TranslationBannerId } from '~/types/banners'
+
+export default defineComponent({
+ name: 'VBanners',
+ components: {
+ VMigrationNotice: () => import('~/components/VBanner/VMigrationNotice.vue'),
+ VTranslationStatusBanner: () =>
+ import('~/components/VBanner/VTranslationStatusBanner.vue'),
+ },
+ setup() {
+ const uiStore = useUiStore()
+ const shouldShowMigrationBanner = computed(
+ () => uiStore.shouldShowMigrationBanner
+ )
+ const shouldShowTranslationBanner = computed(
+ () => uiStore.shouldShowTranslationBanner
+ )
+
+ const translationBannerId = computed<TranslationBannerId>(
+ () => uiStore.translationBannerId
+ )
+ return {
+ translationBannerId,
+ shouldShowMigrationBanner,
+ shouldShowTranslationBanner,
+
+ dismissBanner: uiStore.dismissBanner,
+ }
+ },
+})
+</script>
diff --git a/src/components/VMigrationNotice.vue b/src/components/VBanner/VMigrationNotice.vue
similarity index 65%
rename from src/components/VMigrationNotice.vue
rename to src/components/VBanner/VMigrationNotice.vue
index 75e29b9a1..8bac32880 100644
--- a/src/components/VMigrationNotice.vue
+++ b/src/components/VBanner/VMigrationNotice.vue
@@ -1,8 +1,8 @@
<template>
<VNotificationBanner
id="cc-referral"
- :enabled="isReferredFromCc"
variant="announcement"
+ @close="$emit('close')"
>
{{
$t('migration-notice.intro', {
@@ -25,20 +25,13 @@
</template>
<script lang="ts">
-import { defineComponent, computed } from '@nuxtjs/composition-api'
+import { defineComponent } from '@nuxtjs/composition-api'
-import { useNavigationStore } from '~/stores/navigation'
-
-import VNotificationBanner from '~/components/VNotificationBanner.vue'
+import VNotificationBanner from '~/components/VBanner/VNotificationBanner.vue'
import VLink from '~/components/VLink.vue'
export default defineComponent({
name: 'VMigrationNotice',
components: { VLink, VNotificationBanner },
- setup() {
- const navigationStore = useNavigationStore()
- const isReferredFromCc = computed(() => navigationStore.isReferredFromCc)
- return { isReferredFromCc }
- },
})
</script>
diff --git a/src/components/VNotificationBanner.vue b/src/components/VBanner/VNotificationBanner.vue
similarity index 66%
rename from src/components/VNotificationBanner.vue
rename to src/components/VBanner/VNotificationBanner.vue
index d0b577d4e..b74f509df 100644
--- a/src/components/VNotificationBanner.vue
+++ b/src/components/VBanner/VNotificationBanner.vue
@@ -1,19 +1,18 @@
<template>
<div
- v-show="enabled && shouldShow"
class="flex items-center justify-between px-4 py-2 md:px-7"
:class="$style[variant]"
:data-testid="`banner-${id}`"
>
- <p class="text-left text-sr leading-tight md:text-base md:leading-normal">
+ <p class="caption-regular md:description-regular text-left">
<slot name="default" />
</p>
<div class="flex">
<slot name="buttons">
<VIconButton
- :class="variant === 'announcement' && 'text-white'"
+ :class="{ 'text-white': variant === 'announcement' }"
size="small"
- :aria-label="closeLabel"
+ :aria-label="$t('modal.close')"
:icon-props="{
iconPath: closeIcon,
}"
@@ -27,10 +26,9 @@
<script lang="ts">
import { defineComponent, PropType } from '@nuxtjs/composition-api'
-import { useStorage } from '@vueuse/core'
-
import { defineEvent } from '~/types/emits'
-import { useI18n } from '~/composables/use-i18n'
+
+import type { BannerId } from '~/types/banners'
import VIconButton from '~/components/VIconButton/VIconButton.vue'
@@ -47,31 +45,21 @@ export default defineComponent({
required: true,
},
id: {
- type: String,
- required: true,
- },
- enabled: {
- type: Boolean,
+ type: String as PropType<BannerId>,
required: true,
},
},
emits: {
close: defineEvent(),
},
- setup(props, { emit }) {
- const i18n = useI18n()
- const shouldShow = useStorage(`banner:show-${props.id}`, true)
- const dismissBanner = () => (shouldShow.value = false)
+ setup(_, { emit }) {
const handleClose = () => {
- dismissBanner()
emit('close')
}
- const closeLabel = i18n.t('modal.close') as string
+
return {
closeIcon,
- closeLabel,
handleClose,
- shouldShow,
}
},
})
diff --git a/src/components/VBanner/VTranslationStatusBanner.vue b/src/components/VBanner/VTranslationStatusBanner.vue
new file mode 100644
index 000000000..7a0ff5589
--- /dev/null
+++ b/src/components/VBanner/VTranslationStatusBanner.vue
@@ -0,0 +1,69 @@
+<template>
+ <VNotificationBanner
+ :id="bannerKey"
+ variant="informational"
+ data-testid="banner-translation"
+ @close="$emit('close')"
+ >
+ {{
+ // eslint-disable-next-line @intlify/vue-i18n/no-raw-text
+ '⚠️'
+ }}
+ <i18n path="notification.translation.text">
+ <template #link>
+ <VLink :href="currentLocale.link" class="underline">{{
+ $t('notification.translation.link')
+ }}</VLink>
+ </template>
+ <template #locale>
+ {{ currentLocale.name }}
+ </template>
+ </i18n>
+ </VNotificationBanner>
+</template>
+
+<script lang="ts">
+import { computed, defineComponent, PropType } from '@nuxtjs/composition-api'
+
+import type { BannerId } from '~/types/banners'
+
+import { useUiStore } from '~/stores/ui'
+
+import { createTranslationLink } from '~/utils/translation-banner'
+
+import VLink from '~/components/VLink.vue'
+import VNotificationBanner from '~/components/VBanner/VNotificationBanner.vue'
+
+export default defineComponent({
+ name: 'VTranslationStatusBanner',
+ components: {
+ VLink,
+ VNotificationBanner,
+ },
+ props: {
+ bannerKey: {
+ type: String as PropType<BannerId>,
+ required: true,
+ },
+ },
+ setup() {
+ const uiStore = useUiStore()
+
+ /**
+ * Returns the link to the GlotPress project for the current locale and the locale native name.
+ */
+ const currentLocale = computed(() => {
+ const localeObject = uiStore.currentLocale
+
+ return {
+ link: createTranslationLink(localeObject),
+ name: localeObject.name,
+ }
+ })
+
+ return {
+ currentLocale,
+ }
+ },
+})
+</script>
diff --git a/src/components/VTranslationStatusBanner.vue b/src/components/VTranslationStatusBanner.vue
deleted file mode 100644
index 615085993..000000000
--- a/src/components/VTranslationStatusBanner.vue
+++ /dev/null
@@ -1,52 +0,0 @@
-<template>
- <VNotificationBanner
- :id="bannerKey"
- :enabled="needsTranslationBanner"
- variant="informational"
- data-testid="banner-translation"
- >
- {{
- // eslint-disable-next-line @intlify/vue-i18n/no-raw-text
- '⚠️'
- }}
- <i18n path="notification.translation.text">
- <template #link>
- <VLink :href="translationLink" class="underline">{{
- $t('notification.translation.link')
- }}</VLink>
- </template>
- <template #locale>
- {{ name }}
- </template>
- </i18n>
- </VNotificationBanner>
-</template>
-
-<script lang="ts">
-import { computed, defineComponent } from '@nuxtjs/composition-api'
-
-import { useI18nSync } from '~/composables/use-i18n-sync'
-
-import VLink from '~/components/VLink.vue'
-import VNotificationBanner from '~/components/VNotificationBanner.vue'
-
-export default defineComponent({
- name: 'VTranslationStatusBanner',
- components: {
- VLink,
- VNotificationBanner,
- },
- setup() {
- const { currentLocale, translationLink, needsTranslationBanner } =
- useI18nSync()
- const bannerKey = `translation-${currentLocale.value?.code ?? 'en'}`
- const name = computed(() => currentLocale.value?.name ?? '')
- return {
- needsTranslationBanner,
- bannerKey,
- name,
- translationLink,
- }
- },
-})
-</script>
diff --git a/src/layouts/blank.vue b/src/layouts/blank.vue
index 99f535e2c..f70cf6b3f 100644
--- a/src/layouts/blank.vue
+++ b/src/layouts/blank.vue
@@ -1,7 +1,6 @@
<template>
<div>
- <VMigrationNotice />
- <VTranslationStatusBanner />
+ <VBanners />
<Nuxt />
</div>
</template>
@@ -9,12 +8,11 @@
<script>
import { defineComponent } from '@nuxtjs/composition-api'
-import VTranslationStatusBanner from '~/components/VTranslationStatusBanner.vue'
-import VMigrationNotice from '~/components/VMigrationNotice.vue'
+import VBanners from '~/components/VBanner/VBanners.vue'
export default defineComponent({
name: 'BlankLayout',
- components: { VMigrationNotice, VTranslationStatusBanner },
+ components: { VBanners },
head() {
return this.$nuxtI18nHead({ addSeoAttributes: true, addDirAttribute: true })
},
diff --git a/src/layouts/default.vue b/src/layouts/default.vue
index b42f89e82..f78d878f1 100644
--- a/src/layouts/default.vue
+++ b/src/layouts/default.vue
@@ -2,8 +2,7 @@
<div class="app flex min-h-screen flex-col">
<div class="sticky top-0 z-40 block">
<VTeleportTarget name="skip-to-content" :force-destroy="true" />
- <VMigrationNotice />
- <VTranslationStatusBanner />
+ <VBanners />
<template v-if="isNewHeaderEnabled">
<template v-if="isSearchHeader">
<VHeaderDesktop v-if="isDesktopLayout" />
@@ -66,25 +65,22 @@ import { useSearchStore } from '~/stores/search'
import { IsHeaderScrolledKey, IsSidebarVisibleKey } from '~/types/provides'
-import VMigrationNotice from '~/components/VMigrationNotice.vue'
-import VTranslationStatusBanner from '~/components/VTranslationStatusBanner.vue'
+import VBanners from '~/components/VBanner/VBanners.vue'
import VHeaderOld from '~/components/VHeaderOld/VHeaderOld.vue'
import VModalTarget from '~/components/VModal/VModalTarget.vue'
import VGlobalAudioSection from '~/components/VGlobalAudioSection/VGlobalAudioSection.vue'
-import VFooter from '~/components/VFooter/VFooter.vue'
import VSearchGridFilter from '~/components/VFilters/VSearchGridFilter.vue'
const embeddedPage = {
name: 'embedded',
components: {
- VMigrationNotice,
- VTranslationStatusBanner,
- VHeaderOld,
+ VBanners,
VHeaderDesktop: () => import('~/components/VHeader/VHeaderDesktop.vue'),
VHeaderInternal: () => import('~/components/VHeader/VHeaderInternal.vue'),
VHeaderMobile: () =>
import('~/components/VHeader/VHeaderMobile/VHeaderMobile.vue'),
- VFooter,
+ VFooter: () => import('~/components/VFooter/VFooter.vue'),
+ VHeaderOld,
VModalTarget,
VTeleportTarget,
VGlobalAudioSection,
@@ -164,6 +160,7 @@ const embeddedPage = {
isSearchHeader,
headerHasTwoRows,
isNewHeaderEnabled,
+
closeSidebar,
}
},
diff --git a/src/stores/ui.ts b/src/stores/ui.ts
index 1cbd15733..10a3f327c 100644
--- a/src/stores/ui.ts
+++ b/src/stores/ui.ts
@@ -2,11 +2,18 @@ import { defineStore } from 'pinia'
import { computed } from '@nuxtjs/composition-api'
+import { useNavigationStore } from '~/stores/navigation'
+
import type { OpenverseCookieState, SnackbarState } from '~/types/cookies'
+import type { BannerId, TranslationBannerId } from '~/types/banners'
+
import type { Breakpoint } from '~/constants/screens'
import { ALL_SCREEN_SIZES } from '~/constants/screens'
import { useFeatureFlagStore } from '~/stores/feature-flag'
import { cookieOptions } from '~/utils/cookies'
+import { needsTranslationBanner } from '~/utils/translation-banner'
+
+import type { LocaleObject } from '@nuxtjs/i18n'
const desktopBreakpoints: Breakpoint[] = ['2xl', 'xl', 'lg']
@@ -37,6 +44,7 @@ export interface UiState {
* whether the request user agent is mobile or not.
*/
isMobileUa: boolean
+ dismissedBanners: BannerId[]
}
export const breakpoints = Object.keys(ALL_SCREEN_SIZES)
@@ -49,6 +57,7 @@ export const useUiStore = defineStore('ui', {
isDesktopLayout: false,
breakpoint: 'sm',
isMobileUa: true,
+ dismissedBanners: [],
}),
getters: {
@@ -84,6 +93,40 @@ export const useUiStore = defineStore('ui', {
}
return state.innerFilterVisible
},
+ /**
+ * The locale object of the current locale.
+ */
+ currentLocale(): LocaleObject {
+ return this.$nuxt.i18n.localeProperties
+ },
+ /**
+ * The id used in the translation banner and the cookies for dismissed banners.
+ * @example 'translation-ru'
+ */
+ translationBannerId(): TranslationBannerId {
+ return `translation-${this.currentLocale.code as LocaleObject['code']}`
+ },
+ /**
+ * The translation banner is shown if the translated percentage is below 90%,
+ * and the banner for the current locale was not dismissed (status from cookies).
+ */
+ shouldShowTranslationBanner(): boolean {
+ return (
+ !this.dismissedBanners.includes(this.translationBannerId) &&
+ needsTranslationBanner(this.currentLocale)
+ )
+ },
+ /**
+ * The migration banner is shown if the user is referred from CC Search,
+ * and hasn't dismissed it yet.
+ */
+ shouldShowMigrationBanner(): boolean {
+ const navigationStore = useNavigationStore()
+ return (
+ !this.dismissedBanners.includes('cc-referral') &&
+ navigationStore.isReferredFromCc
+ )
+ },
},
actions: {
@@ -110,6 +153,7 @@ export const useUiStore = defineStore('ui', {
this.innerFilterVisible = this.isDesktopLayout
? !this.isFilterDismissed
: false
+ this.dismissedBanners = cookies.uiDismissedBanners ?? []
this.updateCookies()
},
@@ -124,6 +168,7 @@ export const useUiStore = defineStore('ui', {
{ name: 'uiIsFilterDismissed', value: this.isFilterDismissed, opts },
{ name: 'uiBreakpoint', value: this.breakpoint, opts },
{ name: 'uiIsMobileUa', value: this.isMobileUa, opts },
+ { name: 'uiDismissedBanners', value: this.dismissedBanners, opts },
])
},
@@ -167,6 +212,25 @@ export const useUiStore = defineStore('ui', {
toggleFilters() {
this.setFiltersState(!this.isFilterVisible)
},
+ /**
+ * If the banner wasn't dismissed before, dismisses it and saves the new state in a cookie.
+ * @param bannerId - the id of the banner to dismiss.
+ */
+ dismissBanner(bannerId: BannerId) {
+ if (this.dismissedBanners.includes(bannerId)) {
+ return
+ }
+
+ this.dismissedBanners.push(bannerId)
+ this.$nuxt.$cookies.set(
+ 'uiDismissedBanners',
+ this.dismissedBanners,
+ cookieOptions
+ )
+ },
+ isBannerDismissed(bannerId: BannerId) {
+ return this.dismissedBanners.includes(bannerId)
+ },
/**
* Similar to CSS `@media` queries, this function returns a boolean
* indicating whether the current breakpoint is greater than or equal to
diff --git a/src/types/banners.ts b/src/types/banners.ts
new file mode 100644
index 000000000..91bb1a884
--- /dev/null
+++ b/src/types/banners.ts
@@ -0,0 +1,4 @@
+import type { LocaleObject } from '@nuxtjs/i18n'
+
+export type TranslationBannerId = `translation-${LocaleObject['code']}`
+export type BannerId = TranslationBannerId | 'cc-referral'
diff --git a/src/types/cookies.ts b/src/types/cookies.ts
index a96717d06..b5751f9c9 100644
--- a/src/types/cookies.ts
+++ b/src/types/cookies.ts
@@ -1,9 +1,19 @@
import type { FeatureState } from '~/constants/feature-flag'
+import { isProd } from '~/utils/node-env'
+import type { BannerId } from '~/types/banners'
import type { Breakpoint } from '~/constants/screens'
+import type { CookieSerializeOptions } from 'cookie'
+
export type SnackbarState = 'not_shown' | 'visible' | 'dismissed'
+export const cookieOptions: CookieSerializeOptions = {
+ path: '/',
+ sameSite: 'strict',
+ maxAge: 60 * 60 * 24 * 60, // 60 days
+ secure: isProd,
+}
/**
* The cookies that Openverse uses to store the UI state.
*/
@@ -24,6 +34,10 @@ export interface OpenverseCookieState {
* Whether the request user agent is mobile or not.
*/
uiIsMobileUa?: boolean
+ /**
+ * The list of ids of dismissed banners.
+ */
+ uiDismissedBanners?: BannerId[]
/**
* The state of the feature flags.
*/
diff --git a/src/utils/translation-banner.ts b/src/utils/translation-banner.ts
new file mode 100644
index 000000000..671e63fd7
--- /dev/null
+++ b/src/utils/translation-banner.ts
@@ -0,0 +1,14 @@
+import type { LocaleObject } from '@nuxtjs/i18n'
+
+const BASE_URL = 'https://translate.wordpress.org/projects/meta/openverse/'
+// We show the banner if the translation is less than this percentage
+const MINIMUM_TRANSLATION_PERCENTAGE = 90
+
+export const needsTranslationBanner = (locale: LocaleObject) => {
+ if (!locale || locale.code === 'en') return false
+
+ return (locale.translated ?? 100) <= MINIMUM_TRANSLATION_PERCENTAGE
+}
+
+export const createTranslationLink = (locale: LocaleObject) =>
+ `${BASE_URL}${locale.code || 'en'}/default/`
diff --git a/test/playwright/e2e/migration-banner.spec.ts b/test/playwright/e2e/migration-banner.spec.ts
index bcaa90b76..6b785c464 100644
--- a/test/playwright/e2e/migration-banner.spec.ts
+++ b/test/playwright/e2e/migration-banner.spec.ts
@@ -13,6 +13,24 @@ test.describe('migration banner', () => {
await expect(migrationNotice).toBeVisible()
})
+ test('does not show migration banner if cookie dismissed value is saved', async ({
+ context,
+ page,
+ }) => {
+ await context.addCookies([
+ {
+ name: 'uiDismissedBanners',
+ value: '["cc-referral"]',
+ domain: 'localhost',
+ path: '/',
+ },
+ ])
+ await page.goto('/?referrer=creativecommons.org')
+ const migrationNotice = page.locator('[data-testid="banner-cc-referral"]')
+
+ await expect(migrationNotice).toBeHidden()
+ })
+
test('migration banner goes away on navigation', async ({ page }) => {
await page.goto('/?referrer=creativecommons.org')
diff --git a/test/playwright/e2e/translation-banner.spec.ts b/test/playwright/e2e/translation-banner.spec.ts
index f92c24cf8..14ef8cb3a 100644
--- a/test/playwright/e2e/translation-banner.spec.ts
+++ b/test/playwright/e2e/translation-banner.spec.ts
@@ -24,6 +24,23 @@ test.describe('translation banner', () => {
)
})
+ test('Banner is not shown if dismissed state is saved in a cookie', async ({
+ page,
+ }) => {
+ await page.context().addCookies([
+ {
+ name: 'uiDismissedBanners',
+ value: '["translation-ru"]',
+ domain: 'localhost',
+ path: '/',
+ },
+ ])
+ await page.goto(russianSearchPath)
+ await expect(
+ page.locator('[data-testid="banner-translation"]')
+ ).not.toBeVisible({ timeout: 500 })
+ })
+
test('Can close the translation banner', async ({ page }) => {
await page.goto(russianSearchPath)
await page.click('[data-testid="banner-translation"] button:visible', {
diff --git a/test/unit/specs/stores/ui-store.spec.js b/test/unit/specs/stores/ui-store.spec.js
index a18068baf..0282508de 100644
--- a/test/unit/specs/stores/ui-store.spec.js
+++ b/test/unit/specs/stores/ui-store.spec.js
@@ -8,6 +8,7 @@ const initialState = {
isFilterDismissed: false,
isDesktopLayout: false,
isMobileUa: true,
+ dismissedBanners: [],
}
const VISIBLE_AND_DISMISSED = {
@@ -27,6 +28,13 @@ const NOT_VISIBLE_AND_NOT_DISMISSED = {
isFilterDismissed: false,
}
+const cookieOptions = {
+ maxAge: 5184000,
+ path: '/',
+ sameSite: 'strict',
+ secure: false,
+}
+
describe('Ui Store', () => {
beforeEach(() => {
setActivePinia(createPinia())
@@ -130,6 +138,16 @@ describe('Ui Store', () => {
expect(uiStore.isFilterDismissed).toEqual(false)
expect(uiStore.isFilterVisible).toEqual(false)
})
+
+ it('initFromCookies sets initial state with a dismissed banner', () => {
+ const uiStore = useUiStore()
+ const dismissedBanners = ['ru', 'ar', 'cc-referral']
+ uiStore.initFromCookies({
+ uiDismissedBanners: dismissedBanners,
+ })
+
+ expect(uiStore.dismissedBanners).toEqual(dismissedBanners)
+ })
})
test.each`
@@ -239,4 +257,40 @@ describe('Ui Store', () => {
expect(uiStore.isFilterDismissed).toEqual(expectedState.isFilterDismissed)
}
)
+ it.each`
+ originalState | bannerId | expectedState | areCookiesSet
+ ${[]} | ${'es'} | ${['es']} | ${true}
+ ${['es']} | ${'es'} | ${['es']} | ${false}
+ ${['cc-referral', 'es']} | ${'de'} | ${['cc-referral', 'es', 'de']} | ${true}
+ `(
+ 'dismissBanner($bannerId): $originalState -> $expectedState',
+ ({ originalState, bannerId, expectedState, areCookiesSet }) => {
+ const uiStore = useUiStore()
+ uiStore.$patch({ dismissedBanners: originalState })
+ uiStore.dismissBanner(bannerId)
+
+ expect(uiStore.dismissedBanners).toEqual(expectedState)
+ if (areCookiesSet) {
+ expect(uiStore.$nuxt.$cookies.set).toHaveBeenCalledWith(
+ 'uiDismissedBanners',
+ expectedState,
+ cookieOptions
+ )
+ }
+ }
+ )
+ it.each`
+ originalState | bannerId | expectedState
+ ${[]} | ${'es'} | ${false}
+ ${['es']} | ${'es'} | ${true}
+ ${['cc-referral', 'es']} | ${'de'} | ${false}
+ `(
+ 'isBannerDismissed($bannerId) for $originalState returns $expectedState',
+ ({ originalState, bannerId, expectedState }) => {
+ const uiStore = useUiStore()
+ uiStore.$patch({ dismissedBanners: originalState })
+
+ expect(uiStore.isBannerDismissed(bannerId)).toEqual(expectedState)
+ }
+ )
})
diff --git a/test/unit/test-utils/pinia.js b/test/unit/test-utils/pinia.js
index 0ad415e59..fe8f4948e 100644
--- a/test/unit/test-utils/pinia.js
+++ b/test/unit/test-utils/pinia.js
@@ -14,6 +14,13 @@ export const createPinia = () =>
get: jest.fn(),
setAll: jest.fn(),
},
+ i18n: {
+ localeProperties: {
+ code: 'es',
+ translated: 100,
+ name: 'Spanish',
+ },
+ },
},
}))