Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Analytics: Add REACH_RESULT_END event (#2454)
Olga Bulat859f0347c350
diff --git a/frontend/src/components/VLicense/VLicense.vue b/frontend/src/components/VLicense/VLicense.vueindex cf3e85be8..6592536ec 100644--- a/frontend/src/components/VLicense/VLicense.vue+++ b/frontend/src/components/VLicense/VLicense.vue@@ -62,10 +62,10 @@ export default defineComponent({const iconNames = computed(() => getElements(props.license))const licenseName = computed(() => {+ const licenseKey =+ props.license === "sampling+" ? props.license : camel(props.license)return {- readable: i18n- .t(`licenseReadableNames.${camel(props.license)}`)- .toString(),+ readable: i18n.t(`licenseReadableNames.${licenseKey}`).toString(),full: getFullLicenseName(props.license, "", i18n),}})diff --git a/frontend/src/components/VLoadMore.vue b/frontend/src/components/VLoadMore.vueindex 60c4c1911..863c85ff2 100644--- a/frontend/src/components/VLoadMore.vue+++ b/frontend/src/components/VLoadMore.vue@@ -1,22 +1,29 @@<template>- <VButton- v-show="canLoadMore"- class="label-bold lg:description-bold h-16 w-full lg:h-18"- variant="filled-gray"- size="disabled"- :disabled="isFetching"- data-testid="load-more"- @click="onLoadMore"- >- {{ buttonLabel }}- </VButton>+ <div ref="loadMoreSectionRef" class="w-full">+ <VButton+ v-show="canLoadMore"+ class="label-bold lg:description-bold h-16 w-full lg:h-18"+ variant="filled-gray"+ size="disabled"+ :disabled="fetchState.isFetching"+ data-testid="load-more"+ @click="onLoadMore"+ >+ {{ buttonLabel }}+ </VButton>+ </div></template><script lang="ts">-import { computed, defineComponent } from "vue"+import { computed, defineComponent, onMounted, ref, watch } from "vue"+import { storeToRefs } from "pinia"+import { useElementVisibility } from "@vueuse/core"++import { useRoute } from "@nuxtjs/composition-api"import { useMediaStore } from "~/stores/media"import { useSearchStore } from "~/stores/search"import { useI18n } from "~/composables/use-i18n"+import { useAnalytics } from "~/composables/use-analytics"import VButton from "~/components/VButton.vue"@@ -26,11 +33,19 @@ export default defineComponent({VButton,},setup() {+ const loadMoreSectionRef = ref(null)+ const route = useRoute()const i18n = useI18n()const mediaStore = useMediaStore()const searchStore = useSearchStore()- const isFetching = computed(() => mediaStore.fetchState.isFetching)+ const { sendCustomEvent } = useAnalytics()++ // Use the `_searchType` from mediaStore because it falls back to ALL_MEDIA+ // for unsupported search types.+ const { fetchState, resultCount, currentPage, _searchType } =+ storeToRefs(mediaStore)+ const { searchTerm } = storeToRefs(searchStore)/*** Whether we should show the "Load more" button.@@ -40,12 +55,13 @@ export default defineComponent({*/const canLoadMore = computed(() =>- searchStore.searchTerm !== "" &&- !mediaStore.fetchState.fetchingError &&- !mediaStore.fetchState.isFinished &&- mediaStore.resultCount > 0+ searchTerm.value !== "" &&+ !fetchState.value.fetchingError &&+ !fetchState.value.isFinished &&+ resultCount.value > 0)+ const reachResultEndEventSent = ref(false)/*** On button click, fetch media, persisting the existing results.* The button is disabled when we are fetching, but we still check@@ -53,24 +69,64 @@ export default defineComponent({**/const onLoadMore = async () => {- if (isFetching.value) return+ if (fetchState.value.isFetching) return++ reachResultEndEventSent.value = falseawait mediaStore.fetchMedia({shouldPersistMedia: true,})}+ const sendReachResultEnd = () => {+ // This function can be called before the media is fetched and+ // currentPage is updated from 0, so we use the value or 1.+ // The currentPage can never be 0 here because then the loadMore+ // button would not be visible.+ sendCustomEvent("REACH_RESULT_END", {+ searchType: _searchType.value,+ query: searchTerm.value,+ resultPage: currentPage.value || 1,+ })+ }+const buttonLabel = computed(() =>- isFetching.value+ fetchState.value.isFetching? i18n.t("browsePage.loading"): i18n.t("browsePage.load"))+ const mainPageElement = ref<HTMLElement | null>(null)+ onMounted(() => {+ mainPageElement.value = document.getElementById("main-page")+ })+ const isLoadMoreButtonVisible = useElementVisibility(loadMoreSectionRef, {+ scrollTarget: mainPageElement,+ })++ // Reset the reachResultEndEvent whenever the route changes,+ // to make sure the result end is tracked properly whenever+ // the search query or content type changes+ watch(route, () => {+ reachResultEndEventSent.value = false+ })++ watch(isLoadMoreButtonVisible, (isVisible) => {+ if (isVisible) {+ if (reachResultEndEventSent.value) {+ return+ }+ sendReachResultEnd()+ reachResultEndEventSent.value = true+ }+ })return {buttonLabel,- isFetching,+ fetchState,onLoadMore,canLoadMore,++ loadMoreSectionRef,}},})diff --git a/frontend/src/components/VSearchResultsGrid/VAllResultsGrid.vue b/frontend/src/components/VSearchResultsGrid/VAllResultsGrid.vueindex b601cb13a..a3ebc7e17 100644--- a/frontend/src/components/VSearchResultsGrid/VAllResultsGrid.vue+++ b/frontend/src/components/VSearchResultsGrid/VAllResultsGrid.vue@@ -94,7 +94,8 @@ export default defineComponent({const resultsLoading = computed(() => {return (Boolean(mediaStore.fetchState.fetchingError) ||- mediaStore.fetchState.isFetching+ mediaStore.fetchState.isFetching ||+ !mediaStore.fetchState.hasStarted)})diff --git a/frontend/src/composables/use-search-type.ts b/frontend/src/composables/use-search-type.tsindex e2f8560fd..ff9ad26e7 100644--- a/frontend/src/composables/use-search-type.ts+++ b/frontend/src/composables/use-search-type.ts@@ -11,6 +11,7 @@ import {SearchType,} from "~/constants/media"+import { useMediaStore } from "~/stores/media"import { useSearchStore } from "~/stores/search"import { useFeatureFlagStore } from "~/stores/feature-flag"@@ -63,6 +64,7 @@ export default function useSearchType() {component: componentName,})useSearchStore().setSearchType(searchType)+ useMediaStore().clearMedia()previousSearchType.value = searchType}diff --git a/frontend/src/pages/search.vue b/frontend/src/pages/search.vueindex cac686b01..6ef04e233 100644--- a/frontend/src/pages/search.vue+++ b/frontend/src/pages/search.vue@@ -3,7 +3,6 @@class="browse-page flex w-full flex-col px-6 lg:px-10"><VSearchGrid- ref="searchGridRef":fetch-state="fetchState":query="query":supported="supported"@@ -32,8 +31,9 @@<script lang="ts">import { isShallowEqualObjects } from "@wordpress/is-shallow-equal"-import { computed, inject, ref } from "vue"-import { defineComponent, useMeta } from "@nuxtjs/composition-api"+import { computed, inject, watch } from "vue"+import { storeToRefs } from "pinia"+import { defineComponent, useMeta, useRoute } from "@nuxtjs/composition-api"import { searchMiddleware } from "~/middleware/search"import { useMediaStore } from "~/stores/media"@@ -44,8 +44,6 @@ import VSearchGrid from "~/components/VSearchGrid.vue"import VSkipToContentContainer from "~/components/VSkipToContentContainer.vue"import VScrollButton from "~/components/VScrollButton.vue"-import type { Context } from "@nuxt/types"-export default defineComponent({name: "BrowsePage",components: {@@ -55,15 +53,14 @@ export default defineComponent({},layout: "search-layout",middleware: searchMiddleware,- scrollToTop: false,setup() {- const searchGridRef = ref<InstanceType<typeof VSearchGrid> | null>(null)-const showScrollButton = inject(ShowScrollButtonKey)const isSidebarVisible = inject(IsSidebarVisibleKey)const mediaStore = useMediaStore()const searchStore = useSearchStore()+ const route = useRoute()+// I don't know *exactly* why this is necessary, but without it// transitioning from the homepage to this page breaks the// watcher in useStorage and recent searches won't be saved@@ -71,19 +68,18 @@ export default defineComponent({// hydration and Vue reactives. Hopefully fixed in Nuxt 3.searchStore.refreshRecentSearches()- const searchTerm = computed(() => searchStore.searchTerm)- const searchType = computed(() => searchStore.searchType)- const query = computed(() => searchStore.searchQueryParams)- const supported = computed(() => searchStore.searchTypeIsSupported)- const resultCount = computed(() => mediaStore.resultCount)- const fetchState = computed(() => mediaStore.fetchState)- const resultItems = computed(() => mediaStore.resultItems)+ const {+ searchTerm,+ searchType,+ searchQueryParams: query,+ searchTypeIsSupported: supported,+ } = storeToRefs(searchStore)++ const { resultCount, fetchState, resultItems } = storeToRefs(mediaStore)const needsFetching = computed(() =>Boolean(- searchStore.searchTypeIsSupported &&- !mediaStore.resultCount &&- searchStore.searchTerm.trim() !== ""+ supported.value && !resultCount.value && searchTerm.value.trim() !== ""))@@ -92,8 +88,30 @@ export default defineComponent({meta: [{ hid: "robots", name: "robots", content: "all" }],})+ const fetchMedia = async (+ payload: { shouldPersistMedia?: boolean } = {}+ ) => {+ return mediaStore.fetchMedia(payload)+ }++ watch(route, async (newRoute, oldRoute) => {+ /**+ * Updates the search type only if the route's path changes.+ * Scrolls `main-page` to top if the path changes.+ */+ if (+ newRoute.path !== oldRoute.path ||+ !isShallowEqualObjects(newRoute.query, oldRoute.query)+ ) {+ const { query: urlQuery, path } = newRoute+ searchStore.setSearchStateFromUrl({ urlQuery, path })++ document.getElementById("main-page")?.scroll(0, 0)+ await fetchMedia()+ }+ })+return {- searchGridRef,showScrollButton,searchTerm,searchType,@@ -105,6 +123,8 @@ export default defineComponent({resultItems,needsFetching,isSidebarVisible,++ fetchMedia,}},/**@@ -128,27 +148,5 @@ export default defineComponent({}},head: {},- watch: {- /**- * Updates the search type only if the route's path changes.- */- async $route(newRoute: Context["route"], oldRoute: Context["route"]) {- if (- newRoute.path !== oldRoute.path ||- !isShallowEqualObjects(newRoute.query, oldRoute.query)- ) {- const { query, path } = newRoute- const searchStore = useSearchStore(this.$nuxt.$pinia)- searchStore.setSearchStateFromUrl({ urlQuery: query, path })- await this.fetchMedia()- }- },- },- methods: {- fetchMedia(payload: { shouldPersistMedia?: boolean } = {}) {- const mediaStore = useMediaStore(this.$pinia)- return mediaStore.fetchMedia(payload)- },- },})</script>diff --git a/frontend/src/stores/media/index.ts b/frontend/src/stores/media/index.tsindex d258da3c9..21171c620 100644--- a/frontend/src/stores/media/index.ts+++ b/frontend/src/stores/media/index.ts@@ -38,6 +38,7 @@ export interface MediaState {audio: FetchStateimage: FetchState}+ currentPage: number}export const initialResults = deepFreeze({@@ -67,6 +68,7 @@ export const useMediaStore = defineStore("media", {fetchingError: null,},},+ currentPage: 0,}),getters: {@@ -366,6 +368,7 @@ export const useMediaStore = defineStore("media", {const mediaType = this._searchTypeif (!payload.shouldPersistMedia) {this._resetFetchState()+ this.currentPage = 0}const mediaToFetch = ((mediaType !== ALL_MEDIA@@ -385,11 +388,17 @@ export const useMediaStore = defineStore("media", {})))+ if (mediaType === ALL_MEDIA) {+ this.currentPage += 1+ } else {+ this.currentPage = this.results[mediaType].page ?? 0+ }},clearMedia() {supportedMediaTypes.forEach((mediaType) => {this.resetMedia(mediaType)+ this._resetFetchState()})},diff --git a/frontend/src/types/analytics.ts b/frontend/src/types/analytics.tsindex 0ecfc5242..2b2d9a170 100644--- a/frontend/src/types/analytics.ts+++ b/frontend/src/types/analytics.ts@@ -1,4 +1,8 @@-import type { MediaType, SearchType } from "~/constants/media"+import type {+ MediaType,+ SearchType,+ SupportedSearchType,+} from "~/constants/media"import type { ReportReason } from "~/constants/content-report"import type { NonMatureFilterCategory } from "~/constants/filters"@@ -61,6 +65,26 @@ export type Events = {/** The content type being searched (can include All content) */searchType: SearchType}+ /**+ * Description: Whenever the user scrolls to the end of the results page.+ * Useful to evaluate how often users load more results or click+ * on the external sources dropdown.+ *+ * This event is mainly used as part of a funnel leading to a+ * `LOAD_MORE` or `VIEW_EXTERNAL_SOURCES` event.+ *+ * Questions:+ * - Do users use external search after reaching the result end?+ * - Do users find a result before reaching the end of the results?+ */+ REACH_RESULT_END: {+ /** The media type being searched */+ searchType: SupportedSearchType+ /** The search term */+ query: string+ /** The current page of results the user is on. */+ resultPage: number+ }/*** Description: The user clicks the CTA button to the external source to use the image* Questions:diff --git a/frontend/test/playwright/e2e/load-more.spec.ts b/frontend/test/playwright/e2e/load-more.spec.tsindex c4ab908d7..ea47e2d73 100644--- a/frontend/test/playwright/e2e/load-more.spec.ts+++ b/frontend/test/playwright/e2e/load-more.spec.ts@@ -7,6 +7,11 @@ import {} from "~~/test/playwright/utils/navigation"import { mockProviderApis } from "~~/test/playwright/utils/route"+import {+ collectAnalyticsEvents,+ expectEventPayloadToMatch,+} from "~~/test/playwright/utils/analytics"+import { AUDIO, IMAGE, SupportedMediaType } from "~/constants/media"test.describe.configure({ mode: "parallel" })@@ -125,6 +130,32 @@ test.describe("Load more button", () => {})await expect(page.locator(loadMoreButton)).not.toBeVisible()})++ /**+ * Checks that an analytics event is posted to /api/event and has the correct+ * payload for the REACH_RESULT_END event.+ */+ test(`Sends a valid analytics event when user reaches the load more page`, async ({+ page,+ context,+ }) => {+ const analyticsEvents = collectAnalyticsEvents(context)++ await goToSearchTerm(page, "cat")+ await expect(page.locator(loadMoreButton)).toBeVisible()++ const reachResultEndEvent = analyticsEvents.find(+ (event) => event.n === "REACH_RESULT_END"+ )++ if (reachResultEndEvent) {+ expectEventPayloadToMatch(reachResultEndEvent, {+ query: "cat",+ searchType: "all",+ resultPage: 1,+ })+ }+ })})}})diff --git a/frontend/test/playwright/utils/analytics.ts b/frontend/test/playwright/utils/analytics.tsnew file mode 100644index 000000000..f4693d56e--- /dev/null+++ b/frontend/test/playwright/utils/analytics.ts@@ -0,0 +1,39 @@+// Playwright utilities for making sure analytics events are sent correctly.+// Use collectAnalyticsEvents at the top of your test to collect all analytics events,+// and then expectEventPayloadToMatch to make sure a specific event(s) has the correct payload.++import { BrowserContext, expect } from "@playwright/test"++import type { EventName, Events } from "~/types/analytics"++export type EventResponse<T extends EventName> = {+ n: T+ p: Events[T]+}++export type AnalyticEventResponses = Array<EventResponse<EventName>>++export function expectEventPayloadToMatch<T extends EventName>(+ event: EventResponse<T>,+ expectedPayload: Events[T]+): void {+ expect(expectedPayload).toMatchObject(event.p)+}++export const collectAnalyticsEvents = (context: BrowserContext) => {+ const sentAnalyticsEvents: AnalyticEventResponses = []+ context.route("/api/event", (route, request) => {+ const postData = request.postData()+ if (postData) {+ const parsedData = JSON.parse(postData)+ const event = parsedData+ if (parsedData.p) {+ event.p = JSON.parse(parsedData.p)+ }+ sentAnalyticsEvents.push({ ...parsedData })+ }+ route.abort()+ })++ return sentAnalyticsEvents+}diff --git a/frontend/test/unit/specs/components/v-image-grid.spec.js b/frontend/test/unit/specs/components/v-image-grid.spec.jsindex 850e5058a..708286b25 100644--- a/frontend/test/unit/specs/components/v-image-grid.spec.js+++ b/frontend/test/unit/specs/components/v-image-grid.spec.js@@ -11,10 +11,11 @@ const propsData = {{ id: "i3", url: "http://localhost:8080/i3.svg", title: "image3" },],fetchState: {+ isSinglePage: true,isFetching: false,fetchingError: null,},- isSinglePage: false,+ isSinglePage: true,imageGridLabel: "Image Results",}@@ -26,12 +27,12 @@ describe("VImageGrid", () => {stubs: ["VLicense"],}})- it("renders images without load more button", () => {+ it("renders images without load more button for related images", () => {render(VImageGrid, options)expect(screen.queryAllByRole("img").length).toEqual(propsData.images.length)expect(screen.queryAllByRole("figure").length).toEqual(propsData.images.length)- expect(screen.queryByTestId("load-more")).not.toBeVisible()+ expect(screen.queryByTestId("load-more")).toBeNull()})})