Skip to content

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

Separate features into persistent and session scoped cookies (#2955)

Dhruv Bhanushalidf14afa55832
diff --git a/frontend/src/layouts/content-layout.vue b/frontend/src/layouts/content-layout.vue
index eda471d06..a144a62b7 100644
--- a/frontend/src/layouts/content-layout.vue
+++ b/frontend/src/layouts/content-layout.vue
@@ -36,7 +36,6 @@ import { useWindowScroll } from "~/composables/use-window-scroll"
import { useLayout } from "~/composables/use-layout"
import { useUiStore } from "~/stores/ui"
-import { useFeatureFlagStore } from "~/stores/feature-flag"
import { ShowScrollButtonKey } from "~/types/provides"
@@ -63,11 +62,6 @@ export default defineComponent({
setup() {
const uiStore = useUiStore()
- const featureStore = useFeatureFlagStore()
- onMounted(() => {
- featureStore.initFromSession()
- })
-
const { updateBreakpoint } = useLayout()
/**
diff --git a/frontend/src/layouts/default.vue b/frontend/src/layouts/default.vue
index c73737c79..a8fe6008e 100644
--- a/frontend/src/layouts/default.vue
+++ b/frontend/src/layouts/default.vue
@@ -25,7 +25,6 @@ import { computed, defineComponent, onMounted } from "vue"
import { useLayout } from "~/composables/use-layout"
import { useUiStore } from "~/stores/ui"
-import { useFeatureFlagStore } from "~/stores/feature-flag"
import VBanners from "~/components/VBanner/VBanners.vue"
import VFooter from "~/components/VFooter/VFooter.vue"
@@ -50,11 +49,6 @@ export default defineComponent({
setup() {
const uiStore = useUiStore()
- const featureStore = useFeatureFlagStore()
- onMounted(() => {
- featureStore.initFromSession()
- })
-
const { updateBreakpoint } = useLayout()
/**
diff --git a/frontend/src/layouts/search-layout.vue b/frontend/src/layouts/search-layout.vue
index 5bf3f6840..e6557e72a 100644
--- a/frontend/src/layouts/search-layout.vue
+++ b/frontend/src/layouts/search-layout.vue
@@ -103,9 +103,6 @@ export default defineComponent({
const searchStore = useSearchStore()
const featureStore = useFeatureFlagStore()
- onMounted(() => {
- featureStore.initFromSession()
- })
const isSensitiveContentEnabled = computed(() =>
featureStore.isOn("sensitive_content")
)
diff --git a/frontend/src/middleware/middleware.ts b/frontend/src/middleware/middleware.ts
index 3cfb68fbf..5a1bf967f 100644
--- a/frontend/src/middleware/middleware.ts
+++ b/frontend/src/middleware/middleware.ts
@@ -33,6 +33,7 @@ const middleware: Middleware = async ({
const featureFlagStore = useFeatureFlagStore($pinia)
featureFlagStore.initFromCookies($cookies.get("features") ?? {})
+ featureFlagStore.initFromCookies($cookies.get("sessionFeatures") ?? {})
featureFlagStore.initFromQuery(query)
/* UI store */
@@ -40,7 +41,7 @@ const middleware: Middleware = async ({
const uiStore = useUiStore($pinia)
const isMobileUa = $ua ? $ua.isMobile : false
- $cookies.set("uiIsMobileUa", isMobileUa, { ...cookieOptions })
+ $cookies.set("uiIsMobileUa", isMobileUa, cookieOptions)
uiStore.initFromCookies($cookies.getAll() ?? {})
}
export default middleware
diff --git a/frontend/src/stores/feature-flag.ts b/frontend/src/stores/feature-flag.ts
index 296e8cf16..cf2fad22e 100644
--- a/frontend/src/stores/feature-flag.ts
+++ b/frontend/src/stores/feature-flag.ts
@@ -5,6 +5,7 @@ import { useStorage } from "@vueuse/core"
import featureData from "~~/feat/feature-flags.json"
import { warn } from "~/utils/console"
+import { cookieOptions } from "~/utils/cookies"
import type { FeatureFlag } from "~/types/feature-flag"
import {
@@ -20,8 +21,6 @@ import {
} from "~/constants/feature-flag"
import { LOCAL, DEPLOY_ENVS, DeployEnv } from "~/constants/deploy-env"
-import type { Context } from "@nuxt/types"
-
import type { Dictionary } from "vue-router/types/router"
type FlagName = keyof (typeof featureData)["features"]
@@ -115,41 +114,17 @@ export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {
actions: {
/**
* Given a list of key value pairs of flags and their preferred states,
- * populate the store state to match the cookie.
- *
- * Values stored in the cookie are stored across sessions and can be
- * modified using the '/preferences' page.
+ * populate the store state to match the cookie. The cookie may be
+ * persistent, if written by `writeToCookie`, or session-scoped, if written
+ * by `writeToSession`.
*
* @param cookies - mapping of feature flags and their preferred states
*/
initFromCookies(cookies: Record<string, FeatureState>) {
- Object.entries(this.flags).forEach(([name, flag]) => {
- if (getFlagStatus(flag) === SWITCHABLE && flag.storage === COOKIE)
- Vue.set(flag, "preferredState", cookies[name])
- })
- },
- /**
- * Write the current state of the switchable flags to the cookie.
- *
- * @param cookies - the Nuxt cookies module
- */
- writeToCookies(cookies: Context["$cookies"]) {
- cookies.set("features", this.flagStateMap(COOKIE))
- },
- /**
- * Initialize the state of the switchable flags from the session storage.
- * `Vue.set` is used to ensure reactivity is maintained.
- */
- initFromSession() {
- if (typeof window === "undefined") return
- const features = useStorage<Record<string, FeatureState>>(
- "features",
- {},
- sessionStorage
- )
- Object.entries(this.flags).forEach(([name, flag]) => {
- if (getFlagStatus(flag) === SWITCHABLE && flag.storage === SESSION) {
- Vue.set(flag, "preferredState", features.value[name])
+ Object.entries(cookies).forEach(([name, state]) => {
+ const flag = this.flags[name as FlagName]
+ if (flag && getFlagStatus(flag) === SWITCHABLE) {
+ Vue.set(flag, "preferredState", state)
}
})
},
@@ -158,19 +133,24 @@ export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {
* are read in the corresponding `initFromCookies` method.
*/
writeToCookie() {
- this.$nuxt.$cookies.set("features", this.flagStateMap(COOKIE))
+ this.$nuxt.$cookies.set(
+ "features",
+ this.flagStateMap(COOKIE),
+ cookieOptions
+ )
},
/**
- * Write the current state of the switchable flags to the session storage.
+ * Write the current state of the switchable flags to the session cookie.
+ * These cookies are read in the corresponding `initFromCookies` method.
+ *
+ * This is same as `writeToCookie`, except these cookies are not persistent
+ * and will be deleted by the browser after the session.
*/
writeToSession() {
- if (typeof window === "undefined") return
- const features = useStorage<Record<string, FeatureState>>(
- "features",
- {},
- sessionStorage
- )
- features.value = this.flagStateMap(SESSION)
+ this.$nuxt.$cookies.set("sessionFeatures", this.flagStateMap(SESSION), {
+ ...cookieOptions,
+ maxAge: undefined,
+ })
},
/**
* Set the value of flag entries from the query parameters. Only those
diff --git a/frontend/src/types/cookies.ts b/frontend/src/types/cookies.ts
index 1be3e112a..7b6591676 100644
--- a/frontend/src/types/cookies.ts
+++ b/frontend/src/types/cookies.ts
@@ -39,7 +39,11 @@ export interface OpenverseCookieState {
*/
uiDismissedBanners?: BannerId[]
/**
- * The state of the feature flags.
+ * The state of the persistent feature flags.
*/
features?: Record<string, FeatureState>
+ /**
+ * The state of the session-scoped feature flags.
+ */
+ sessionFeatures?: Record<string, FeatureState>
}
diff --git a/frontend/src/utils/cookies.ts b/frontend/src/utils/cookies.ts
index 7c0a8869b..1a2988574 100644
--- a/frontend/src/utils/cookies.ts
+++ b/frontend/src/utils/cookies.ts
@@ -5,6 +5,6 @@ import type { CookieSerializeOptions } from "cookie"
export const cookieOptions: CookieSerializeOptions = {
path: "/",
sameSite: "strict",
- maxAge: 60 * 60 * 24 * 60, // 60 days
+ maxAge: 60 * 60 * 24 * 60, // 60 days; Makes the cookie persistent.
secure: isProd,
}
diff --git a/frontend/test/playwright/e2e/translation-banner.spec.ts b/frontend/test/playwright/e2e/translation-banner.spec.ts
index bff4e5744..9b0879bed 100644
--- a/frontend/test/playwright/e2e/translation-banner.spec.ts
+++ b/frontend/test/playwright/e2e/translation-banner.spec.ts
@@ -39,14 +39,12 @@ test.describe("translation banner", () => {
test("Can close the translation banner", async ({ page }) => {
await page.goto(russianSearchPath)
- await page.click('[data-testid="banner-translation"] button:visible', {
- timeout: 500,
- })
+ await page.click('[data-testid="banner-translation"] button:visible')
const banner = page.locator('.span:has-text("Help us get to 100 percent")')
await expect(banner).toBeHidden({ timeout: 500 })
// Test that the banner does not re-appear when navigating to the 'About us' page
- await page.locator('a[href="/ru/about"]').click()
+ await page.locator('li a[href="/ru/about"]').click()
await expect(banner).toBeHidden({ timeout: 500 })
await page.goto(russianSearchPath)
diff --git a/frontend/test/playwright/visual-regression/pages/homepage.spec.ts b/frontend/test/playwright/visual-regression/pages/homepage.spec.ts
index dc781907a..49ba95aae 100644
--- a/frontend/test/playwright/visual-regression/pages/homepage.spec.ts
+++ b/frontend/test/playwright/visual-regression/pages/homepage.spec.ts
@@ -26,7 +26,7 @@ const cleanImageCarousel = async (page: Page) => {
for (const dir of languageDirections) {
test.describe(`${dir} homepage snapshots`, () => {
- const path = pathWithDir("/", dir)
+ const path = pathWithDir("/?ff_additional_search_types=off", dir)
test.beforeEach(async ({ page }) => {
await page.goto(path)
await dismissTranslationBanner(page)
diff --git a/frontend/test/unit/specs/stores/feature-flag-store.spec.js b/frontend/test/unit/specs/stores/feature-flag-store.spec.js
index ace9e971e..8475b1acd 100644
--- a/frontend/test/unit/specs/stores/feature-flag-store.spec.js
+++ b/frontend/test/unit/specs/stores/feature-flag-store.spec.js
@@ -1,7 +1,7 @@
import { setActivePinia, createPinia } from "~~/test/unit/test-utils/pinia"
import { useFeatureFlagStore, getFlagStatus } from "~/stores/feature-flag"
-import { OFF, ON, COOKIE, SESSION } from "~/constants/feature-flag"
+import { OFF, COOKIE, SESSION } from "~/constants/feature-flag"
jest.mock(
"~~/feat/feature-flags.json",
@@ -91,27 +91,6 @@ describe("Feature flag store", () => {
}
)
- it.each`
- doSessionInit | featureState
- ${false} | ${"off"}
- ${true} | ${"on"}
- `(
- "cascades session-storage flag from sessionStorage",
- ({ doSessionInit, featureState }) => {
- const flagName = "feat_switchable_optin"
- const featureFlagStore = useFeatureFlagStore()
-
- window.sessionStorage.setItem(
- "features",
- JSON.stringify({ feat_switchable_optin: ON })
- )
- if (doSessionInit) featureFlagStore.initFromSession()
-
- expect(featureFlagStore.featureState(flagName)).toEqual(featureState)
- expect(featureFlagStore.isOn(flagName)).toEqual(featureState === "on")
- }
- )
-
it.each`
cookieState | queryState | finalState
${"off"} | ${"on"} | ${"on"}