Skip to content

Commit

Permalink
Feat: import sendAnalyticsEvent on demand (#2472)
Browse files Browse the repository at this point in the history
## What's the purpose of this pull request?

This PR is part of the Performance epic and aims to import the
`sendAnalyticsEvent` method from `faststore/sdk` dynamically instead of
static so that it will not be part of the initial bundle.

## How to test it?

1. run `yarn dev`.
2. Following the
https://developers.vtex.com/docs/guides/faststore/troubleshooting-analytics-and-partytown#see-events-pushed-to-datalayer

We need to put it in the console when we use the `partytown` to see the
events in the dataLayer:

```js
window.dataLayerHistory = []
const originalPush = dataLayer.push
dataLayer.push = (data) => {
  console.log(data)
  dataLayerHistory.push(data)
  originalPush(data)
}
```

3. Then navigate to the pages and double-check that the tags are being
triggered as before. Check the image below.
<img width="1906" alt="Screenshot 2024-09-20 at 18 46 46"
src="https://github.com/user-attachments/assets/89cc7f21-0663-441e-a24b-5f53b43984c5">

### Starter PR

- vtex-sites/starter.store#550

PSI Snapshot

<img width="897" alt="Screenshot 2024-09-25 at 18 11 24"
src="https://github.com/user-attachments/assets/87ca71e2-c184-4d08-a6d3-e219f95d1df6">
  • Loading branch information
eduardoformiga authored Oct 8, 2024
1 parent 52d1483 commit 8838ee8
Show file tree
Hide file tree
Showing 11 changed files with 239 additions and 225 deletions.
67 changes: 34 additions & 33 deletions packages/core/src/components/cart/CartItem/CartItem.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
import { sendAnalyticsEvent } from '@faststore/sdk'
import type {
AddToCartEvent,
CurrencyCode,
RemoveFromCartEvent,
} from '@faststore/sdk'
import {
CartItem as UICartItem,
CartItemImage as UICartItemImage,
CartItemSummary as UICartItemSummary,
} from '@faststore/ui'
import { useCallback, useMemo } from 'react'
import type {
AddToCartEvent,
CurrencyCode,
RemoveFromCartEvent,
} from '@faststore/sdk'

import { Image } from 'src/components/ui/Image'
import type { AnalyticsItem } from 'src/sdk/analytics/types'
import type { CartItem as ICartItem } from 'src/sdk/cart'
import { cartStore } from 'src/sdk/cart'
import { useRemoveButton } from 'src/sdk/cart/useRemoveButton'
import { useFormattedPrice } from 'src/sdk/product/useFormattedPrice'
import { useSession } from 'src/sdk/session'
import { useRemoveButton } from 'src/sdk/cart/useRemoveButton'
import type { CartItem as ICartItem } from 'src/sdk/cart'
import type { AnalyticsItem } from 'src/sdk/analytics/types'

function useCartItemEvent() {
const {
Expand All @@ -28,30 +27,32 @@ function useCartItemEvent() {
(item: Props['item'], quantity: number) => {
const quantityDelta = quantity - item.quantity

return sendAnalyticsEvent<
AddToCartEvent<AnalyticsItem> | RemoveFromCartEvent<AnalyticsItem>
>({
name: quantityDelta > 0 ? 'add_to_cart' : 'remove_from_cart',
params: {
currency: code as CurrencyCode,
// TODO: In the future, we can explore more robust ways of
// calculating the value (gift items, discounts, etc.).
value: item.price * Math.abs(quantityDelta),
items: [
{
item_id: item.itemOffered.isVariantOf.productGroupID,
item_name: item.itemOffered.isVariantOf.name,
item_brand: item.itemOffered.brand.name,
item_variant: item.itemOffered.sku,
quantity: Math.abs(quantityDelta),
price: item.price,
discount: item.listPrice - item.price,
currency: code as CurrencyCode,
item_variant_name: item.itemOffered.name,
product_reference_id: item.itemOffered.gtin,
},
],
},
import('@faststore/sdk').then(({ sendAnalyticsEvent }) => {
return sendAnalyticsEvent<
AddToCartEvent<AnalyticsItem> | RemoveFromCartEvent<AnalyticsItem>
>({
name: quantityDelta > 0 ? 'add_to_cart' : 'remove_from_cart',
params: {
currency: code as CurrencyCode,
// TODO: In the future, we can explore more robust ways of
// calculating the value (gift items, discounts, etc.).
value: item.price * Math.abs(quantityDelta),
items: [
{
item_id: item.itemOffered.isVariantOf.productGroupID,
item_name: item.itemOffered.isVariantOf.name,
item_brand: item.itemOffered.brand.name,
item_variant: item.itemOffered.sku,
quantity: Math.abs(quantityDelta),
price: item.price,
discount: item.listPrice - item.price,
currency: code as CurrencyCode,
item_variant_name: item.itemOffered.name,
product_reference_id: item.itemOffered.gtin,
},
],
},
})
})
},
[code]
Expand Down
37 changes: 19 additions & 18 deletions packages/core/src/components/cart/CartSidebar/CartSidebar.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { sendAnalyticsEvent } from '@faststore/sdk'
import {
Button as UIButton,
CartSidebar as UICartSidebar,
Expand Down Expand Up @@ -28,24 +27,26 @@ function useViewCartEvent() {
const { items, gifts, total } = useCart()

const sendViewCartEvent = useCallback(() => {
return sendAnalyticsEvent<ViewCartEvent>({
name: 'view_cart',
params: {
currency: code as CurrencyCode,
value: total,
items: items.concat(gifts).map((item) => ({
item_id: item.itemOffered.isVariantOf.productGroupID,
item_name: item.itemOffered.isVariantOf.name,
item_brand: item.itemOffered.brand.name,
item_variant: item.itemOffered.sku,
quantity: item.quantity,
price: item.price,
discount: item.listPrice - item.price,
import('@faststore/sdk').then(({ sendAnalyticsEvent }) => {
return sendAnalyticsEvent<ViewCartEvent>({
name: 'view_cart',
params: {
currency: code as CurrencyCode,
item_variant_name: item.itemOffered.name,
product_reference_id: item.itemOffered.gtin,
})),
},
value: total,
items: items.concat(gifts).map((item) => ({
item_id: item.itemOffered.isVariantOf.productGroupID,
item_name: item.itemOffered.isVariantOf.name,
item_brand: item.itemOffered.brand.name,
item_variant: item.itemOffered.sku,
quantity: item.quantity,
price: item.price,
discount: item.listPrice - item.price,
currency: code as CurrencyCode,
item_variant_name: item.itemOffered.name,
product_reference_id: item.itemOffered.gtin,
})),
},
})
})
}, [code, gifts, items, total])

Expand Down
28 changes: 16 additions & 12 deletions packages/core/src/components/search/SearchInput/SearchInput.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { SearchEvent, SearchState } from '@faststore/sdk'
import { sendAnalyticsEvent } from '@faststore/sdk'

import type {
SearchInputFieldProps as UISearchInputFieldProps,
Expand All @@ -22,7 +21,6 @@ import {
useState,
} from 'react'

import { formatSearchPath } from 'src/sdk/search/formatSearchPath'
import useSearchHistory from 'src/sdk/search/useSearchHistory'
import useSuggestions from 'src/sdk/search/useSuggestions'
import useOnClickOutside from 'src/sdk/ui/useOnClickOutside'
Expand All @@ -46,9 +44,11 @@ export type SearchInputRef = UISearchInputFieldRef & {
}

const sendAnalytics = async (term: string) => {
sendAnalyticsEvent<SearchEvent>({
name: 'search',
params: { search_term: term },
import('@faststore/sdk').then(({ sendAnalyticsEvent }) => {
sendAnalyticsEvent<SearchEvent>({
name: 'search',
params: { search_term: term },
})
})
}

Expand Down Expand Up @@ -119,13 +119,17 @@ const SearchInput = forwardRef<SearchInputRef, SearchInputProps>(
placeholder={placeholder}
onChange={(e) => setSearchQuery(e.target.value)}
onSubmit={(term) => {
const path = formatSearchPath({
term,
sort: sort as SearchState['sort'],
})

onSearchSelection(term, path)
router.push(path)
import('src/sdk/search/formatSearchPath').then(
({ formatSearchPath }) => {
const path = formatSearchPath({
term,
sort: sort as SearchState['sort'],
})

onSearchSelection(term, path)
router.push(path)
}
)
}}
onFocus={() => setSearchDropdownVisible(true)}
value={searchQuery}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { useEffect, useState, useMemo } from 'react'
import { useEffect, useMemo, useState } from 'react'

import type { CurrencyCode, ViewItemEvent } from '@faststore/sdk'
import { sendAnalyticsEvent } from '@faststore/sdk'

import { gql } from '@generated'
import type { AnalyticsItem } from 'src/sdk/analytics/types'
Expand All @@ -12,10 +11,10 @@ import Section from '../Section'

import styles from './section.module.scss'

import { usePDP } from '../../../sdk/overrides/PageProvider'
import { getOverridableSection } from '../../../sdk/overrides/getOverriddenSection'
import { useOverrideComponents } from '../../../sdk/overrides/OverrideContext'
import { usePDP } from '../../../sdk/overrides/PageProvider'
import { ProductDetailsDefaultComponents } from './DefaultComponents'
import { getOverridableSection } from '../../../sdk/overrides/getOverriddenSection'

export interface ProductDetailsProps {
productTitle: {
Expand Down Expand Up @@ -115,25 +114,27 @@ function ProductDetails({
} = product

useEffect(() => {
sendAnalyticsEvent<ViewItemEvent<AnalyticsItem>>({
name: 'view_item',
params: {
currency: currency.code as CurrencyCode,
value: price,
items: [
{
item_id: isVariantOf.productGroupID,
item_name: isVariantOf.name,
item_brand: brand.name,
item_variant: sku,
price,
discount: listPrice - price,
currency: currency.code as CurrencyCode,
item_variant_name: variantName,
product_reference_id: gtin,
},
],
},
import('@faststore/sdk').then(({ sendAnalyticsEvent }) => {
sendAnalyticsEvent<ViewItemEvent<AnalyticsItem>>({
name: 'view_item',
params: {
currency: currency.code as CurrencyCode,
value: price,
items: [
{
item_id: isVariantOf.productGroupID,
item_name: isVariantOf.name,
item_brand: brand.name,
item_variant: sku,
price,
discount: listPrice - price,
currency: currency.code as CurrencyCode,
item_variant_name: variantName,
product_reference_id: gtin,
},
],
},
})
})
}, [
isVariantOf.productGroupID,
Expand Down
21 changes: 11 additions & 10 deletions packages/core/src/sdk/analytics/hooks/usePageViewEvent.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import { useCallback, useEffect } from 'react'
import { useRouter } from 'next/router'
import { sendAnalyticsEvent } from '@faststore/sdk'
import type { PageViewEvent } from '@faststore/sdk'
import { useRouter } from 'next/router'
import { useCallback, useEffect } from 'react'

export const usePageViewEvent = () => {
const sendPageViewEvent = useCallback(() => {
sendAnalyticsEvent<PageViewEvent>({
name: 'page_view',
params: {
page_title: document.title,
page_location: location.href,
send_page_view: true,
},
import('@faststore/sdk').then(({ sendAnalyticsEvent }) => {
sendAnalyticsEvent<PageViewEvent>({
name: 'page_view',
params: {
page_title: document.title,
page_location: location.href,
send_page_view: true,
},
})
})
}, [])

Expand Down
42 changes: 22 additions & 20 deletions packages/core/src/sdk/analytics/hooks/useViewItemListEvent.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { sendAnalyticsEvent } from '@faststore/sdk'
import { useCallback } from 'react'
import type { CurrencyCode, ViewItemListEvent } from '@faststore/sdk'

Expand All @@ -25,25 +24,28 @@ export const useViewItemListEvent = ({
} = useSession()

const sendViewItemListEvent = useCallback(() => {
sendAnalyticsEvent<ViewItemListEvent<AnalyticsItem>>({
name: 'view_item_list',
params: {
item_list_name: title,
item_list_id: title,
items: products.map(({ node: product }, index) => ({
item_id: product.isVariantOf.productGroupID,
item_name: product.isVariantOf.name,
item_brand: product.brand.name,
item_variant: product.sku,
price: product.offers.offers[0].price,
index: page * pageSize + index + 1,
discount:
product.offers.offers[0].listPrice - product.offers.offers[0].price,
currency: code as CurrencyCode,
item_variant_name: product.name,
product_reference_id: product.gtin,
})),
},
import('@faststore/sdk').then(({ sendAnalyticsEvent }) => {
sendAnalyticsEvent<ViewItemListEvent<AnalyticsItem>>({
name: 'view_item_list',
params: {
item_list_name: title,
item_list_id: title,
items: products.map(({ node: product }, index) => ({
item_id: product.isVariantOf.productGroupID,
item_name: product.isVariantOf.name,
item_brand: product.brand.name,
item_variant: product.sku,
price: product.offers.offers[0].price,
index: page * pageSize + index + 1,
discount:
product.offers.offers[0].listPrice -
product.offers.offers[0].price,
currency: code as CurrencyCode,
item_variant_name: product.name,
product_reference_id: product.gtin,
})),
},
})
})
}, [code, products, title, page, pageSize])

Expand Down
Loading

0 comments on commit 8838ee8

Please sign in to comment.